开机自启有很多种办法,下面用广播的方式实现。
1、首先先创建广播,开机代码
/**
* Created by Forrest.
* User: Administrator
* Date: 2023/3/6
* Description:
*/
public class BootCompleteReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// TODO: This method is called when the BroadcastReceiver is receiving
// an Intent broadcast.
if(Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
Intent thisIntent = new Intent(context, MainActivity.class);
thisIntent.setAction("android.intent.action.MAIN");
thisIntent.addCategory("android.intent.category.LAUNCHER");
thisIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(thisIntent);
}
}
}
2、在清单文件里面注册,同时添加权限文章来源:https://uudwc.com/A/ABw4w
<!-- .开机自启广播 -->
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<receiver
android:name=".BootCompleteReceiver"
android:enabled="true"
android:exported="true">
<!-- 接收启动完成的广播 -->
<intent-filter android:priority="1000">
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
完成文章来源地址https://uudwc.com/A/ABw4w