1、写一个BroadcastReceiver,重写onReceive方法:
StringACTION_BOOT="android.intent.action.BOOT_COMPLETED";//开机
onReceive(Context context,Intent intent){
if(ACTION_BOOT.equals(intent.getAction())){
Intent startIntent =newIntent(context,MainActivity.class);//接收到广播后,跳转到MainActivity(或Service)
startIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(startIntent);
}
}
2、添加权限:
<uses-permissionandroid:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
3、注册BroadcastReceiver,添加过滤条件:
<intent-filter>
<actionandroid:name="android.intent.action.BOOT_COMPLETED"/>
<categoryandroid:name="android.intent.category.HOME"/>
</intent-filter>