1. 说明
Android手机开机后,会发送android.intent.action.BOOT_COMPLETED广播,监听这个广播就能监听开机。
2. 代码
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<receiver android:name="com.example.restarttest.BootupReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
public class BootupReceiver extends BroadcastReceiver { private final String ACTION_BOOT = "android.intent.action.BOOT_COMPLETED"; @Override public void onReceive(Context context, Intent intent) { if (ACTION_BOOT.equals(intent.getAction())) Toast.makeText(context, R.string.bootup_receiver, Toast.LENGTH_SHORT).show(); } }
3. 问题
Android API Level8以上的时候,程序可以安装在SD卡上。如果程序安装在SD卡上,那么在BOOT_COMPLETED广播发送之后,SD卡才会挂载,因此程序无法监听到该广播。
4. 解决
监听SD卡的挂载。
5. 同时监听的Intent-Filter问题
如果BOOT_COMPLETED和MEDIA_MOUNTED,MEDIA_EJECT写在同一个intent-filter中,那么无法检测到BOOT_COMPLETED,对于没有SD卡的手机,只能检测BOOT_COMPLETED,这样就会导致无法检测到开机了。
<receiver android:name=".com.example.restarttest.BootupReceiver" >
<intent-filter android:priority="1000" >
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
<intent-filter android:priority="1000" >
<action android:name="android.intent.action.MEDIA_MOUNTED" />
<action android:name="android.intent.action.MEDIA_EJECT" />
<data android:scheme="file" />
</intent-filter>
</receiver>
5. 参考
http://stackoverflow.com/questions/2784441/trying-to-start-a-service-on-boot-on-android
android 同时监听 boot completed 和 media mounted的广播
6. 本文链接