PermissionsDispatcher


Source link: https://github.com/hotchemi/PermissionsDispatcher

PermissionsDispatcher

PermissionsDispatcher provides a simple annotation-based API to handle runtime permissions.

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.

Usage

  • If you're using Kotlin check Kotlin ver first of all.

Here's a minimum example, in which you register a MainActivity which requires Manifest.permission.CAMERA.

0. Prepare AndroidManifest

Add the following line to AndroidManifest.xml:

<uses-permission android:name="android.permission.CAMERA" />

1. Attach annotations

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();

  
}
 
}

2. Delegate to generated class

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.showCameraWithPermissionCheck(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 for more details.

Other features

Known issues

If you're in trouble check known issues list before filing an issue.

Users

Thankfully we've got hundreds of users around the world!

Download

To add PermissionsDispatcher to your project, include the following in your app module build.gradle file:

${ latest.version } is

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/' 
}
 
}

Misc

  • If you include Jitpack.io dependencies in your project, it is important to review the order of the repositories available to your app module
    • Because of the library's artifact ID, Jitpack might be tempted to resolve the dependency on its own, which could lead to an error during Gradle's configuration time
  • If you're going to bump up the major version number we recommend to refer to migration guide

Licence

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. 

Resources

Nucleus is an Android library which helps to use the Model-View-Presenter pattern.

MicroBus is inspired by OttoBus, and it has its stronger and weaker points.

Advantages:

Disadvantages:

  • This is a one-thread solution.
  • Usage requires a little more code.

Android Drawable Importer Plugin.

Custom dialog view like a loader with circular progress bar animation.

Save 25% memory using Sets.

A Simple Log Tool.

An encapsulation of android.util.Log, which provides:

  • Log level control. You can display different log according different environment.
  • Log with parameters

Topics


2D Engines   3D Engines   9-Patch   Action Bars   Activities   ADB   Advertisements   Analytics   Animations   ANR   AOP   API   APK   APT   Architecture   Audio   Autocomplete   Background Processing   Backward Compatibility   Badges   Bar Codes   Benchmarking   Bitmaps   Bluetooth   Blur Effects   Bread Crumbs   BRMS   Browser Extensions   Build Systems   Bundles   Buttons   Caching   Camera   Canvas   Cards   Carousels   Changelog   Checkboxes   Cloud Storages   Color Analysis   Color Pickers   Colors   Comet/Push   Compass Sensors   Conferences   Content Providers   Continuous Integration   Crash Reports   Credit Cards   Credits   CSV   Curl/Flip   Data Binding   Data Generators   Data Structures   Database   Database Browsers   Date &   Debugging   Decompilers   Deep Links   Dependency Injections   Design   Design Patterns   Dex   Dialogs   Distributed Computing   Distribution Platforms   Download Managers   Drawables   Emoji   Emulators   EPUB   Equalizers &   Event Buses   Exception Handling   Face Recognition   Feedback &   File System   File/Directory   Fingerprint   Floating Action   Fonts   Forms   Fragments   FRP   FSM   Functional Programming   Gamepads   Games   Geocaching   Gestures   GIF   Glow Pad   Gradle Plugins   Graphics   Grid Views   Highlighting   HTML   HTTP Mocking   Icons   IDE   IDE Plugins   Image Croppers   Image Loaders   Image Pickers   Image Processing   Image Views   Instrumentation   Intents   Job Schedulers   JSON   Keyboard   Kotlin   Layouts   Library Demos   List View   List Views   Localization   Location   Lock Patterns   Logcat   Logging   Mails   Maps   Markdown   Mathematics   Maven Plugins   MBaaS   Media   Menus   Messaging   MIME   Mobile Web   Native Image   Navigation   NDK   Networking   NFC   NoSQL   Number Pickers   OAuth   Object Mocking   OCR Engines   OpenGL   ORM   Other Pickers   Parallax List   Parcelables   Particle Systems   Password Inputs   PDF   Permissions   Physics Engines   Platforms   Plugin Frameworks   Preferences   Progress Indicators   ProGuard   Properties   Protocol Buffer   Pull To   Purchases   Push/Pull   QR Codes   Quick Return   Radio Buttons   Range Bars   Ratings   Recycler Views   Resources   REST   Ripple Effects   RSS   Screenshots   Scripting   Scroll Views   SDK   Search Inputs   Security   Sensors   Services   Showcase Views   Signatures   Sliding Panels   Snackbars   SOAP   Social Networks   Spannable   Spinners   Splash Screens   SSH   Static Analysis   Status Bars   Styling   SVG   System   Tags   Task Managers   TDD &   Template Engines   Testing   Testing Tools   Text Formatting   Text Views   Text Watchers   Text-to   Toasts   Toolkits For   Tools   Tooltips   Trainings   TV   Twitter   Updaters   USB   User Stories   Utils   Validation   Video   View Adapters   View Pagers   Views   Watch Face   Wearable Data   Wearables   Weather   Web Tools   Web Views   WebRTC   WebSockets   Wheel Widgets   Wi-Fi   Widgets   Windows   Wizards   XML   XMPP   YAML   ZIP Codes