- googlesamples (来自google教科书)
Easypermissions
1. 添加依赖
build.gradle
dependencies {
compile 'pub.devrel:easypermissions:0.2.1'
}
2. 涉及到权限的activity
或fragment
实现PermissionCallbacks
接口.
public class UserActivity extends AppCompatActivity
implements EasyPermissions.PermissionCallbacks {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
// 将权限处理转交给EasyPermissions
EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
}
/**
*具体的涉及敏感权限的法.REQUEST_CODE_PERMISSION_PHOTO_PICKER用来*标识此权限是否被用户准许,回调至Granted or Denied方法内.
*/
@AfterPermissionGranted(REQUEST_CODE_PERMISSION_PHOTO_PICKER)
private void choicePhotoWrapper() {
// 被申请的权限数组
String[] perms = { Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA };
if (EasyPermissions.hasPermissions(this, perms)) {
// 具体的操作方法(此处用打开相机来说明)
Intent intent = newIntent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent,TAKE_PHOTO_WITH_DATA);
} else {
EasyPermissions.requestPermissions(this, "相机需要以下权限:\n\n1.访问设备上的照片",
REQUEST_CODE_PERMISSION_PHOTO_PICKER, perms);
}
}
@Override
public void onPermissionsGranted(int requestCode, List<String> list) {
// Some permissions have been granted
// 某些权限被允许后的回调...
}
@Override public void onPermissionsDenied(int requestCode, List<String> list) {
// Some permissions have been denied
// 用户拒绝此权限后的操作...(弹出Dialog提示用户手动设置开启)
if (requestCode == REQUEST_CODE_PERMISSION_PHOTO_PICKER) {
Toast.makeText(this, "您拒绝了「打开相机」所需要的相关权限!", Toast.LENGTH_SHORT).show();
}
if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
new AppSettingsDialog.Builder(this, getString(R.string.rationale_ask_again)).setTitle(
getString(R.string.title_settings_dialog))
.setPositiveButton(getString(R.string.setting))
.setNegativeButton(getString(R.string.cancel), null /* click listener */)
.setRequestCode(RC_SETTINGS_SCREEN)
.build()
.show();
}
}
}