环境配置
- jdk1.8
- compileSdk 34
- minSdk 31
- targetSdk 33
代码
AndroidManifest.xml
java
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application>
<receiver
android:name=".receiver.BootBroadcastReceiver"
android:enabled="true"
android:exported="true"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
<intent-filter android:priority="1000">
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
</application>
自定义BootBroadcastReceiver(开机广播接收)
java
/**
* 开机自启动广播接收
*/
public class BootBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
Toast.makeText(context, "QZ-APP接收到开机广播", Toast.LENGTH_LONG);
Log.i("BootBroadcastReceiver", "QZ-APP接收到开机广播");
// Intent newIntent = new Intent(context, MainActivity.class); // 要启动的Activity
//1.如果自启动APP,参数为需要自动启动的应用包名
Intent newIntent = context.getPackageManager().getLaunchIntentForPackage(context.getPackageName());
//下面这句话必须加上才能开机自动运行app的界面
newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//2.如果自启动Activity
context.startActivity(newIntent);
//3.如果自启动服务
// context.startService(newIntent);
}
}
}