21.2动态权限申请
直接使用Android系统的函数实现动态权限申请比较麻烦,目前也有许多开源库实现此功能,其中easypermissions使用比较简单。
示例代码如下:
//build.gradle中添加库
dependencies{
compile'pub.devrel:easypermissions:0.1.7
}
publicclass MainActivity extends Activity implements
EasyPermissions.PermissionCallbacks {
private static final String TAG ="MainActivity";
private static final intRC_CAMERA_STORAGE_PERM = 110;
@Override
protected void onCreate(BundlesavedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.button_selectImage).setOnClickListener(newView.OnClickListener() {
@Override
public void onClick(View v) {
selectImageTask ();
}
});
@AfterPermissionGranted(RC_CAMERA_STORAGE_PERM)
public void selectImageTask() {
String[] perms = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE };
if(EasyPermissions.hasPermissions(getContext(), perms)) {
// Have permission, do the thing!
getImage();
} else {
// Ask for one permission
EasyPermissions.requestPermissions(this,getString(R.string.rationale_camera_storge),
RC_CAMERA_STORAGE_PERM,perms);
}
}
@Override
public void onRequestPermissionsResult(intrequestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions,grantResults);
// EasyPermissions handles the requestresult.
EasyPermissions.onRequestPermissionsResult(requestCode,permissions, grantResults, this);
}
@Override
public void onPermissionsGranted(intrequestCode, List perms) {
//Log.d(TAG,"onPermissionsGranted:" + requestCode + ":" +perms.size());
}
@Override
public void onPermissionsDenied(intrequestCode, List perms) {
//Log.d(TAG,"onPermissionsDenied:" + requestCode + ":" + perms.size());
// (Optional) Check whether the userdenied permissions and checked NEVER ASK AGAIN.
// This will display a dialog directingthem to enable the permission in app settings.
EasyPermissions.checkDeniedPermissionsNeverAskAgain(this,
getString(R.string.rationale_ask_again),
R.string.mine_setting,R.string.cancel, perms);
}
}