安卓系统6.0以上需要动态申请手机权限,下面直接贴上申请的代码模版
private void requestPermission(String[]permissions,int code,PermissionCallback callback){ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (checkPermissions(permissions)) { ActivityCompat.requestPermissions(this, permissions, code); mPermissionCallbacks.put(code, callback); }else { //6.0以上已经动态申请了权限 callback.onSuccess(); } }else {//6.0一下,无需动态申请 callback.onSuccess(); } } private boolean checkPermissions(String[] permossions){ BaseActivity activity = MyEnvironment.activity(); for(String permission:permossions){ if(ActivityCompat.checkSelfPermission(activity, permission) == PackageManager.PERMISSION_GRANTED){ return false; } } return true; } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); PermissionCallback callback = mPermissionCallbacks.get(requestCode); int success = 0; for (int grantResult : grantResults) { success += grantResult == PackageManager.PERMISSION_GRANTED ? 1 : 0; } if (success == grantResults.length) { callback.onSuccess();//申请成功 } else { callback.onError(new Exception("申请权限失败")); } mPermissionCallbacks.remove(requestCode); } protected SparseArraymPermissionCallbacks = new SparseArray (); public interface PermissionCallback { void onSuccess(); void onError(Exception exception); }
以上方法一般放在基类,需要动态申请其他权限的时候,只需要添加对应的code和权限permission就可以了,添加的方式如下
public static final int REQUEST_CODE_CAMERA = 3; public static final int REQUEST_CODE_EXTERNAL_STORAGE = 4; public void requestExternalPermission(PermissionCallback callback){ requestPermission(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE},REQUEST_CODE_EXTERNAL_STORAGE,callback); } public void requestCameraPermission(PermissionCallback callback){ requestPermission(new String[]{Manifest.permission.CAMERA},REQUEST_CODE_CAMERA,callback); }
自己定义好code就可以了,对外只需要暴露requestXXXPermission方法,真正申请权限的代码在requestPermission方法中,已经整理成模版,每个权限对应的code应当是不相同的。
调用:
activity.requestCameraPermission(new PermissionCallback() { @Override public void onSuccess() {//动态申请成功 takePhote(); } @Override public void onError(Exception exception) { Toast.makeText(PermissionActivity.this, "请通过设置允许应用获取权限", Toast.LENGTH_SHORT).show(); } });
只需要提供一个回调就可以了,是不是很简单易用
权限族参考列表
Permission Group | Permissions |
---|---|
CALENDAR | READ_CALENDAR , WRITE_CALENDAR |
CAMERA | CAMERA |
CONTACTS | READ_CONTACTS , WRITE_CONTACTS , GET_ACCOUNTS |
LOCATION | ACCESS_FINE_LOCATION, ACCESS_COARSE_LOCATION |
MICROPHONE | RECORD_AUDIO |
PHONE | READ_PHONE_STATE ,CALL_PHONE READ_CALL_LOG, WRITE_CALL_LOG ADD_VOICEMAIL |
SENSORS | BODY_SENSORS |
SMS | SEND_SMS ,RECEIVE_SMS ,READ_SMS, RECEIVE_WAP_PUSH, RECEIVE_MMS |
STORAGE | READ_EXTERNAL_STORAGE ,WRITE_EXTERNAL_STORAGE |