com.hundsun.yr.mobile.lib.permission.PermissionManager.java Source code

Java tutorial

Introduction

Here is the source code for com.hundsun.yr.mobile.lib.permission.PermissionManager.java

Source

/*
 * Copyright Google Inc. All Rights Reserved.
 *
 * 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.
 */
package com.hundsun.yr.mobile.lib.permission;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.annotation.StringRes;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import java.util.ArrayList;
import java.util.List;

/**
 * Utility to request and check System permissions for apps targeting Android M (API >= 23).
 */

/**
 * @Title: PermissionManager.java 
 * @Description: ???
 * SDK (API >= 23)
 * @date 2017-3-20 ?2:21:55 
 * @author:hejun.shen
 * @email:shenhj15971@hundsun.com 
 * @replace author:
 * @replace date:
 * @version V1.0   
 */
public class PermissionManager {

    /**?*/
    public static final int SETTINGS_REQ_CODE = 16061;

    private Object object;
    private String[] mPermissions;
    private int mRequestCode;

    private PermissionManager(Object object) {
        this.object = object;
    }

    public static PermissionManager with(Activity activity) {
        return new PermissionManager(activity);
    }

    public static PermissionManager with(Fragment fragment) {
        return new PermissionManager(fragment);
    }

    public PermissionManager permissions(String... permissions) {
        this.mPermissions = permissions;
        return this;
    }

    public PermissionManager addRequestCode(int requestCode) {
        this.mRequestCode = requestCode;
        return this;
    }

    public void request() {
        requestPermissions(object, mRequestCode, mPermissions);
    }

    /**
     * Check if the calling context has a set of permissions.
     */
    public static boolean hasPermissions(Context context, String... perms) {
        // Always return true for SDK < M, let the system deal with the permissions
        if (!PermissionUtils.isOverMarshmallow()) {
            return true;
        }

        if (perms == null || perms.length == 0) {
            return true;
        }

        for (String perm : perms) {
            boolean hasPerm = (ContextCompat.checkSelfPermission(context,
                    perm) == PackageManager.PERMISSION_GRANTED);
            if (!hasPerm) {
                return false;
            }
        }

        return true;
    }

    /**
     * ??
     * @param object
     * @param requestCode
     * @param permissions
     */
    public static void requestPermissions(final Object object, final int requestCode, final String... permissions) {

        checkCallingObjectSuitability(object);

        PermissionCallback mCallBack = (PermissionCallback) object;

        if (!PermissionUtils.isOverMarshmallow()) {
            mCallBack.onPermissionGranted(requestCode, permissions);
            return;
        }

        final List<String> deniedPermissions = PermissionUtils
                .findDeniedPermissions(PermissionUtils.getActivity(object), permissions);
        if (isEmpty(deniedPermissions)) {
            return;
        }

        boolean shouldShowRationale = false;
        for (String perm : deniedPermissions) {
            shouldShowRationale = shouldShowRationale
                    || PermissionUtils.shouldShowRequestPermissionRationale(object, perm);
        }

        if (isEmpty(deniedPermissions)) {
            mCallBack.onPermissionGranted(requestCode, permissions);
        } else {

            final String[] deniedPermissionArray = deniedPermissions.toArray(new String[deniedPermissions.size()]);

            if (shouldShowRationale) {
                //                Activity activity = PermissionUtils.getActivity(object);
                //                if (null == activity) {
                //                    return;
                //                }
                //                new AlertDialog.Builder(activity).setMessage(rationale)
                //                .setPositiveButton(positiveButton, new DialogInterface.OnClickListener() {
                //                    @Override public void onClick(DialogInterface dialog, int which) {
                //                        executePermissionsRequest(object, deniedPermissionArray, requestCode);
                //                    }
                //                })
                //                .setNegativeButton(negativeButton, new DialogInterface.OnClickListener() {
                //                    @Override public void onClick(DialogInterface dialog, int which) {
                //                        // act as if the permissions were denied
                //                        ((PermissionCallback) object).onEasyPermissionDenied(requestCode,
                //                                                                             deniedPermissionArray);
                //                    }
                //                })
                //                .create()
                //                .show();
                executePermissionsRequest(object, deniedPermissionArray, requestCode);
            } else {
                executePermissionsRequest(object, deniedPermissionArray, requestCode);
            }
        }
    }

    @TargetApi(23)
    private static void executePermissionsRequest(Object object, String[] perms, int requestCode) {
        checkCallingObjectSuitability(object);

        if (object instanceof Activity) {
            ActivityCompat.requestPermissions((Activity) object, perms, requestCode);
        } else if (object instanceof Fragment) {
            ((Fragment) object).requestPermissions(perms, requestCode);
        } else if (object instanceof android.app.Fragment) {
            ((android.app.Fragment) object).requestPermissions(perms, requestCode);
        }
    }

    /**
     * Handle the result of a permission request.
     */
    public static void onRequestPermissionsResult(Object object, int requestCode, String[] permissions,
            int[] grantResults) {
        checkCallingObjectSuitability(object);

        PermissionCallback mCallBack = (PermissionCallback) object;

        List<String> deniedPermissions = new ArrayList<>();
        for (int i = 0; i < grantResults.length; i++) {
            if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                deniedPermissions.add(permissions[i]);
            }
        }

        if (isEmpty(deniedPermissions)) {
            mCallBack.onPermissionGranted(requestCode, permissions);
        } else {
            mCallBack.onPermissionDenied(requestCode,
                    deniedPermissions.toArray(new String[deniedPermissions.size()]));
        }
    }

    /**
     * ??
     * @param list
     * @return
     */
    private static boolean isEmpty(List<String> list) {
        return list == null || list.isEmpty();
    }

    /**
     * with a {@code null} argument for the negative buttonOnClickListener.
     */
    public static boolean checkDeniedPermissionsNeverAskAgain(final Object object, String rationale,
            String... deniedPerms) {
        return checkDeniedPermissionsNeverAskAgain(object, rationale, android.R.string.ok, android.R.string.cancel,
                null, deniedPerms);
    }

    /**
     * OnActivityResult???
     * {@link PermissionManager#hasPermissions(Context, String...)}
     *
     * If user denied permissions with the flag NEVER ASK AGAIN, open a dialog explaining the
     * permissions rationale again and directing the user to the app settings. After the user
     * returned to the app, {@link Activity#onActivityResult(int, int, Intent)} or
     * {@link Fragment#onActivityResult(int, int, Intent)} or
     * {@link android.app.Fragment#onActivityResult(int, int, Intent)} will be called with
     * {@value #SETTINGS_REQ_CODE} as requestCode
     * <p>
     *
     * NOTE: use of this method is optional, should be called from
     * {@link PermissionCallback#onEasyPermissionDenied(int, String[])}
     *
     * @return {@code true} if user denied at least one permission with the flag NEVER ASK AGAIN.
     */
    public static boolean checkDeniedPermissionsNeverAskAgain(final Object object, String rationale,
            @StringRes int positiveButton, @StringRes int negativeButton,
            @Nullable DialogInterface.OnClickListener negativeButtonOnClickListener, String... deniedPerms) {
        boolean shouldShowRationale;
        for (String perm : deniedPerms) {
            shouldShowRationale = PermissionUtils.shouldShowRequestPermissionRationale(object, perm);

            if (!shouldShowRationale) {
                final Activity activity = PermissionUtils.getActivity(object);
                if (null == activity) {
                    return true;
                }

                new AlertDialog.Builder(activity).setMessage(rationale)
                        .setPositiveButton(positiveButton, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                Uri uri = Uri.fromParts("package", activity.getPackageName(), null);
                                intent.setData(uri);
                                startAppSettingsScreen(object, intent);
                            }
                        }).setNegativeButton(negativeButton, negativeButtonOnClickListener).create().show();

                return true;
            }
        }

        return false;
    }

    @TargetApi(11)
    private static void startAppSettingsScreen(Object object, Intent intent) {
        if (object instanceof Activity) {
            ((Activity) object).startActivityForResult(intent, SETTINGS_REQ_CODE);
        } else if (object instanceof Fragment) {
            ((Fragment) object).startActivityForResult(intent, SETTINGS_REQ_CODE);
        } else if (object instanceof android.app.Fragment) {
            ((android.app.Fragment) object).startActivityForResult(intent, SETTINGS_REQ_CODE);
        }
    }

    private static void checkCallingObjectSuitability(Object object) {

        if (!((object instanceof Fragment) || (object instanceof Activity)
                || (object instanceof android.app.Fragment))) {
            throw new IllegalArgumentException("Caller must be an Activity or a Fragment.");
        }

        if (!(object instanceof PermissionCallback)) {
            throw new IllegalArgumentException("Caller must implement PermissionCallback.");
        }
    }

}