安卓6.0之后改动较大,其中权限方面就对我们的app开发有较大的影响,甚至会直接导致app的崩溃,这是因为android 6.0以后新增了运行时权限机制,下面是我参看多方播客后结合自己的开发所采用的解决方案
注:应首先在AndroidManifest.xml中申明所需的权限,这里就不多做说明了
//同时申请多个权限
public void applyPermission(){
//需要申请的权限的列表
String[] mutiPermissions = new String[]{
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.ACCESS_FINE_LOCATION,};
//需要请求授权的权限
ArrayList<String> needRequest = new ArrayList<>();
//遍历 过滤已授权的权限,防止重复申请
for (String permission : mutiPermissions) {
int check = 0;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
check = checkSelfPermission(permission);
}
if (check != PackageManager.PERMISSION_GRANTED) {
needRequest.add(permission);
Log.d("RuntimePermissionDemo","needCheck: " + permission);
}
}
//如果没有全部授权
if (needRequest.size() > 0) {
//请求权限,此方法异步执行,会弹出权限请求对话框,让用户授权,并回调 onRequestPermissionsResult 来告知授权结果
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { //判断android 版本
requestPermissions(needRequest.toArray(new String[needRequest.size()]), REQUEST_CODE_ASK_MUTI_PERMISSIONS);
}
}else {
//已经全部授权了
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode) {
case REQUEST_CODE_ASK_SINGLE_PERMISSION://请求单个权限
//...
break;
case REQUEST_CODE_ASK_MUTI_PERMISSIONS://请求多个权限
if (grantResults.length > 0) {
//被拒绝的权限列表
ArrayList<String> deniedPermissions = new ArrayList<>();
for (int i=0; i<grantResults.length; i++) {
if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
deniedPermissions.add(permissions[i]);
Log.d("RuntimePermissionDemo", "Denied Permission: " + permissions[i]);
}
}
if (deniedPermissions.size() <= 0) {
//已经全部授权
}else {//没有全部授权
Toast.makeText(TEMainActivity.this, "缺少部分权限", Toast.LENGTH_SHORT).show();
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
//需要引导用户手动开启的权限列表
ArrayList<String> needShow = new ArrayList<>();
//从没有授权的权限中判断是否需要引导用户
for (int i=0; i<deniedPermissions.size(); i++) {
String permission = deniedPermissions.get(i);
if (!shouldShowRequestPermissionRationale(permission)) {
needShow.add(permission);
Log.d("RuntimePermissionDemo", "needShow: " + permission);
}
}
//需要引导用户
if (needShow.size() > 0) {
//需要弹出自定义对话框,引导用户去应用的设置界面手动开启权限
showMissingPermissionDialog();
}
}
}
}
break;
default: super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
/**
* 需要手动开启缺失的权限对话框
*/
private void showMissingPermissionDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("提示");
builder.setMessage("当前应用权限不足。\n\n可点击\"设置\"-\"权限\"-打开所需权限。\n\n最后点击两次后退按钮,即可返回。");
builder.setNegativeButton("知道了", null);
builder.setPositiveButton("设置", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
startAppSettings();
}
});
builder.setCancelable(false);
builder.show();
}