Saturday, January 27, 2018

How to create auto start android app code example


Welcome to droid-tech

 To start your Activity/Service on device boot complete we need system broadcast receiver with action action android:name="android.intent.action.BOOT_COMPLETED"
We will see it in below steps.

1. Create a BootupBroadcastReceiver by extending BroadcastReceiver Class.

package com.droidtech.autostart_bootup;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

/** * Created by Droid-Tech on 1/27/2018. */
public class BootupBroadcastReceiver extends BroadcastReceiver {
    @Override    public void onReceive(Context context, Intent intent) {
        // Write down necessary code in our case we need to start an activity  
      context.startActivity(new Intent().setClass(context, MainActivity.class)
      .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));

    }
}
When device boot completed onReceive() method will be called.

2. Register your broadcast receiver so that system will know to fire your broadcast. To register it we have to register it in manifest so it should work,

BroadcastReceiver need to register with <receiver> tag in manifest as below.
this should be enclosed in <application></application> tag.

    <receiver android:name=".BootupBroadcastReceiver" android:enabled="true"
        android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </receiver>    

3.Permission in order to getting it working it requires permission.

Add below permission to manifest.

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> 

Now you are good to go.

MainActivity.java is as below.

package com.droidtech.autostart_bootup;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

/** * @author droid-tech */public class MainActivity extends AppCompatActivity {

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

Now go ahead and test your app! Good Luck

No comments:

Post a Comment