Recipe 1.6 Auto-Launching Your Application at Boot Time
If you need to automatically start your application whenever the device starts up, you need to register a BroadcastReceiver. This recipe shows you how.
Solution
To auto-launch your app during device boot-up, add a new class to your package and ensure that it extends the BroadcastReceiver base class. The following BootupReceiver class is an example:
package net.learn2develop.autostartapp;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class BootupReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "App started", Toast.LENGTH_LONG).show();
//---start the main activity of our app---
Intent i = new Intent(context,MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
}
When the device boots up, it will fire this broadcast receiver and call the onReceiver() method. To display your activity when the device boots up, you will use an Intent object. Remember to add the FLAG_ACTIVITY_NEW_TASK flag to the Intent object.
To register the broadcast receiver, you need to add the <receiver> element to the AndroidManifest.xml file. You also need the RECEIVE_BOOT_COMPLETED permission: ...
Get Android Application Development Cookbook: 93 Recipes for Building Winning Apps now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.