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. 參考
Android開機廣播和關機廣播
http://stackoverflow.com/questions/2784441/trying-to-start-a-service-on-boot-on-android
監聽SD卡的掛載
android 同時監聽 boot completed 和 media mounted的廣播
6. 本文連結
http://blog.csdn.net/xiaodongrush/article/details/9616113