使用广播方式
public class BootBroadcastReceiver extends BroadcastReceiver {
//先获取相关权限
private void startPermissionActivity(Context context) {
ComponentName name = new ComponentName(context.getApplicationInfo().processName, PermissionActivity.class.getName());
Intent intentMain = new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
intentMain.setComponent(name);
try {
context.startActivity(intentMain);
} catch (Exception ex) {
android.util.Log.e("BootStartReceiver", "bootStart.startActivity faild", ex);
}
}
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(Intent.ACTION_BOOT_COMPLETED)) {
// better delay some time.
handlerThread = new HandlerThread("startThread");
handlerThread.start();
handler = new Handler(handlerThread.getLooper());
handler.postDelayed(new Runnable() {
@Override
public void run() {
startPermissionActivity(context);
}
},1000 * 10);
}
}
}
在Manifest文件中定义该Broadcast Receiver
<receiver
android:name=".receiver.BootBroadcastReceiver"
android:enabled="true"
android:exported="true"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
加上所需权限
<uses-permission android:name=”android.permission.RECEIVE_BOOT_COMPLETED” />