赞
踩
在Android系统开启之后,目标app可以在系统开机之后启动。
使用广播的方式
首先我们要创建一个广播(这里是启动了一个Service服务)
public class BootReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
Intent myIntent = new Intent(context, MyForegroundService.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//Android 8.0以上调用
context.startForegroundService(myIntent);
} else {
context.startService(myIntent);
}
}
}
}
然后需要在【AndroidManifest.xml】注册清单里面
1.添加权限
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
2.注册
<receiver
android:name=".receiver.BootReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
ps:这里也可以启动一个Activity
public class BootReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
Intent i = new Intent(context, MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
}
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。