启动不可见活动以获取服务权限

时间:2018-12-16 20:51:28

标签: android android-5.0-lollipop android-permissions boot

感谢大家阅读。这是一个具有引导接收器的应用程序,因此它会在启动android设备时启动:

public class BootReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {

    Intent i1 = new Intent(context, SplashActivity.class);
    i1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    i1.putExtra("permission_for_service","");
    context.startActivity(i1);

}

SplashActivity.class的实现是为了在启动MainActivity.class之前获取权限。

    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (!checkAllRequestedPermissions()) {
        ActivityCompat.requestPermissions(this, allRequestedPermissions, MY_PERMISSIONS_REQUEST);
    }
    else {
        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | IntentCompat.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
    }
}    

private boolean checkAllRequestedPermissions() {
    for (String permission : allRequestedPermissions) {
        if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
            return false;
        }
    }
    return true;
}

我想做的是通过使用服务来防止在启动时启动用户界面:

    @Override
protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);

    if (!checkAllRequestedPermissions()) {
        ActivityCompat.requestPermissions(this, allRequestedPermissions, MY_PERMISSIONS_REQUEST);
    } else {
        if (getIntent().hasExtra("permission_for_service")) {
            //service init
            if (!isServiceRunning(SchedulerService.class)) {
                startService(new Intent(this, SchedulerService.class));
            }

            finish();
        } else {
            Intent intent = new Intent(this, MainActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | IntentCompat.FLAG_ACTIVITY_CLEAR_TASK);
            startActivity(intent);
        }
    }
}

不幸的是,这在BOOT_COMPLETE上崩溃了。关于如何使其运作的任何想法?谢谢一百万

0 个答案:

没有答案