1. 說明java
Android手機開機後,會發送android.intent.action.BOOT_COMPLETED廣播,監聽這個廣播就能監聽開機。android
2. 代碼ide
<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. 問題spa
Android API Level8以上的時候,程序能夠安裝在SD卡上。若是程序安裝在SD卡上,那麼在BOOT_COMPLETED廣播發送以後,SD卡纔會掛載,所以程序沒法監聽到該廣播。rest
4. 解決
code
監聽SD卡的掛載。orm
5. 同時監聽的Intent-Filter問題get
若是BOOT_COMPLETED和MEDIA_MOUNTED,MEDIA_EJECT寫在同一個intent-filter中,那麼沒法檢測到BOOT_COMPLETED,對於沒有SD卡的手機,只能檢測BOOT_COMPLETED,這樣就會致使沒法檢測到開機了。string
<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>