Android 应用开机启动
安卓10.0之前可用的开机启动方式
在Android中,想要实现开机启动,必须要拦截开机的广播android.permission.RECEIVE_BOOT_COMPLETED。并且需要静态注册该广播和添加权限<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
- AndroidManifest.xml中定义广播和声明权限
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application>
...
<activity
android:name=".view.main.MainActivity"
android:configChanges="keyboardHidden|orientation|screenSize"
android:exported="true"
android:screenOrientation="userLandscape">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".receiver.BootReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
-
广播中启动
MainActivityclass BootReceiver : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { if (Intent.ACTION_BOOT_COMPLETED == intent.action) { LogUtils.i("---开机启动---") context.startActivity(Intent(context, MainActivity::class.java).apply { addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) }) } } }
安卓4.0以后,应用必须要手动启动一次才能有效。
失败可能的原因
检查手机是否被360之类的安全软件限制的自启动,或者本机自带的手机管家。如果有在自启动软件管理中设置成【允许】。
HUAWEI MatePad 平板 HarmonyOS 3.0.0 型号:BAH3-W59的画面
如果还是失败,那么请检查你的手机是不是设置了app安装首选位置是sd卡,据说安装到sd卡的话,因为手机启动成功后(发送了启动完成的广播后)才加载sd卡,所以app接收不到广播。如果是的话,把app安装到内部存储试试。如果不懂得设置的话,那么直接在AndroidManifest.xml文件中设置安装路径,android:installLocation=“internalOnly”。
安卓10及以上的开机启动方式
基本步骤与上方一致,需要多一个步骤,关闭电池优化
private fun isIgnoringBatteryOptimizations(): Boolean {
val powerManager = getSystemService(Context.POWER_SERVICE) as PowerManager
val isIgnoring = powerManager.isIgnoringBatteryOptimizations(packageName)
LogUtils.i("是否已经忽略电池优化:$isIgnoring")
return isIgnoring
}
private fun ignoringBatteryOptimizations() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
if (!isIgnoringBatteryOptimizations()) {
startActivity(Intent().apply {
action = Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS
data = Uri.parse("package:${packageName}")
})
}
}
}