方式1 :
private static final int PERMESSION_CODE =1001;
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED
|| ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED
|| ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE)
!= PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this,"没有权限,请手动开启定位权限",Toast.LENGTH_SHORT).show();
// 申请一个(或多个)权限,并提供用于回调返回的获取码(用户定义)
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_PHONE_STATE},PERMESSION_CODE );
}
@Override
public void onRequestPermissionsResult(int requestCode,@NonNull String[] permissions,
@NonNull int[] grantResults) {
switch (requestCode) {
case PERMESSION_CODE :
break;
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
方式2:
//Android权限管理库
implementation'com.yanzhenjie:permission:1.0.5'
private void permissionApply(){
AndPermission.with(this)
.requestCode(100)
.permission(Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.READ_EXTERNAL_STORAGE)
.rationale(rationaleListener)
.send();
}
private RationaleListenerrationaleListener =new RationaleListener() {
@Override
public void showRequestPermissionRationale(int requestCode,final Rationale rationale) {
//拒绝一次后,再次提示用户权限作用
AndPermission.rationaleDialog(context, rationale).show();
}
};
@Override
public void onRequestPermissionsResult(int requestCode,@NonNull String[] permissions,@NonNull int[] grantResults) {
AndPermission.onRequestPermissionsResult(requestCode, permissions, grantResults,permissionListener);
}
private PermissionListenerpermissionListener =new PermissionListener() {
@Override
public void onSucceed(int requestCode, List grantPermissions) {
if (requestCode ==100) {
//do something
}else if (requestCode ==101){
}
}
@Override
public void onFailed(int requestCode, List deniedPermissions) {
if (AndPermission.hasAlwaysDeniedPermission(MainActivity.this, deniedPermissions)) {
AndPermission.defaultSettingDialog(MainActivity.this,100).show();
}
}
};
网友评论