終於等到你--權限工具類

Foreword

以前老是有小夥伴問 AndroidUtilCode 中有沒有權限工具類,但都被我懟回去了,讓先用着其餘第三方的,不過,到了現在的 1.11.0 版本的 AndroidUtilCode,這個一直拖欠着的權限工具類總算要問世了,之後小夥伴們若是用 AndroidUtilCode 須要動態受權的話,就不用再多依賴一個第三方庫了,下面來介紹下其功能。html

Functions

  • 兼容安卓各版本,包括 Android 8.0
  • 支持任意地方申請權限,不只限於 Activity 和 Fragment 等
  • 支持多權限同時申請
  • 採用鏈式調用,一句話解決權限申請

Achieve

首先來介紹其實現方式,關於運行時權限的介紹能夠在官網查看 -> 傳送門。關於危險權限列表,我封裝危險權限常量類 PermissionConstants.java,代碼以下所示:java

import android.Manifest;
import android.Manifest.permission;
import android.annotation.SuppressLint;
import android.support.annotation.StringDef;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;


/** * <pre> * author: Blankj * blog : http://blankj.com * time : 2017/12/29 * desc : 權限相關常量 * </pre> */
@SuppressLint("InlinedApi")
public final class PermissionConstants {

    public static final String CALENDAR   = Manifest.permission_group.CALENDAR;
    public static final String CAMERA     = Manifest.permission_group.CAMERA;
    public static final String CONTACTS   = Manifest.permission_group.CONTACTS;
    public static final String LOCATION   = Manifest.permission_group.LOCATION;
    public static final String MICROPHONE = Manifest.permission_group.MICROPHONE;
    public static final String PHONE      = Manifest.permission_group.PHONE;
    public static final String SENSORS    = Manifest.permission_group.SENSORS;
    public static final String SMS        = Manifest.permission_group.SMS;
    public static final String STORAGE    = Manifest.permission_group.STORAGE;

    private static final String[] GROUP_CALENDAR   = {
            permission.READ_CALENDAR, permission.WRITE_CALENDAR
    };
    private static final String[] GROUP_CAMERA     = {
            permission.CAMERA
    };
    private static final String[] GROUP_CONTACTS   = {
            permission.READ_CONTACTS, permission.WRITE_CONTACTS, permission.GET_ACCOUNTS
    };
    private static final String[] GROUP_LOCATION   = {
            permission.ACCESS_FINE_LOCATION, permission.ACCESS_COARSE_LOCATION
    };
    private static final String[] GROUP_MICROPHONE = {
            permission.RECORD_AUDIO
    };
    private static final String[] GROUP_PHONE      = {
            permission.READ_PHONE_STATE, permission.READ_PHONE_NUMBERS, permission.CALL_PHONE,
            permission.ANSWER_PHONE_CALLS, permission.READ_CALL_LOG, permission.WRITE_CALL_LOG,
            permission.ADD_VOICEMAIL, permission.USE_SIP, permission.PROCESS_OUTGOING_CALLS
    };
    private static final String[] GROUP_SENSORS    = {
            permission.BODY_SENSORS
    };
    private static final String[] GROUP_SMS        = {
            permission.SEND_SMS, permission.RECEIVE_SMS, permission.READ_SMS,
            permission.RECEIVE_WAP_PUSH, permission.RECEIVE_MMS,
    };
    private static final String[] GROUP_STORAGE    = {
            permission.READ_EXTERNAL_STORAGE, permission.WRITE_EXTERNAL_STORAGE
    };

    @StringDef({CALENDAR, CAMERA, CONTACTS, LOCATION, MICROPHONE, PHONE, SENSORS, SMS, STORAGE,})
    @Retention(RetentionPolicy.SOURCE)
    public @interface Permission {
    }

    public static String[] getPermissions(@Permission final String permission) {
        switch (permission) {
            case CALENDAR:
                return GROUP_CALENDAR;
            case CAMERA:
                return GROUP_CAMERA;
            case CONTACTS:
                return GROUP_CONTACTS;
            case LOCATION:
                return GROUP_LOCATION;
            case MICROPHONE:
                return GROUP_MICROPHONE;
            case PHONE:
                return GROUP_PHONE;
            case SENSORS:
                return GROUP_SENSORS;
            case SMS:
                return GROUP_SMS;
            case STORAGE:
                return GROUP_STORAGE;
        }
        return new String[]{permission};
    }
}
複製代碼

爲了適配 Android 8.0,我在申請權限的時候,會把清單文件中使用到的同組的權限都一次性申請完畢,相關代碼以下所示:android

private static final List<String> PERMISSIONS = getPermissions();

/** * 獲取應用權限 * * @return 清單文件中的權限列表 */
public static List<String> getPermissions() {
    return getPermissions(Utils.getApp().getPackageName());
}

/** * 獲取應用權限 * * @param packageName 包名 * @return 清單文件中的權限列表 */
public static List<String> getPermissions(final String packageName) {
    PackageManager pm = Utils.getApp().getPackageManager();
    try {
        return Arrays.asList(
                pm.getPackageInfo(packageName, PackageManager.GET_PERMISSIONS)
                        .requestedPermissions
        );
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
        return Collections.emptyList();
    }
}

/** * 設置請求權限 * * @param permissions 要請求的權限 * @return {@link PermissionUtils} */
public static PermissionUtils permission(@Permission final String... permissions) {
    return new PermissionUtils(permissions);
}

private PermissionUtils(final String... permissions) {
    mPermissions = new LinkedHashSet<>();
    for (String permission : permissions) {
        for (String aPermission : PermissionConstants.getPermissions(permission)) {
            if (PERMISSIONS.contains(aPermission)) {
                mPermissions.add(aPermission);
            }
        }
    }
    sInstance = this;
}
複製代碼

爲了支持任意地方均可以申請權限,我在 PermissionUtils.java 中封裝了 PermissionActivity,源碼以下所示:git

@RequiresApi(api = Build.VERSION_CODES.M)
public static class PermissionActivity extends Activity {
    public static void start(final Context context) {
        Intent starter = new Intent(context, PermissionActivity.class);
        starter.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(starter);
    }
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        if (sInstance.mThemeCallback != null) {
            sInstance.mThemeCallback.onActivityCreate(this);
        } else {
            Window window = getWindow();
            window.setBackgroundDrawable(null);
            int option = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
            window.getDecorView().setSystemUiVisibility(option);
            window.setStatusBarColor(Color.TRANSPARENT);
        }
        super.onCreate(savedInstanceState);
        if (sInstance.rationale(this)) {
            finish();
            return;
        }
        if (sInstance.mPermissionsRequest != null) {
            int size = sInstance.mPermissionsRequest.size();
            requestPermissions(sInstance.mPermissionsRequest.toArray(new String[size]), 1);
        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        sInstance.onRequestPermissionsResult(this);
        finish();
    }
}
複製代碼

這樣咱們即可以本身全權處理權限請求,但啓動的這個 PermissionActivity 的主題並不必定符合小夥伴們應用的 Activity 相關主題,因此我留了個設置主題的回調接口,好比能夠把這個 Activity 設置爲全屏等操做,這樣即可無感知地啓動一個 Activity,相關主題屬性以下:github

<style name="ActivityTranslucent">
    <item name="android:windowBackground">@android:color/transparent</item>
    <item name="android:colorBackgroundCacheHint">@null</item>
    <item name="android:windowIsTranslucent">true</item>
    <item name="android:windowNoTitle">true</item>
    <item name="android:windowContentOverlay">@null</item>
    <item name="android:activityOpenEnterAnimation">@null</item>
    <item name="android:activityOpenExitAnimation">@null</item>
    <item name="android:activityCloseEnterAnimation">@null</item>
    <item name="android:activityCloseExitAnimation">@null</item>
    <item name="android:statusBarColor">@android:color/transparent</item>
</style>
複製代碼

這個應該能適配不少應用了。api

固然,若是有設置 rationale 的話,也就是設置拒絕權限後再次請求的回調接口,此時便會走 sInstance.rationale(this),具體代碼以下所示:bash

@RequiresApi(api = Build.VERSION_CODES.M)
private boolean rationale(final Activity activity) {
    boolean isRationale = false;
    if (mOnRationaleListener != null) {
        for (String permission : mPermissionsRequest) {
            if (activity.shouldShowRequestPermissionRationale(permission)) {
                getPermissionsStatus(activity);
                mOnRationaleListener.rationale(new ShouldRequest() {
                    @Override
                    public void again(boolean again) {
                        if (again) {
                            startPermissionActivity();
                        } else {
                            requestCallback();
                        }
                    }
                });
                isRationale = true;
                break;
            }
        }
        mOnRationaleListener = null;
    }
    return isRationale;
}
複製代碼

邏輯就是若是 rationale 回調接口 執行了 shouldRequest.again(true);,那麼就會繼續申請下去,反之則再也不申請,多用在彈出一個提示對話框來讓用戶選擇是否繼續請求權限。app

最終就是發起請求和接受請求,並把最終狀態保存到 mPermissionsGrantedmPermissionsDeniedmPermissionsDeniedForever 中,最終回調 callback 的接口,相關代碼以下所示:ide

private void getPermissionsStatus(final Activity activity) {
    for (String permission : mPermissionsRequest) {
        if (isGranted(permission)) {
            mPermissionsGranted.add(permission);
        } else {
            mPermissionsDenied.add(permission);
            if (!activity.shouldShowRequestPermissionRationale(permission)) {
                mPermissionsDeniedForever.add(permission);
            }
        }
    }
}

private void requestCallback() {
    if (mSimpleCallback != null) {
        if (mPermissionsRequest.size() == 0
                || mPermissions.size() == mPermissionsGranted.size()) {
            mSimpleCallback.onGranted();
        } else {
            if (!mPermissionsDenied.isEmpty()) {
                mSimpleCallback.onDenied();
            }
        }
        mSimpleCallback = null;
    }
    if (mFullCallback != null) {
        if (mPermissionsRequest.size() == 0
                || mPermissions.size() == mPermissionsGranted.size()) {
            mFullCallback.onGranted(mPermissionsGranted);
        } else {
            if (!mPermissionsDenied.isEmpty()) {
                mFullCallback.onDenied(mPermissionsDeniedForever, mPermissionsDenied);
            }
        }
        mFullCallback = null;
    }
    mOnRationaleListener = null;
    mThemeCallback = null;
}

private void onRequestPermissionsResult(final Activity activity) {
    getPermissionsStatus(activity);
    requestCallback();
}
複製代碼

Use

說了那麼多,總算到使用了,其實使用起來很是方便,一句話便可,好比咱們要申請 android.permission.READ_CALENDAR 權限,那麼咱們能夠去 PermissionConstants.java 中找到其所屬組,也就是 CALENDAR,而應用是全屏類型的應用,那麼咱們能夠像下面這樣發起請求。工具

PermissionUtils.permission(PermissionConstants.CALENDAR)
        .rationale(new PermissionUtils.OnRationaleListener() {
            @Override
            public void rationale(final ShouldRequest shouldRequest) {
                PermissionHelper.showRationaleDialog(shouldRequest);
            }
        })
        .callback(new PermissionUtils.FullCallback() {
            @Override
            public void onGranted(List<String> permissionsGranted) {
                updateAboutPermission();
            }
            @Override
            public void onDenied(List<String> permissionsDeniedForever, List<String> permissionsDenied) {
                if (!permissionsDeniedForever.isEmpty()) {
                    PermissionHelper.showOpenAppSettingDialog();
                }
                LogUtils.d(permissionsDeniedForever, permissionsDenied);
            }
        })
        .theme(new PermissionUtils.ThemeCallback() {
            @Override
            public void onActivityCreate(Activity activity) {
                ScreenUtils.setFullScreen(activity);
            }
        })
        .request();
複製代碼

若是還有不會的能夠參考 AndroidUtilCode 中的 demo -> PermissionActivity.java

Tips:推薦小夥伴們最好把權限請求相關的操做都放在一個 helper 類中,就像我 AndroidUtilCode 中 demo 的作法,建立一個 PermissionHelper.java,畢竟有不少權限請求都是重複。

Conclusion

好了,本次的權限工具類介紹就到此結束了,在這麼簡潔的工具類背後都是本柯基辛勤付出的汗水,瘋狂地 debug,瘋狂地測試來消除內存泄漏的問題,雖然路途很艱辛,但最終仍是成功地完成了該工具類,終於等到你。

相關文章
相關標籤/搜索