Preparation During device start-up, system will broadcast an event named android.intent.action.BOOT_COMPLETED, this event only be sent once.
Implement
Define a class derived from BroadcaseReceiver, and overloads member function onReceiveIntent to launch service or activity.
package com.mypackage
import android.content.BroadcastReceiver; import android.content.Content; import android.content.Intent; public class MyReceiver extends BroadcastReceiver { public void onReceive(Context context, Intent intent) { if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) { //Phase 1: Launch a servie Intent service = new Intent(yourService.ACTION_START); service.setClass(context, yourService.class); context.startService(service);
//Phase 2: Launch an activity Intent newIntent = new Intent(this, MyActivity.class); newIntent.setAction("android.intent.action.MAIN"); //MyActivity action defined in AndroidManifest.xml newIntent.setCategory("android.intent.category.LAUNCHER");//MyActivity category defined in AndroidManifest.xml
newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //If activity is
not launched in Activity environment, this flag is mandatory to set context.startActivity(newIntent); } } }
Modify AndroidManifest.xml to add "receiver" elements and declare required permission.
package="com.mypackage">
Bug Scrub
If you implement a single instance activity. After you reboot handset, the activity is started by receiver automatically, but when you click app icon in Program list (Or click app icon in status bar if applicatin supports such notification), the activity is restarted.
Solution: That may caused by configuration changing, if so, you can append "mcc|mnc|" to the attribute android:configChanges in your Activity element in AndroidManefest.xml. If the previous solution can't solve the issue, try to add more available value to android:configChanges.