项目中很多操作需要事先进行危险权限的判断和获取,本人在Android项目开发中封装了一个获取Android6.0以上系统危险权限的获取的方法,希望能给大家带来帮助。
首先定义一个接口,里面有两个方法。
public interface AccreditListener {
void onAccreditSucceed(); //权限获取成功
void onAccreditFailure(); //权限获取失败
}
然后,定义一个activity基类,可供需要工程中的activity继承。
public class AppBaseActivity extends AppCompatActivity {
public int mRequestCode;
public int mPermissionRequestCount;
private AccreditListener mAccreditListener;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
}
/**
* android6.0权限处理
*
* @param context
* @param permissionNames
* @param requestCode
*/
public void requestPermission(Context context, String[] permissionNames, int requestCode, AccreditListener accreditListener) {
if (permissionNames == null || permissionNames.length < 1) {
return;
}
mRequestCode = requestCode;
mPermissionRequestCount = permissionNames.length;
mAccreditListener = accreditListener;
boolean isPermitted = true;
for (String permissionName : permissionNames) {
if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(context, permissionName)) {
isPermitted = false;
}
}
if (isPermitted) {
mAccreditListener.onAccreditSucceed();
} else {
ActivityCompat.requestPermissions((Activity) context, permissionNames, requestCode);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == mRequestCode && mPermissionRequestCount > 0) {
boolean isPermitted = true;
for (int i = 0; i < mPermissionRequestCount; i++) {
if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
isPermitted = false;
}
}
if (isPermitted) {
mAccreditListener.onAccreditSucceed();
} else {
mAccreditListener.onAccreditFailure();
}
}
}
后面可以在需要的地方随意调用了,比如:
mMicrophone.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
requestPermission(
ContactSearchActivity.this,
new String[]{
Manifest.permission.RECORD_AUDIO,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE},
0x11, new AccreditListener() {
@Override
public void onAccreditSucceed() {
Log.i(TAG,"权限获取成功!");
}
@Override
public void onAccreditFailure() {
Log.i(TAG,"权限获取失败!");
}
});
}
});