Usage Analysis of Alert Dialog

Keywords: Android less Fragment github

Android 6.0 + permission application

Preface

Runtime Permissions are divided into two categories: common permissions and high-risk permissions. For general permission applications, only once when the APP is installed, and for high-risk permissions, starting with Android M (API.23), the application will be dynamically applied when the APP runs, so that users can choose whether to grant the permission to the APP, thus protecting the user's security.

Runtime permissions official documentation explains: https://developer.android.com/training/permissions/requesting.html

Note:
- If the device system is less than 6.0, permissions will only be asked when the APP is installed.
- If targetSdkVersion is less than 23, permissions will only be asked when APP is installed

The permissions for dynamic applications include the following.

Note: One privilege in the same group is authorized, and other privileges in the same group are automatically authorized.

Permission Group Permissions
CALENDAR READ_CALENDAR,WRITE_CALENDAR
CAMERA CAMERA
CONTACTS READ_CONTACTS,WRITE_CONTACTS , GET_ACCOUNTS
LOCATION ACCESS_FINE_LOCATION,ACCESS_COARSE_LOCATION
MICROPHONE RECORD_AUDIO
PHONE READ_PHONE_STATE,CALL_PHONE,READ_CALL_LOG,WRITE_CALL_LOG,
ADD_VOICEMAIL,USE_SIP,PROCESS_OUTGOING_CALLS
SENSORS BODY_SENSORS
SMS SEND_SMS,RECEIVE_SMS,READ_SMS,RECEIVE_WAP_PUSH,RECEIVE_MMS
STORAGE READ_EXTERNAL_STORAGE,WRITE_EXTERNAL_STORAGE

There are pictures and facts.

Runtime permission application

  1. First, determine whether permissions have been applied for
  2. If you do not apply for this permission, apply for permission
  3. The first application was rejected (the user did not click to ask no more). If you apply for permission again, you need to give the user a hint why you need to apply for the permission. After the user clicks to allow, you apply for the permission.

1. Judgment of authority

    int checkSelfPermission = ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA);
        if (checkSelfPermission != PackageManager.PERMISSION_GRANTED) {
            // No authority, need to apply
        } else {
            // With authority.
        }

2. Application for Authority

ActivityCompat.requestPermissions(MainActivity.this,new String[] { Manifest.permission.CAMERA }, REQUEST_STORAGE_PERMISSION);

When applying for permissions, the second parameter is the array format, that is, multiple permissions can be applied at the same time, but this is not recommended. REQUEST_STORAGE_PERMISSION is a custom request code.

If you apply for permissions in Fragment, you need to call Fragment's requestPermissions(...) method and change ActivityCompat.requestPermissions to requestPermissions. Otherwise, it calls back to the onRequestPermissionsResult method of Activity.

3. Processing permission application callback - onRequest Permissions Result

The operation after the success or failure of permission application needs to be implemented in this callback method.

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
            @NonNull int[] grantResults) {
        switch (requestCode) {
        case REQUEST_STORAGE_PERMISSION:
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Access Successful
            } else {
                // Privileges were not granted
            }
            break;
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
  • Because permissions can be applied for more than one at a time, the callback results are also returned as arrays. Here we take requesting only one privilege as an example. If the user grants privileges, then
    grantResults[0] = PackageManager.PERMISSION_GRANTED;

4.shouldShowRequestPermissionRationale(…)

1. The method returns false the first time permission is applied
2. The method returns true if the first application for permission fails and the user clicks on the denial of permission and applies for permission again.
3. If the user refuses authorization and chooses [no more reminders], the method returns false.
4. After the device system prohibits APP from using this permission, it returns false.

When a user refuses to grant permission, the system provides a way for us to explain why we want to apply for that permission. Therefore, we can display a Dialog to re-apply for permission from the user.

if (checkSelfPermission != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
            //Explain to the user the reason for the permission application
                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                builder.setTitle("Camera privileges are required for two-dimensional code scanning");
                builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        // Permission application
                    }
                });
                builder.setNegativeButton("Cancle", null);
                builder.show();
            } else {
               // Permission application
            }
        } else {
            // With authority.
        }

Third-party library EasyPermissions

Easy Permissions simplifies the steps of permission application, judgment and processing at Android runtime
Official documents https://github.com/googlesamples/easypermissions

1.build.gradle adds dependencies

dependencies {
    compile 'pub.devrel:easypermissions:0.3.0'

Note: If Error:Failed to resolve: com.android.support:appcompat-v7:25.1.0, you need to upgrade your SDK.

2. Check permissions

String[] perms = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
        if (!EasyPermissions.hasPermissions(this, perms)) {
           // No authority
        }

3. Application Authority

@AfterPermissionGranted(REQUEST_CODE_QRCODE_PERMISSIONS)
    private void requestCodeQRCodePermissions() {
        String[] perms = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
        if (!EasyPermissions.hasPermissions(this, perms)) {
            EasyPermissions.requestPermissions(this, "Scanning two-dimensional code requires opening camera and astigmatism", REQUEST_CODE_QRCODE_PERMISSIONS, perms);
        }else {
            // The privileges are already in place and other operations can be performed.
        }
    }

After the first application fails, the Dialog dialog box will pop up automatically if the application needs to be re-applied. The second parameter is Mesage of the dialog box, which explains to the user why the application for this privilege is made and enhances the possibility of user authorization.

AfterPermissionGranted is an optional annotation that, if tagged, automatically calls the method when the request value corresponding to the permission application passes.

4. Implement the EasyPermissions.PermissionCallbacks interface to directly handle the success or failure of permission applications

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // Forward results to EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }
    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        // Successful application for authority
    }
    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        // Failure of permission application
    }

5. Users click "No Questions"

If the user clicks "No Question", he can't get permission through APP, and the permission can only be re-granted in the settings interface. In this case, you can use the EasyPermissions. somePermission Permanently Denied (...) method to display a system dialog box to open the system settings interface.

@Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        // Failure of permission application
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this).build().show();
        }
    }

When the user returns to the APP interface from the settings interface, the authorization of permissions can be judged again in the onActivityResult(...) method.

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == AppSettingsDialog.DEFAULT_SETTINGS_REQ_CODE){
            String[] perms = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
            if (EasyPermissions.hasPermissions(this, perms)) {
                Toast.makeText(MainActivity.this,"Privileges are re-granted by the user through the settings interface",Toast.LENGTH_SHORT).show();
            }
        }
    }

Last

Attach demo address:
http://download.csdn.net/download/u014527323/9762717

Posted by brax23 on Thu, 04 Apr 2019 14:12:31 -0700