Android 动态申请权限

 

 

AndroidManifest.xml(清单文件)添加需要的权限


<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <!-- 用于进行网络定位 -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <!-- 用于访问GPS定位 -->
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" /> <!-- 允许应用程序访问额外的位置提供命令 -->

 

//权限数组(申请定位)
private String[] permissions = new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS};

//返回code
private static final int OPEN_SET_REQUEST_CODE = 100;
//调用此方法判断是否拥有权限
private void initPermissions() {
    if (lacksPermission(permissions)) {//判断是否拥有权限
//请求权限,第二参数权限String数据,第三个参数是请求码便于在onRequestPermissionsResult 方法中根据code进行判断
ActivityCompat.requestPermissions(this, permissions, OPEN_SET_REQUEST_CODE);
} else {
//拥有权限执行操作
}
}

//如果返回true表示缺少权限
public boolean lacksPermission() {
for (String permission : permissions) {
//判断是否缺少权限,true=缺少权限
if(ContextCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED){
return true;
}
}
return false;
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);

switch (requestCode){//响应Code
case OPEN_SET_REQUEST_CODE:
if (grantResults.length > 0) {
for(int i = 0; i < grantResults.length; i++){
if(grantResults[i] != PackageManager.PERMISSION_GRANTED){
Toast.makeText(context,"未拥有相应权限",Toast.LENGTH_LONG).show();
return;
}
}
//拥有权限执行操作
} else {
Toast.makeText(context,"未拥有相应权限",Toast.LENGTH_LONG).show();
}
break;
}
}
posted @ 2019-08-12 16:10  LEON D  阅读(3271)  评论(0编辑  收藏  举报