找不到方法 android.app.Activity.checkSelfPermission

Could not find method android.app.Activity.checkSelfPermission

我正在尝试实施 运行首次使用我的应用程序的用户请求的时间许可。这是代码:

if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
        if ((ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) &&
                (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)) {
            new masterdb(getApplicationContext());
            new checkRegistration().execute();
        } else {

        }
    } else {
        //initialize database
    }

但是我的应用程序因应用程序无响应而崩溃。 logcat 显示如下内容:

Could not find method android.app.Activity.checkSelfPermission, referenced from method myPackageName.Lib.hasPermission 09-16 11:46:54.969 3763-3763/myPackageName W/dalvikvm: VFY: unable to resolve virtual method 170: Landroid/app/Activity;.checkSelfPermission (Ljava/lang/String;)I

这里的问题是,这段代码甚至不应该在 android Kitkat 中 运行(检查权限)。但我仍然得到这个日志。当我将我的代码移出 sdk 版本的 if 块时,检查它 运行 没问题。

请尝试使用此代码

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
      for (String permission : permissions) {
          int phoneStatePermission = Context.checkSelfPermission(permission);
          if (phoneStatePermission != PackageManager.PERMISSION_GRANTED) {

           }
      }
}

使用此功能检查权限是否被授予。如果不是请求权限

private boolean checkPermission(){
        int result = ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION);
        if (result == PackageManager.PERMISSION_GRANTED){

            return true;

        } else {

            return false;

        }
    }

    private void requestPermission(){

        if (ActivityCompat.shouldShowRequestPermissionRationale(activity,Manifest.permission.ACCESS_FINE_LOCATION)){

            Toast.makeText(context,"GPS permission allows us to access location data. Please allow in App Settings for additional functionality.",Toast.LENGTH_LONG).show();

        } else {

            ActivityCompat.requestPermissions(activity,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},PERMISSION_REQUEST_CODE);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case PERMISSION_REQUEST_CODE:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    Snackbar.make(view,"Permission Granted, Now you can access location data.",Snackbar.LENGTH_LONG).show();

                } else {

                    Snackbar.make(view,"Permission Denied, You cannot access location data.",Snackbar.LENGTH_LONG).show();

                }
                break;
        }
    }