本文主要介紹Android應用如何開機自啓動、自啓動失敗的緣由、adb命令發送BOOT_COMPLETED。
問題:應用程序是否能夠在安裝後自啓動,沒有ui的純service應用如何啓動?答案立刻揭曉^_*
一、Android應用如何開機自啓動
(1)、在AndroidManifest.xml中註冊html
AndroidManifest.xml中註冊BOOT_COMPLETED Action android
注意不只要添加android.intent.action.BOOT_COMPLETED對應的action,還須要添加對應的uses-permissionshell
(2)、Receiver接收廣播進行處理安全
Javaapp
public class BootBroadcastReceiver extends BroadcastReceiver { public static final String TAG = "BootBroadcastReceiver"; @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction().toString(); if (action.equals(Intent.ACTION_BOOT_COMPLETED)) { // u can start your service here Toast.makeText(context, "boot completed action has got", Toast.LENGTH_LONG).show(); return; } } }ide
1測試 2ui 3spa 4xml 5 6 7 8 9 10 11 12 13 14 |
public class BootBroadcastReceiver extends BroadcastReceiver {
public static final String TAG = "BootBroadcastReceiver";
@Override public void onReceive(Context context, Intent intent) { String action = intent.getAction().toString(); if (action.equals(Intent.ACTION_BOOT_COMPLETED)) { // u can start your service here Toast.makeText(context, "boot completed action has got", Toast.LENGTH_LONG).show(); return; } } } |
二、自啓動失敗的緣由
接收不到BOOT_COMPLETED廣播可能的緣由
(1)、BOOT_COMPLETED對應的action和uses-permission沒有一塊兒添加
(2)、應用安裝到了sd卡內,安裝在sd卡內的應用是收不到BOOT_COMPLETED廣播的
(3)、系統開啓了Fast Boot模式,這種模式下系統啓動並不會發送BOOT_COMPLETED廣播
(4)、應用程序安裝後重來沒有啓動過,這種狀況下應用程序接收不到任何廣播,包括BOOT_COMPLETED、ACTION_PACKAGE_ADDED、CONNECTIVITY_ACTION等等。
Android3.1以後,系統爲了增強了安全性控制,應用程序安裝後或是(設置)應用管理中被強制關閉後處於stopped狀態,在這種狀態下接收不到任何廣播。直到被啓動過(用戶打開或是其餘應用調用)纔會脫離這種狀態,因此Android3.1以後
(1)、應用程序沒法在安裝後本身啓動
(2)、沒有ui的程序必須經過其餘應用激活才能啓動,如它的Activity、Service、Content Provider被其餘應用調用。
存在一種例外,就是應用程序被adb push you.apk /system/app/下是會自動啓動的,不處於stopped狀態。
具體說明見:
http://developer.android.com/about/versions/android-3.1.html#launchcontrols
http://commonsware.com/blog/2011/07/13/boot-completed-regression-confirmed.html
三、adb發送BOOT_COMPLETED
咱們能夠經過
adb shell am broadcast -a android.intent.action.BOOT_COMPLETED
1 |
adb shell am broadcast -a android.intent.action.BOOT_COMPLETED |
命令發送BOOT_COMPLETED廣播,而不用重啓測試機或模擬器來測試BOOT_COMPLETED廣播,這條命令能夠更精確的發送到某個package,以下:
adb shell am broadcast -a android.intent.action.BOOT_COMPLETED -c android.intent.category.HOME -n package_name/class_name
1 |
adb shell am broadcast -a android.intent.action.BOOT_COMPLETED -c android.intent.category.HOME -n package_name/class_name |