Android设备开机的时候,会发送android.intent.action.BOOT_COMPLETED的广播。通过注册广播监听这个Action,然后启动Activity或Servcie。
第一步:创建Service和BrocastReceiver
第二步:在AndroidManifest.xml 注册service 和BroadcastReceiver
<receiver android:name=".receiver.BootBroadcastReceiver">
<intent-filter android:priority="1000">
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<action android:name="android.media.AUDIO_BECOMING_NOISY" />
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</receiver>
<service android:name=".service.AppService"
android:exported="true">
</service>
<activity android:name=".TestActivity"/>
(注:android.media.AUDIO_BECOMING_NOISY是开机声音的广播)
第三步:添加权限
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
第四步:在BrocastReceiver中启动Service或者应用
public class BootBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
//启动Service
if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)||
intent.getAction().equals("android.media.AUDIO_BECOMING_NOISY") ){
Log.e("","BootBroadcastReceiver AppServic. start");
// Intent serviceIntent = new Intent(context, AppService.class);
// context.startService(serviceIntent);
Intent newIntent = new Intent(context,TestActivity.class);
newIntent.setAction("android.intent.action.MAIN");
newIntent.addCategory("android.intent.category.LAUNCHER");
newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //注意,必须添加这个标记,否则启动会失败
context.startActivity(newIntent);
}
}
}
运行后发现没有开机启动。然后开始找原因,原来是Android3.1之后,系统为了加强了安全性控制,应用程序安装后或是(设置)应用管理中被强制关闭后处于stopped状态,在这种状态下接收不到任何广播。对于android3.1以后版本,如果要应用接收开机广播有两种方法:
a).将应用预置到/system/app/目录。
具体方法可参考:https://blog.csdn.net/PursuingD/article/details/51820700
b).安装应用后先启动一次。
哪位有更好的方法,可以留言告知一声,谢谢!