Android 开机广播实现开机自启应用
1、具体实现
- 新增广播接收器
java
public class BootReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (!Intent.ACTION_BOOT_COMPLETED.equals(action)
&& !Intent.ACTION_LOCKED_BOOT_COMPLETED.equals(action)) {
return;
}
Intent launchIntent = new Intent(context, MainActivity.class);
launchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(launchIntent);
}
}
- Manifest 注册
xml
<receiver
android:name=".boradcast.BootReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.LOCKED_BOOT_COMPLETED" />
</intent-filter>
</receiver>
-
开机流程如下
设备开机完成
系统发送 BOOT_COMPLETED
拉起应用进程
BootReceiver.onReceive 执行
startActivity(MainActivity)
应用恢复到主界面并继续初始化
2、注意事项
-
普通 Android 10+ 设备,用这种广播里直接启动 MainActivity 的方式,大多数会被拦掉
-
这是定制设备可用的方案,不是所有 Android 设备都能保证开机自启应用