Android 6.0 open failed: EACCES (Permission denied)
对于6.0+权限问题,报错如上:
解决方案:
Android 6.0 (Marshmallow). 添加新的权限模型,需要在运行时动态获取所需要的权限。
首先判断手机系统版本是否在6.0+然后才是支持运行时动态获取权限:
private boolean canMakeSmores(){return(Build.VERSION.SDK_INT>Build.VERSION_CODES.LOLLIPOP_MR1);}
然后是运行时获取权限的操作:
String[] perms = {"android.permission.RECORD_AUDIO", "android.permission.CAMERA"};int permsRequestCode = 200; requestPermissions(perms, permsRequestCode);requestPermissions这个方法是Activity的方法,然后在onRequestPermissionResult里面拿到权限授予的回调结果:@Overridepublic void onRequestPermissionsResult(int permsRequestCode, String[] permissions, int[] grantResults){switch(permsRequestCode){case 200:boolean audioAccepted = grantResults[0]==PackageManager.PERMISSION_GRANTED;boolean cameraAccepted = grantResults[1]==PackageManager.PERMISSION_GRANTED;break;}}
下面这个方法可以获取用户是不是已经授予某些特殊的权限:
private boolean hasPermission(String permission){if(canMakeSmores()){return(checkSelfPermission(permission)==PackageManager.PERMISSION_GRANTED);}return true;}
如果用户已经授权过了这些权限,系统不会记住的,需要我们自己记住这些。
private boolean shouldWeAsk(String permission){return (sharedPreferences.getBoolean(permission, true));}private void markAsAsked(String permission){sharedPreferences.edit().putBoolean(permission, false).apply;}
同一个页面,可能多次需要某些权限,切记不要重复让用户授权
private ArrayList findUnAskedPermissions(ArrayList wanted){ArrayList result = new ArrayList<~>();for(String perm : wanted){if(!hasPermission(perm) && shouldWeAsk(perm)){result.add(perm);}}return result;}
转自:http://www.captechconsulting.com/blogs/runtime-permissions-best-practices-and-how-to-gracefully-handle-permission-removal