標籤:bsp als ted stat extends start int java blog
(1)首先添加許可權開機啟動許可權
<!--開機啟動許可權--> <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
(2)註冊一個BroadcastReceiver來檢測android系統開機時發出的開機廣播
package com.wxyz.dengchaoqun.testswf;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;/** * Created by 鄧超群 on 2017/2/4. *///開機自啟動廣播接受public class AutoStartBroadcastReceiver extends BroadcastReceiver { static final String action_boot ="android.intent.action.BOOT_COMPLETED"; @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(action_boot)){ Intent sayHelloIntent=new Intent(context,MainActivity.class); sayHelloIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(sayHelloIntent); } }}
這裡要強調的是,開機啟動可以啟動app的Activity也可以啟動服務,這就看app的具體需求了,我這裡是啟動的MainActivity
(3)在設定檔裡面註冊服務
<!-- 開機自啟動廣播接受 --> <receiver android:name=".AutoStartBroadcastReceiver" > <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED" /> <category android:name="android.intent.category.HOME"/> </intent-filter> </receiver>
Android中app開機自啟動的開發