**:
有些時候,應用需要在開機時就自動執行,例如某個自動從網上更新內容的後台service。怎樣實現開機自動執行的應用?在撰寫本文時,聯想到高煥堂先生以「don't call me, i'll call you back!」總結android框架,真是說到點子上了。理解這句話的含義,許多有關android平台上實現某種功能的問題,都能迎刃而解。
手機開機後,自動執行程式。
當android啟動時,會發出乙個系統廣播,內容為action_boot_completed,它的字串常量表示為android.intent.action.boot_completed。只要在程式中「捕捉」到這個訊息,再啟動之即可。記住,android框架說:don't call me, i'll call you back。我們要做的是等到接收這個訊息,而實現的手段就是實現乙個broadcastreceiver。 ? 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package
com.example;
import
import
android.content.dialoginte***ce;
import
android.os.bundle;
import
android.view.*;
import
android.widget.toast;
public
class
mainactivity
extends
activity
? 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package
com.example;
import
android.content.broadcastreceiver;
import
android.content.context;
import
android.content.intent;
/**
* created with intellij idea.
* user: 郟高陽
* date: 13-6-5
* time: 下午8:25
* to change this template use file | settings | file templates.
*/
public
class
bootbroadcastreceiver
extends
broadcastreceiver
}
}
該類派生自broadcastreceiver,覆載方法onreceive中,檢測接收到的intent是否符合boot_completed,如果符合,則啟動mainactivity。在 ? 1
2
3
4
5
<
receiver
android:name
=
".bootbroadcastreceiver"
>
<
intent-filter
>
<
action
android:name
=
"android.intent.action.boot_completed"
/>
向系統註冊了乙個receiver,子節點intent-filter表示接收android.intent.action.boot_completed訊息。
在多數情況下,要自動執行的不是有介面的程式,而是在後台執行的service。此時,就要用startservice來啟動相應的service了。
2、自啟動失敗的原因
具體說明見:
3、adb傳送boot_completed
我們可以通過
1
adb
shell
am broadcast-a
android
.intent
.action
.boot_completed
命令傳送boot_completed廣播,而不用重啟測試機或模擬器來測試boot_completed廣播,這條命令可以更精確的傳送到某個package,如下:
1adb
shell
am broadcast-a
android
.intent
.action
.boot_completed-c
android
.intent
.category
.home-n
package_name
/class_name
Android開機自啟動詳解
如果需要在android開機時自動啟動應用程式,可以通過響應android.intent.action.boot completed廣播訊息來實現,android系統啟動結束時,會發出 android.intent.action.boot completed 訊息。要實現開機自啟動應用或servic...
Android 開機自啟動應用
分享一下我老師大神的人工智慧教程!零基礎,通俗易懂!android啟動時,會發出乙個系統廣播 action boot completed,它的字串常量表示為 android.intent.action.boot completed 開機自啟動程式,只需要 捕捉 到這個訊息再啟動你的程式即可,我們要做...
Android應用如何開機自啟動 自啟動失敗原因
問題 應用程式是否可以在安裝後自啟動,沒有ui的純service應用如何啟動?1 android應用如何開機自啟動 1 在androidmanifest.xml中註冊androidmanifest.xml中註冊boot completed action 注意不僅要新增android.intent.a...