2016-09-16 127 views
2

我想實現從用戶第一次使用我的應用程序請求運行時權限。這裏是代碼:找不到方法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的說明是這樣的:

找不到方法android.app.Activity.checkSelfPermission,從方法myPackageName.Lib.hasPermission 11月9日至16日引用:46:54.969 3763-3763/myPackageName W/dalvikvm :VFY:無法解析虛方法170:Landroid /應用/活動; .checkSelfPermission(Ljava /朗/字符串;)我

的東西在這裏,這段代碼應該不能運行(檢查許可)在Android Kitkat。但我仍然得到這個日誌。當我將代碼移出sdk版本的if塊時,請檢查它是否正常運行。

+0

我也得到相同的警告......你有沒有找到任何解決方案? –

+0

使用ContextCompat代替ActivityCompat解決了我的問題 –

回答

0

使用此功能來檢查是否許可​​授予。如果不是,請求許可

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; 
     } 
    } 
1

請嘗試使用此代碼

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

      } 
     } 
} 
+1

不知道它做了什麼區別,它是完全一樣的代碼 –

+0

@AmanGrover請看這篇文章 http://stackoverflow.com/a/32615104/4746180 – Hayk