Android 系统在完成启动后,会发射一个ACTION_BOOT_COMPLETED的广播,并且这个广播只有系统才能发送,来广播系统启动已完成,因此我们如果可以在APP内拦截这个广播的话,就可以让APP做到开机自启动。
1. 拦截这个通知需要在AndroidManifest.xml中增加指定权限:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
2. 自定义BroadcastReceiver 来接收BOOT_COMPLETE广播
public class BootCompletedReceiver extends BroadcastReceiver {
private static final StringTAG="TS.BootCompletedReceiver";
@Override
public void onReceive (Context context, Intent intent) {
Log.d(TAG,"boot completed");
//Do the thing u want to do, generally start stubActivity to load the HomePage and then skip to the homeActivity
}
}
3.在AndroidManifest.xml文件中声明自定义的BootCompletedReceiver,申明intent filter的值。
<receiver android:name=".BootCompletedReceiver"
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
/>