During this period of time, we were engaged in basic Android development. Now we need to start the system and follow some blog posts on the Internet to find that it has never been successful, when the server is started, it always prompts that the started application is accidentally terminated. Therefore, after referring to the Android SDK doc and finally solving the problem, I will share my experience with you.
Android boot Activity or Service method
Principle]
After the Android system completes the BOOT phase, it will send a broadcast named ACTION_BOOT_COMPLETED. We can capture this broadcast in a BroadcastReceiver and then start our Activity or Service, of course, we must note that our application must have the permission to capture the broadcast. See the specific steps below:
[Step 1] First, you must have an Activity or Service for startup. Here we will explain the simplest Activity created by the system.
[Step 2] compile a BroadcastReceiver to capture the broadcast ACTION_BOOT_COMPLETED and start the Activity to be started after the capture.
Note: you must addIntent. FLAG_ACTIVITY_NEW_TASKMark. Because each Activity must be created in a job stack, this flag specifies the Startup Mode of the Activity, which means to start in a new job stack. When startActivity is used to start a new Activity, Intent has the default startup mode. When the startActivity method is called outside the Activity, there is no default start mode. For example, in service or broadcastReceiver, you must specify a Startup Mode for the Activity.
- Import android. content. BroadcastReceiver;
- Import android. content. Context;
- Import android. content. Intent;
-
- Public class BootCompletedReceiver extends BroadcastReceiver {
- @ Override
- Public void onReceive (Context context, Intent intent ){
- If (intent. getAction (). equals (Intent. ACTION_BOOT_COMPLETED ))
- {
- Intent newIntent = new Intent (context, BootTestActivity. class );
- NewIntent. addFlags (Intent. FLAG_ACTIVITY_NEW_TASK); // note that this flag must be added; otherwise, the startup will fail.
- Context. startActivity (newIntent );
- }
- }
- }
[Step 3] register our BroadcastReceiver in the AndroidManifest. xml configuration file
[Step 4] Add the permission to allow us to capture the broadcast in the AndroidManifest. xml configuration file.
Restart the virtual machine.
The AndroidManifest. xml is attached below for your understanding and reference.