如下所示:
/** * 读写权限 自己可以添加需要判断的权限 */ public static String[]permissionsREAD={ Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE };
/** * 判断权限集合 * permissions 权限数组 * return true-表示没有改权限 false-表示权限已开启 */ public static boolean lacksPermissions(Context mContexts,permissionsREAD) { for (String permission : permissions) { if (lacksPermission(mContexts,permission)) { return true; } } return false; } /** * 判断是否缺少权限 */ private static boolean lacksPermission(Context mContexts, String permission) { return ContextCompat.checkSelfPermission(mContexts, permission) == PackageManager.PERMISSION_DENIED; }
//Activity使用
if (lacksPermissions()){//读写权限没开启 ActivityCompat.requestPermissions(this,permissionsREAD,0); }else { //读写权限已开启 }
//权限设置回调
@Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode==0){ for (int i = 0; i < permissions.length; i++) { if (grantResults[i]!=-1){ //T.showShort(mContext,"权限设置成功"); }else { //T.showShort(mContext,"拒绝权限"); // 权限被拒绝,弹出dialog 提示去开启权限 showPermissions(); break; } } } }
//弹出dialog
private void showPermissions(){ final Dialog dialog=new android.app.AlertDialog.Builder(mContext).create(); View v=LayoutInflater.from(mContext).inflate(R.layout.dialog_permissions,null); dialog.show(); dialog.setContentView(v); Button btn_add= (Button) v.findViewById(R.id.btn_add); Button btn_diss= (Button) v.findViewById(R.id.btn_diss); btn_add.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { dialog.dismiss(); Intent intent = new Intent(); intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS); intent.addCategory(Intent.CATEGORY_DEFAULT); intent.setData(Uri.parse("package:" + getPackageName())); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY); intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS); startActivity(intent); } }); btn_diss.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { dialog.dismiss(); } }); }
//dialog布局