原因1. 没有授权检查;
原因2. 权限检查与声明不匹配
例如:
近期,维护一个接手的App,由于历史原因,没有权限管理,直接导致在高版本的Android上闪退。
直接导入了以前项目使用的以下代码
public static String[] check(@NonNull Context context, @NonNull String[] permissions ) { // android 5 --> 21 // android 5.1 --> 22 if( Build.VERSION.SDK_INT < Build.VERSION_CODES.M ) //if( Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP ) { return null ; } if( null == permissions ) { permissions = PERMISSIONS ; } List<String> ungranted_permissions = new ArrayList<String>(); int hasPermission = 0 ; for( int idx = 0 ; idx < permissions.length ; idx++ ) { //PermissionChecker.checkSelfPermission(this, permission.WRITE_CONTACTS) //hasPermission = ContextCompat.checkSelfPermission(getApplication(), permission.WRITE_EXTERNAL_STORAGE); hasPermission = ContextCompat.checkSelfPermission( context, permissions[idx] ) ; if (PackageManager.PERMISSION_GRANTED != hasPermission) { //startGetImageThread(); ungranted_permissions.add( permissions[idx] ) ; } } if( 0 == ungranted_permissions.size() ) { //TODO: continue for start return null ; } //pop dialog to usr for assign permission else { //ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, CODE_REQ_MULTIPLE_PERMISSION); permissions = new String[ungranted_permissions.size()] ; ungranted_permissions.toArray( permissions ) ; Log.i( "PermissionUtil", "req permissions = "+ permissions ); return permissions ; } }
和
@Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { switch (requestCode) { case PermissionUtil.CODE_REQ_MULTIPLE_PERMISSION: for(int idx=0; idx<permissions.length ;idx++) { Log.i(TAG, "permissions = " + permissions[idx] + ", grantResults = " + grantResults[idx]); } // If request is cancelled, the result arrays are empty. if ( grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED ) { // permission was granted, yay! Do the contacts-related task you need to do. //doCreate } else { // permission denied, boo! Disable the // functionality that depends on this permission. Log.i(TAG, "Permissions NOT Granted, Finish App!" ); Toast.makeText( this, "Permissions NOT Granted, Finish App!", Toast.LENGTH_SHORT).show(); finish(); } return; } // other 'case' lines to check for other // permissions this app might request super.onRequestPermissionsResult(requestCode, permissions, grantResults); }
发现,在授权后,依然是闪退,抓LOG看,显示没有被授权,明明刚进行过授权啊,后来检查才发现:
在添加权限的时候,授权列表中的项目,同时也需要在manifest文件中添加权限声明, 仅仅进行授权检查是不可用的。
以此判断,虽然高版本android增加了动态授权,但是原来的声明授权方式依然其作用,系统显然是检查了两处都已经授权才允许通行。