如何在运行时检查授予权限?

Posted

技术标签:

【中文标题】如何在运行时检查授予权限?【英文标题】:How to check Grants Permissions at Run-Time? 【发布时间】:2015-08-13 11:59:29 【问题描述】:

Android M(预览版)中,用户可以选择特定应用并获取特定权限。

所以我问如何在运行时检查授予权限

【问题讨论】:

我尝试为这个github.com/nitiwari-dev/androidMRuntimePermissionDemo构建一个简单的演示 我已经为它创建了库。通过简单的步骤即可轻松使用。 github.com/Kishanjvaghela/Ask-Permission 它在codesfor.in/android-request-permission-dynamically-example创建了一个关于在an​​droid中请求权限运行时的步骤的小文档 【参考方案1】:

不错!!

我刚刚发现我的需要,我们可以检查权限是否被授予:

checkSelfPermission(Manifest.permission.READ_CONTACTS)

必要时请求权限

if (checkSelfPermission(Manifest.permission.READ_CONTACTS)
            != PackageManager.PERMISSION_GRANTED) 
        requestPermissions(new String[]Manifest.permission.READ_CONTACTS,
                MY_PERMISSIONS_REQUEST_READ_CONTACTS);

        // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
        // app-defined int constant

        return;
    

处理权限请求响应

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

                // permission was granted, yay! do the
                // calendar task you need to do.

             else 

                // permission denied, boo! Disable the
                // functionality that depends on this permission.
            
            return;
        

        // other 'switch' lines to check for other
        // permissions this app might request
    

【讨论】:

请记住我们必须有 noHistory=false 才能接收回调。如果您没有收到回拨,也请参考this。我浪费了几个小时来弄清楚。 我已经为它创建了库。通过简单的步骤即可轻松使用。 github.com/Kishanjvaghela/Ask-Permission【参考方案2】:

最佳描述在:http://inthecheesefactory.com/blog/things-you-need-to-know-about-android-m-permission-developer-edition/en

对于简单的使用权限,你可以使用这个库:http://hotchemi.github.io/PermissionsDispatcher/

【讨论】:

【参考方案3】:

也可以通过以下代码sn-p进行查询,向后兼容;

int hasPermission = ContextCompat.checkSelfPermission(this,Manifest.permission.WRITE_CONTACTS);
if (hasPermission == PackageManager.PERMISSION_GRANTED) 
    //Do smthng

【讨论】:

【参考方案4】:

试试这个简单的请求代码https://www.learn2crack.com/2015/10/android-marshmallow-permissions.html

public static final int REQUEST_ID_MULTIPLE_PERMISSIONS = 1;

private  boolean checkAndRequestPermissions() 
    int camera = ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA);
    int storage = ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
    int loc = ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION);
    int loc2 = ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION);
    List<String> listPermissionsNeeded = new ArrayList<>();

    if (camera != PackageManager.PERMISSION_GRANTED) 
        listPermissionsNeeded.add(android.Manifest.permission.CAMERA);
    
    if (storage != PackageManager.PERMISSION_GRANTED) 
        listPermissionsNeeded.add(android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
    
    if (loc2 != PackageManager.PERMISSION_GRANTED) 
        listPermissionsNeeded.add(android.Manifest.permission.ACCESS_FINE_LOCATION);
    
    if (loc != PackageManager.PERMISSION_GRANTED) 
        listPermissionsNeeded.add(android.Manifest.permission.ACCESS_COARSE_LOCATION);
    
    if (!listPermissionsNeeded.isEmpty())
    
        ActivityCompat.requestPermissions(this,listPermissionsNeeded.toArray
                (new String[listPermissionsNeeded.size()]),REQUEST_ID_MULTIPLE_PERMISSIONS);
        return false;
    
    return true;

【讨论】:

反应很好。 我已经为它创建了库。通过简单的步骤即可轻松使用。 github.com/Kishanjvaghela/Ask-Permission 完美运行! 我试过这个示例,但它总是说安全异常 @Vishali 您是否也在清单中添加了权限?一旦检查正确,它将起作用【参考方案5】:
fun hasPermission(permission: String): Boolean 
      if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) return true // must be granted after installed.
      return mAppSet.appContext.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED

【讨论】:

【参考方案6】:

对于位置运行时权限

ActivityCompat.requestPermissions(this,new String[]android.Manifest.permission.ACCESS_FINE_LOCATION, 1);

public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) 
    switch (requestCode) 
        case 1: 
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) 
                Log.d("yes","yes");

             else 
                Log.d("yes","no");
                // permission denied, boo! Disable the
                // functionality that depends on this permission.
            
            return;
        
        // other 'case' lines to check for other
        // permissions this app might request
    

【讨论】:

【参考方案7】:

试试这个检查运行时权限:

@Override
protected void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    checkRunTimePermission();

检查运行时权限:

private void checkRunTimePermission() 
    String[] permissionArrays = new String[]Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE;

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) 
        requestPermissions(permissionArrays, 11111);
     else 
         // if already permition granted
        // PUT YOUR ACTION (Like Open cemara etc..)
    

处理权限结果:

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) 
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    boolean openActivityOnce = true;
    boolean openDialogOnce = true;
    if (requestCode == 11111) 
        for (int i = 0; i < grantResults.length; i++) 
            String permission = permissions[i];

            isPermitted = grantResults[i] == PackageManager.PERMISSION_GRANTED;

            if (grantResults[i] == PackageManager.PERMISSION_DENIED) 
                // user rejected the permission
                boolean showRationale = shouldShowRequestPermissionRationale(permission);
                if (!showRationale) 
                    //execute when 'never Ask Again' tick and permission dialog not show
                 else 
                    if (openDialogOnce) 
                        alertView();
                    
                
            
        

        if (isPermitted)
            if (isPermissionFromGallery)
                openGalleryFragment();
    

设置自定义提醒:

private void alertView() 
    AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity(), R.style.MyAlertDialogStyle);

    dialog.setTitle("Permission Denied")
            .setInverseBackgroundForced(true)
            //.setIcon(R.drawable.ic_info_black_24dp)
            .setMessage("Without those permission the app is unable to save your profile. App needs to save profile image in your external storage and also need to get profile image from camera or external storage.Are you sure you want to deny this permission?")

            .setNegativeButton("I'M SURE", new DialogInterface.OnClickListener() 
                public void onClick(DialogInterface dialoginterface, int i) 
                    dialoginterface.dismiss();
                
            )
            .setPositiveButton("RE-TRY", new DialogInterface.OnClickListener() 
                public void onClick(DialogInterface dialoginterface, int i) 
                    dialoginterface.dismiss();
                    checkRunTimePermission();

                
            ).show();

【讨论】:

被允许??其分配的地方【参考方案8】:

原创(不是我的)帖子here

对于特殊权限,例如 android.Manifest.permission.PACKAGE_USAGE_STATS 使用 AppOpsManagerKotlin

private fun hasPermission(permission:String, permissionAppOpsManager:String): Boolean 
    var granted = false
    if (VERSION.SDK_INT >= VERSION_CODES.M) 
        // requires kitkat
        val appOps = applicationContext!!.getSystemService(Context.APP_OPS_SERVICE) as AppOpsManager

        // requires lollipop
        val mode = appOps.checkOpNoThrow(permissionAppOpsManager,
                              android.os.Process.myUid(), applicationContext!!.packageName)

        if (mode == AppOpsManager.MODE_DEFAULT) 
            granted = applicationContext!!.checkCallingOrSelfPermission(permission) == PackageManager.PERMISSION_GRANTED
         else 
            granted = mode == AppOpsManager.MODE_ALLOWED
        
    

    return granted

以及代码中的任何地方:

val permissionAppOpsManager = AppOpsManager.OPSTR_GET_USAGE_STATS
val permission = android.Manifest.permission.PACKAGE_USAGE_STATS
val permissionActivity = Settings.ACTION_USAGE_ACCESS_SETTINGS

if (hasPermission(permission, permissionAppOpsManager)) 
    Timber.i("has permission: $permission")
    // do here what needs permission
 else 
    Timber.e("has no permission: $permission")
    // start activity to get permission
    startActivity(Intent(permissionActivity))

您可以通过TedPermission library获得其他权限

【讨论】:

【参考方案9】:

使用Dexter library

在您的 build.gradle 中包含该库

dependencies
    implementation 'com.karumi:dexter:4.2.0'

这个例子请求WRITE_EXTERNAL_STORAGE.

Dexter.withActivity(this)
                .withPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .withListener(new PermissionListener() 
                    @Override
                    public void onPermissionGranted(PermissionGrantedResponse response) 
                        // permission is granted, open the camera
                    

                    @Override
                    public void onPermissionDenied(PermissionDeniedResponse response) 
                        // check for permanent denial of permission
                        if (response.isPermanentlyDenied()) 
                            // navigate user to app settings
                        
                    

                    @Override
                    public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) 
                        token.continuePermissionRequest();
                    
                ).check();

检查这个答案here

【讨论】:

【参考方案10】:

在 git 中查看以下库:

RuntimePermission

实施:

        allprojects 
            repositories 
                ...
                maven  url 'https://jitpack.io' 
            
        
        
        dependencies 
            implementation 'com.github.manoj140220:RuntimePermission:1.0.3'
        
    
    
      
    
        new RuntimePermission(Current Class Object, String[] , ActvityContext);
          
          String[] : permission array.
          example  : String[] permissionArray = Manifest.permission.CAMERA, Manifest.permission.BODY_SENSORS,... 
    
    Implement : PermissionNotify
    
    interface notifier methods.
    
    @Override
    public void notifyPermissionGrant() 
        
    
    
    @Override
    public void notifyPermissionDeny() 
         
    

【讨论】:

以上是关于如何在运行时检查授予权限?的主要内容,如果未能解决你的问题,请参考以下文章

如何在 PhoneGap 应用程序运行时检查权限?

请求运行时权限时检查 Android 版本

已授予 Android 运行时权限,但仍被拒绝

谷歌应用程序脚本在第一次运行时授予用户权限访问电子表格上的服务,而无需打开脚本编辑器

Android动态运行时权限

Android动态运行时权限