21.2動態(tài)權(quán)限申請
直接使用Android系統(tǒng)的函數(shù)實現(xiàn)動態(tài)權(quán)限申請比較麻煩吼过,目前也有許多開源庫實現(xiàn)此功能绪商,其中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);
}
}