PermissionsDispatcher provides a simple annotation-based API to handle runtime permissions in Android Marshmallow, 100% reflection-free.
This library lifts the burden that comes with writing a bunch of check statements whether a permission has been granted or not from you, in order to keep your code clean and safe.
Here's a minimum example, in which we register a MainActivity
which requires Manifest.permission.CAMERA
.
Add the following line to AndroidManifest.xml
:
<uses-permission android:name="android.permission.CAMERA" />
PermissionsDispatcher introduces only a few annotations, keeping its general API concise:
NOTE: Annotated methods must not be
private
.
Annotation | Required | Description |
---|---|---|
@RuntimePermissions |
โ | Register an Activity or Fragment (we support both) to handle permissions |
@NeedsPermission |
โ | Annotate a method which performs the action that requires one or more permissions |
@OnShowRationale |
Annotate a method which explains why the permission/s is/are needed. It passes in a PermissionRequest object which can be used to continue or abort the current permission request upon user input |
|
@OnPermissionDenied |
Annotate a method which is invoked if the user doesn't grant the permissions | |
@OnNeverAskAgain |
Annotate a method which is invoked if the user chose to have the device "never ask again" about a permission |
@RuntimePermissions
public class MainActivity extends AppCompatActivity {
@NeedsPermission(Manifest.permission.CAMERA)
void showCamera() {
getSupportFragmentManager().beginTransaction()
.replace(R.id.sample_content_fragment, CameraPreviewFragment.newInstance())
.addToBackStack("camera")
.commitAllowingStateLoss();
}
@OnShowRationale(Manifest.permission.CAMERA)
void showRationaleForCamera(final PermissionRequest request) {
new AlertDialog.Builder(this)
.setMessage(R.string.permission_camera_rationale)
.setPositiveButton(R.string.button_allow, (dialog, button) -> request.proceed())
.setNegativeButton(R.string.button_deny, (dialog, button) -> request.cancel())
.show();
}
@OnPermissionDenied(Manifest.permission.CAMERA)
void showDeniedForCamera() {
Toast.makeText(this, R.string.permission_camera_denied, Toast.LENGTH_SHORT).show();
}
@OnNeverAskAgain(Manifest.permission.CAMERA)
void showNeverAskForCamera() {
Toast.makeText(this, R.string.permission_camera_neverask, Toast.LENGTH_SHORT).show();
}
}
Upon compilation, PermissionsDispatcher generates a class for MainActivityPermissionsDispatcher
([Activity Name] + PermissionsDispatcher), which you can use to safely access these permission-protected methods.
The only step you have to do is delegating the work to this helper class:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.button_camera).setOnClickListener(v -> {
// NOTE: delegate the permission handling to generated method
MainActivityPermissionsDispatcher.showCameraWithCheck(this);
});
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
// NOTE: delegate the permission handling to generated method
MainActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
}
Check out the sample and generated class for more details.
PermissionsDispatcher takes care of special permissions Manifest.permission.SYSTEM_ALERT_WINDOW
and Manifest.permission.WRITE_SETTINGS
.
The following sample is to grant SYSTEM_ALERT_WINDOW
.
Add the following line to AndroidManifest.xml
:
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
It's the same as other permissions:
@RuntimePermissions
public class MainActivity extends AppCompatActivity {
@NeedsPermission(Manifest.permission.SYSTEM_ALERT_WINDOW)
void systemAlertWindow() {
}
@OnShowRationale(Manifest.permission.SYSTEM_ALERT_WINDOW)
void systemAlertWindowOnShowRationale(final PermissionRequest request) {
}
@OnPermissionDenied(Manifest.permission.SYSTEM_ALERT_WINDOW)
void systemAlertWindowOnPermissionDenied() {
}
@OnNeverAskAgain(Manifest.permission.SYSTEM_ALERT_WINDOW)
void systemAlertWindowOnNeverAskAgain() {
}
}
Unlike other permissions, special permissions require to call the delegation method at onActivityResult
:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.button_system_alert_window).setOnClickListener(v -> {
// NOTE: delegate the permission handling to generated method
MainActivityPermissionsDispatcher.systemAlertWindowWithCheck(this);
});
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
MainActivityPermissionsDispatcher.onActivityResult(this, requestCode);
}
<uses-permission> has an attribute call maxSdkVersion
. PermissionsDispatcher support the feature as well.
The following sample is for declaring Manifest.permisison.WRITE_EXTERNAL_STORAGE
up to API level 18.
Declare the permission with maxSdkVersion
attribute
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="18" />
@RuntimePermissions
public class MainActivity extends AppCompatActivity {
@NeedsPermission(value = Manifest.permission.WRITE_EXTERNAL_STORAGE, maxSdkVersion = 18)
void getStorage() {
// ...
}
}
If you use AndroidAnnotations, you need to add AndroidAnnotationsPermissionsDispatcherPlugin to your dependencies so PermissionsDispatcher's looks for AA's subclasses (your project won't compile otherwise).
To add it to your project, include the following in your app module build.gradle
file:
dependencies {
compile 'com.github.hotchemi:permissionsdispatcher:${latest.version}' {
// if you don't use android.app.Fragment you can exclude support for them
exclude module: "support-v13"
}
annotationProcessor 'com.github.hotchemi:permissionsdispatcher-processor:${latest.version}'
}
Snapshots of the development version are available in JFrog's snapshots repository.
Add the repo below to download SNAPSHOT
releases.
repositories {
jcenter()
maven { url 'http://oss.jfrog.org/artifactory/oss-snapshot-local/' }
}
Copyright 2016 Shintaro Katafuchi, Marcel Schnelle, Yoshinori Isogai
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.