前言
應(yīng)用自啟動(dòng)主要是通過(guò)接收系統(tǒng)廣播BOOT_COMPLETED來(lái)實(shí)現(xiàn)的,在receiver中執(zhí)行APP啟動(dòng)的方法。
實(shí)現(xiàn)
主要分為兩個(gè)部分:
- AndroidManifest.xml配置,包括權(quán)限配置和廣播注冊(cè)。
- 廣播中添加應(yīng)用啟動(dòng)的代碼。
1. 權(quán)限添加
在AndroidManifest.xml文件中添加BOOT監(jiān)聽(tīng)權(quán)限:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
2. 安裝方式配置
在manifest根目錄下設(shè)置為安裝方式:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
...
android:installLocation="internalOnly">
設(shè)置為將應(yīng)用安裝到內(nèi)部存儲(chǔ)中,安裝在SD卡中可能會(huì)導(dǎo)致自啟動(dòng)失敗。
3. 廣播注冊(cè)
AndroidManifest.xml文件中注冊(cè)廣播:
<receiver
android:name=".receiver.BootReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
4. receiver中添加應(yīng)用啟動(dòng)邏輯
示例代碼如下:
class BootReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
if (intent == null) return
if (TextUtils.equals(intent.action, "android.intent.action.BOOT_COMPLETED")) {
val newIntent = Intent(context, MainActivity::class.java)
ContextCompat.startActivity(context, newIntent, null)
}
}
}
設(shè)置一下應(yīng)用啟動(dòng)邏輯。
5. 問(wèn)題說(shuō)明
在執(zhí)行如上步驟之后,在模擬器運(yùn)行已經(jīng)可以啟動(dòng)后應(yīng)用重啟。
但是在手機(jī)上測(cè)試可以會(huì)無(wú)法啟動(dòng),原因是手機(jī)上可能安裝有手機(jī)管家之類的軟件。需要在其中將當(dāng)前應(yīng)用的自啟動(dòng)選項(xiàng)打開(kāi)才能生效。
總結(jié)
Android開(kāi)機(jī)自啟動(dòng)示例