(1)首先添加权限开机启动权限
<!--开机启动权限--> <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
(2)注册一个BroadcastReceiver来检测android系统开机时发出的开机广播
package com.wxyz.dengchaoqun.testswf; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; /** * Created by 邓超群 on 2017/2/4. */ //开机自启动广播接受 public class AutoStartBroadcastReceiver extends BroadcastReceiver { static final String action_boot ="android.intent.action.BOOT_COMPLETED"; @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(action_boot)){ Intent sayHelloIntent=new Intent(context,MainActivity.class); sayHelloIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(sayHelloIntent); } } }
这里要强调的是,开机启动可以启动app的Activity也可以启动服务,这就看app的具体需求了,我这里是启动的MainActivity
(3)在配置文件里面注册服务
<!-- 开机自启动广播接受 --> <receiver android:name=".AutoStartBroadcastReceiver" > <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED" /> <category android:name="android.intent.category.HOME"/> </intent-filter> </receiver>
时间: 2024-10-22 03:35:31