關於Android3.1后Boot_COMPLETED廣播不響應的問題見ALEX的文章:Android3.1后Boot_COMPLETED廣播不響應的問題
感謝ALEX的指正。
android系統在Manifest.permission中有這樣一條RECEIVE_BOOT_COMPLETED的定義,當你自己的程序加入這個權限后,就可以在系統啟動完畢后收到一條系統的廣播,這個廣播的標志為ACTION_BOOT_COMPLETED,因此我們只要定義一個BroadcastReceiver用來接收這個廣播,然后加入自定義的動作即可。代碼如下:
- public class LocationLoggerServiceManager extends BroadcastReceiver {
- public static final String TAG = "customTag";
- @Override
- public void onReceive(Context context, Intent intent) {
- if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
- ComponentName comp = new ComponentName(context.getPackageName(), MainActivity.class.getName());
- context.startActivity(new Intent().setComponent(comp).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
- } else {
- Log.e(TAG, "Received unexpected intent " + intent.toString());
- }
- }
- }
在AndroidManifest.xml中加入這個類的定義和權限說明
- <receiver
- android:name=".LocationLoggerServiceManager"
- android:enabled="true"
- android:exported="false"
- android:label="LocationLoggerServiceManager">
- <intent-filter>
- <action
- android:name="android.intent.action.BOOT_COMPLETED" />
- </intent-filter>
- </receiver>
- <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
OK,大功告成。這里演示的是啟動一個activity,同理你也可以啟動一個service.
REFERENCES:http://blog.csdn.net/roadog2006/article/details/5477294