Compiling the Android operating system in the simulator can help us implement the auto-start function of the application at startup. Here, we will use a piece of code to fully master the implementation of Android boot auto-start, to help you master this application.
1. Define a BroadcastReceiver
Java code
- public class BootReceiver extends BroadcastReceiver {
- public void onReceive(Context ctx, Intent intent) {
- Log.d("BootReceiver", "system boot completed");
- //start activity
- String action="android.intent.action.MAIN";
- String category="android.intent.category.LAUNCHER";
- Intent myi=new Intent(ctx,CustomDialog.class);
- myi.setAction(action);
- myi.addCategory(category);
- myi.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
- ctx.startActivity(myi);
- //start service
- Intent s=new Intent(ctx,MyService.class);
- ctx.startService(s);
- }
- }
- public class BootReceiver extends BroadcastReceiver {
- public void onReceive(Context ctx, Intent intent) {
- Log.d("BootReceiver", "system boot completed");
- //start activity
- String action="android.intent.action.MAIN";
- String category="android.intent.category.LAUNCHER";
- Intent myi=new Intent(ctx,CustomDialog.class);
- myi.setAction(action);
- myi.addCategory(category);
- myi.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
- ctx.startActivity(myi);
- //start service
- Intent s=new Intent(ctx,MyService.class);
- ctx.startService(s);
- }
- }
2. Configure the license for the consumer to allow the system to receive startup messages. In AndroidManifest. xml:
Xml Code
- < uses-permission android:name=
"android.permission.RECEIVE_BOOT_COMPLETED"/>
- < uses-permission android:name=
"android.permission.RECEIVE_BOOT_COMPLETED"/>
3. Configure the consumer er to receive system startup messages. In AndroidManifest. xml
Xml code for Android auto-start
- < receiver android:name=".app.BootReceiver">
- < intent-filter>
- < action android:name="android.intent.action.BOOT_COMPLETED"/>
- < category android:name="android.intent.category.HOME" />
- < /intent-filter>
- < /receiver>
- < receiver android:name=".app.BootReceiver">
- < intent-filter>
- < action android:name="android.intent.action.BOOT_COMPLETED"/>
- < category android:name="android.intent.category.HOME" />
- < /intent-filter>
- < /receiver>
4. Start the simulator. A dialog box is displayed after the system is started.
This section describes how to enable Android boot automatically.