Android Rights Management PermissionsDispatcher2.3.2 use + Native 6.0 permissions to use

Source: Internet
Author: User

PermissionsDispatcher2.3.2 use

Android6.0 Rights official website
Https://developer.android.com/about/versions/marshmallow/android-6.0-changes.html?hl=zh-cn
System permissions:
Https://developer.android.com/training/permissions/index.html?hl=zh-cn
Best Practices for permissions:
Https://developer.android.com/training/permissions/best-practices.html?hl=zh-cn#testing
GitHub address for this library
Https://github.com/hotchemi/PermissionsDispatcher


Permissions Gradle Configuration

With Permissionsdispatcher, you need to add the Build.gradle in Project

(1) When studio version is above 2.2

In the app module, add the Build.gradle:

dependencies {  compile ‘com.github.hotchemi:permissionsdispatcher:${latest.version}‘  annotationProcessor ‘com.github.hotchemi:permissionsdispatcher-processor:${latest.version}‘}

Current ${latest.version}
The latest is 2.3.2.

(2) When studio version is less than 2.2

In the project directory, add the Build.gradle file:

buildscript {    dependencies {      classpath ‘com.neenbedankt.gradle.plugins:android-apt:1.8‘    }  }

Then add it in the Build.gradle in the app module: (must be added in the app module)

apply plugin: ‘android-apt‘  dependencies {    compile ‘com.github.hotchemi:permissionsdispatcher:${latest.version}‘    apt ‘com.github.hotchemi:permissionsdispatcher-processor:${latest.version}‘  }
Usage: 1. Annotations

Permissionsdispatcher only introduces a few annotations, keeping its generic API concise:

Note: The annotated method must not be private.

Annotations need to Description
@RuntimePermissions ? Issues that need to be added in activity or fragment to handle permissions
@NeedsPermission ? Note The method whose execution requires the action of one or more licenses (when the user grants permission, the method that uses this annotation is called)
@OnShowRationale Note This explains why a license/second/method is required. It passes the current permission request object in a permissionrequest that can be used to continue or abort the user input
@OnPermissionDenied Note This is the method that is called if the user does not grant permission
@OnNeverAskAgain Note If the user chooses to let the device "no longer ask" about the method that the license is called

The specific use is as follows:

@RuntimePermissionspublic class Mainactivity extends Appcompatactivity {@NeedsPermission (Manifest.permission.CAMERA ) void Showcamera () {Getsupportfragmentmanager (). BeginTransaction (). Replace (r.id.sample_content _fragment, Camerapreviewfragment.newinstance ()). Addtobackstack ("Camera"). Commitallowingsta    Teloss ();        } @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, (dial    OG, 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_nev    Erask, Toast.length_short). Show (); }}
2. Auto-Generated classes

Activity inherits the Appcompatactivity, yes, if you use Permissionsdispatcher for Rights Management, then the activity will inherit appcompatactivity. This will use the class in the Compatibility Pack. Also, the subject used in the corresponding activity should be modified to the subject in the corresponding Compatibility Pack.
At compile time, Permissionsdispatcher produces a class of mainactivitypermissionsdispatcher ([activity name] + permissionsdispatcher), You can use secure access to these license-protected methods.

Mainactivitypermissionsdispatcher need to compile themselves to have:

  @Overrideprotected 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);    }); Findviewbyid (r.id.button_contacts). Setonclicklistener (V, {//note:delegate the permission handling to generate    D method Mainactivitypermissionsdispatcher.showcontactswithcheck (this); });} @Overridepublic void Onrequestpermissionsresult (int requestcode, @NonNull string[] permissions, @NonNull int[]    Grantresults) {Super.onrequestpermissionsresult (Requestcode, permissions, grantresults); Note:delegate the permission handling to generated method Mainactivitypermissionsdispatcher.onrequestpermissionsres Ult (This, Requestcode, grantresults);}  
There are two ways to add SDK support versions:
    • 1, Androidmanifest
      <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="18" />
    • 2. Add SDK version control at the time of annotation
@RuntimePermissionspublic class MainActivity extends AppCompatActivity {    @NeedsPermission(value = Manifest.permission.WRITE_EXTERNAL_STORAGE, maxSdkVersion = 18)    void getStorage() {        // ...    }}
To use steps: First, add permissions in Manifest
  <uses-permission android:name="android.permission.CAMERA" />
Ii. adding annotations to activity
@RuntimePermissionspublic class Mainactivity extends Appcompatactivity {@Override protected void onCreate (Bundle sa        Vedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);    Butterknife.bind (this);        /** * Show Camera Permissions */@NeedsPermission (Manifest.permission.CAMERA) void Showcamera () {//Handle the method that needs to be handled when the user allows the permission Getsupportfragmentmanager (). BeginTransaction (). replace (R.id.sample_content_fragment, Camerapreviewfra    Gment.newinstance ()). Addtobackstack ("Camera"). Commitallowingstateloss (); } @OnShowRationale (Manifest.permission.CAMERA) void Showrationaleforcamera (final permissionrequest request) {//Prompt user The permissions are used by the dialog box new Alertdialog. Builder (This). Setmessage ("Open Permissions"). Setpositivebutton ("Allow", new dialoginterface.onclicklist Ener () {@Override public void OnClick (DialoginterfaCe dialog, int which) {request.proceed (); }}). Setnegativebutton ("Reject", new Dialoginterface.onclicklistener () {@Ov Erride public void OnClick (Dialoginterface dialog, int which) {Request.cancel ()                    ;    }}). Show ();        }/** * If the user rejects this permission execution method */@OnPermissionDenied (Manifest.permission.CAMERA) void Showdeniedforcamera () {    Toast.maketext (This, "Get permission Failed", Toast.length_short). Show (); } @OnNeverAskAgain (Manifest.permission.CAMERA) void Showneveraskforcamera () {Toast.maketext (this, "get permission Again",    Toast.length_short). Show (); }
Third, rewrite the callback method, and use Mainactivitypermissionsdispatcher (this method compiles build "Activity" +permissionsdispatcher)
  /**     * 权限请求回调,提示用户之后,用户点击“允许”或者“拒绝”之后调用此方法     *     * @param requestCode  定义的权限编码     * @param permissions  权限名称     * @param grantResults 允许/拒绝     */    @Override    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {        super.onRequestPermissionsResult(requestCode, permissions, grantResults);        MainActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);    }    @OnClick({R.id.button_camera, R.id.button_contacts})    public void onClick(View view) {        switch (view.getId()) {            case R.id.button_camera://                show(this, "相机");//                默认是没有此类的,需要编译下才会有此类                MainActivityPermissionsDispatcher.showCameraWithCheck(this);                break;        }    }
Attention
    • Permissions to use must be registered in Mnifest
    • Permissionsdispatcher relies on support-v4 by default libraries, so that you can use some permissions compat classes.
    • Need to add Support-v13 library together with Permissionsdispatcher in your project, it will enable native fragment support
Native 6.0 permissions using Android 6.0 change

See Also
Android 6.0 API Overview

In addition to providing many new features and functionality, Android 6.0 (API level 23) has made various changes to system and API behavior.
If you've previously published an Android app, be aware that your app may be affected by these platform changes.

Run-time permissions

This release introduces a new permission pattern that now allows users to manage app permissions directly at run time. This mode allows users to better understand and control permissions, while streamlining the installation and automatic update process for application developers. Users can grant or revoke permissions individually for each app that they install.
For apps that target platforms with Android 6.0 (API level 23) or later, be sure to check and request permissions at run time. To determine whether your app has been granted permission, call the new Checkselfpermission ()
Method. To request permission, call the new Requestpermissions ()
Method. Even if your app doesn't target Android 6.0 (API level 23), you should test your app in new permission mode.

Use Step 1 To add the required permissions in the Androidmanifest file.

This step and our previous development did not change, trying to apply for an undeclared permission may cause the program to crash.

2. Check Permissions
if (ContextCompat.checkSelfPermission(this,                Manifest.permission.READ_CONTACTS)        != PackageManager.PERMISSION_GRANTED) {}else{    //}

This involves a api,contextcompat.checkselfpermission, which is used primarily to detect whether a permission has been granted, and the return value of the method is Packagemanager.permission_ Denied or packagemanager.permission_granted. When returning to denied, a request for authorization is required.

3. Application for authorization
 ActivityCompat.requestPermissions(this,                new String[]{Manifest.permission.READ_CONTACTS},                MY_PERMISSIONS_REQUEST_READ_CONTACTS);

The method is asynchronous, the first parameter is the context, the second parameter is an array of strings for the permission to be requested, and the third parameter is Requestcode, which is used primarily for callback detection. Can be seen from the method name Requestpermissions and the second parameter, is to support a one-time application of multiple permissions, the system will be a dialog box to ask whether the user authorization.

4. Processing permission Request callback
@Overridepublic void onRequestPermissionsResult(int requestCode,        String permissions[], int[] grantResults) {    switch (requestCode) {        case MY_PERMISSIONS_REQUEST_READ_CONTACTS: {            // If request is cancelled, the result arrays are empty.            if (grantResults.length > 0                && grantResults[0] == PackageManager.PERMISSION_GRANTED) {                // permission was granted, yay! Do the                // contacts-related task you need to do.            } else {                // permission denied, boo! Disable the                // functionality that depends on this permission.            }            return;        }    }}

First verify that Requestcode navigates to your application, and then verify that grantresults corresponds to the result of the request, where the array corresponds to the second permission string array at the time of the request. If you apply for two permissions at the same time, then the length of the Grantresults is 2, recording the results of your application for two permissions respectively. If the application is successful, you can do your thing ~

For specific use see Demo,github:https://github.com/huangshuyuan/permissionsdispatcherdemo

Reference Document: http://blog.csdn.net/lmj623565791/article/details/50709663



Water playing upon Ripple
Links: http://www.jianshu.com/p/d299f22dfbdb
Source: Pinterest
Copyright belongs to the author. Commercial reprint please contact the author for authorization, non-commercial reprint please specify the source. Add

Now online a lot of permissions on the library, you can directly use, on GitHub search can
https://github.com/search?o=desc&q=android+permission&s=stars&type=Repositories&utf8=%E2%9C%93

Android Rights Management PermissionsDispatcher2.3.2 use + Native 6.0 permissions to use

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.