工作過程中遇到一個需求,要求手機重啓之後,自己寫的APP中的服務生效
思考:
- 要想自己APP中的服務生效,必須先啓動APP
- 問題轉化成手機重啓之後 將自己開發的APP 自主啓動起來
- 手機重啓/開機完成後,系統會有一個啓動完成的廣播 ACTION_BOOT_COMPLETED
- 在我的APP中監聽這個廣播,收到廣播 意味着手機完成重啓/開機,然後把自己的APP調用起來
實操:
首先需要再AndroidManifest.xml中添加接收重啓的權限,並註冊一個廣播接收器
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<!--在 application標籤下-->
<receiver android:name=".BootBroadcastReceiver">
<intent-filter android:priority="1000">
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</receiver>
廣播接收中監聽 ACTION_BOOT_COMPLETED,監聽到之後 就啓動項目的入口Activity
public class BootBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(Intent.ACTION_BOOT_COMPLETED)) {
Intent intent2 = new Intent(context,MainActivity.class);
context.startActivity(intent2);
}
}
}