if(ContextCompat.checkSelfPermission(this,Manifest.permission.CAMERA)!=PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.CAMERA},10001);
}else {
//权限申请成功,做相应功能
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode){
case 10001:
if (grantResults.length>0&&grantResults[0]==PackageManager.PERMISSION_GRANTED){
//做相应功能
}else {
Toast.makeText(this, "权限申请成功!", Toast.LENGTH_SHORT).show();
}
break;
}
}
implementation 'pub.devrel:easypermissions:2.0.1
’String PERMISSION_STORAGE_MSG = "请授予权限,否则影响部分使用功能";
int PERMISSION_STORAGE_CODE = 10001;
String[] PERMS = {Manifest.permission.CAMERA, Manifest.permission.ACCESS_FINE_LOCATION};
if (EasyPermissions.hasPermissions(this, PERMS)) {
// 已经申请过权限,做想做的事
} else {
// 没有申请过权限,现在去申请
/**
*@param host Context对象
*@param rationale 权限弹窗上的提示语。
*@param requestCode 请求权限的唯一标识码
*@param perms 一系列权限
*/
EasyPermissions.requestPermissions(this, PERMISSION_STORAGE_MSG, PERMISSION_STORAGE_CODE, PERMS);
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//将结果转发给EasyPermissions
EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
}
public class MainActivity extends AppCompatActivity implements EasyPermissions.PermissionCallbacks {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/**
* 申请成功时调用
* @param requestCode 请求权限的唯一标识码
* @param perms 一系列权限
*/
@Override
public void onPermissionsGranted(int requestCode,List<String> perms) {
}
/**
* 申请拒绝时调用
* @param requestCode 请求权限的唯一标识码
* @param perms 一系列权限
*/
@Override
public void onPermissionsDenied(int requestCode,List<String> perms) {
}
使用了该注解,当权限请求被用户同意后,会根据请求code来执行,相应的含有@AfterPermissionGranted注解的方法。
简化了请求成功操作流程,不需要在EasyPermissions.onRequestPermissionsResult()的回调监听器中请求成功的方法中,再次手动调用,获取权限后需要操作的逻辑代码。
@AfterPermissionGranted(10001)
public void onPermissionSuccess(){
Toast.makeText(this,"AfterPermission调用成功了",Toast.LENGTH_SHORT).show();
}
@Override
public void onPermissionsDenied(int requestCode, List<String> perms) {
/**
* 若是在权限弹窗中,用户勾选了'不在提示',且拒绝权限。
* 这时候,需要跳转到设置界面去,让用户手动开启。
*/
if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
new AppSettingsDialog.Builder(this).build().show();
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == AppSettingsDialog.DEFAULT_SETTINGS_REQ_CODE) {
//从设置页面返回,判断权限是否申请。
if (EasyPermissions.hasPermissions(this, PERMS)) {
Toast.makeText(this, "权限申请成功!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "权限申请失败!", Toast.LENGTH_SHORT).show();
}
}
}