1. 程式人生 > >android6.0動態許可權申請工具類

android6.0動態許可權申請工具類

一、分析

android6.0後,僅在manifest.xml清單中配置相關許可權時,如果將targetSdkVersion設定為23及以上,部分敏感許可權需要動態申請後才能使用;如果不想處理6.0以上的適配,請將targetSdkVersion設定為22或以下;

這些敏感許可權也是危險許可權Dangerous-Permisson,能夠獲取到使用者的隱私;

共9類

CALENDAR    日曆
CAMERA      相機
CONTACTS    聯絡人
LOCATION    定位
MICROPHONE  麥克相關,比如錄音
PHONE       手機狀態
SENSORS     感測器
SMS         簡訊
STORAGE     儲存許可權

詳細許可權

group:android.permission-group.CONTACTS
    permission:android.permission.WRITE_CONTACTS
    permission:android.permission.GET_ACCOUNTS    
    permission:android.permission.READ_CONTACTS

  group:android.permission-group.PHONE
    permission:android.permission.READ_CALL_LOG
    permission:android.permission
.READ_PHONE_STATE permission:android.permission.CALL_PHONE permission:android.permission.WRITE_CALL_LOG permission:android.permission.USE_SIP permission:android.permission.PROCESS_OUTGOING_CALLS permission:com.android.voicemail.permission.ADD_VOICEMAIL group:android.permission
-group.CALENDAR permission:android.permission.READ_CALENDAR permission:android.permission.WRITE_CALENDAR group:android.permission-group.CAMERA permission:android.permission.CAMERA group:android.permission-group.SENSORS permission:android.permission.BODY_SENSORS group:android.permission-group.LOCATION permission:android.permission.ACCESS_FINE_LOCATION permission:android.permission.ACCESS_COARSE_LOCATION group:android.permission-group.STORAGE permission:android.permission.READ_EXTERNAL_STORAGE permission:android.permission.WRITE_EXTERNAL_STORAGE group:android.permission-group.MICROPHONE permission:android.permission.RECORD_AUDIO group:android.permission-group.SMS permission:android.permission.READ_SMS permission:android.permission.RECEIVE_WAP_PUSH permission:android.permission.RECEIVE_MMS permission:android.permission.RECEIVE_SMS permission:android.permission.SEND_SMS permission:android.permission.READ_CELL_BROADCASTS

二、程式碼

許可權工具類

public class PermissionUtil {
    /**
     * 是否需要檢查許可權
     */
    private static boolean needCheckPermission() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M;
    }

    /**
     * 獲取sd儲存卡讀寫許可權
     *
     * @return 是否已經獲取許可權,沒有自動申請
     */
    public static boolean getExternalStoragePermissions(@NonNull Activity activity, int requestCode) {
        return requestPerssions(activity, requestCode, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE);
    }

    /**
     * 獲取拍照許可權
     *
     * @return 是否已經獲取許可權,沒有自動申請
     */
    public static boolean getCameraPermissions(@NonNull Activity activity, int requestCode) {
        return requestPerssions(activity, requestCode, Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE);
    }
    /**
     * 獲取麥克風許可權
     *
     * @return 是否已經獲取許可權,沒有自動申請
     */
    public static boolean getAudioPermissions(@NonNull Activity activity, int requestCode) {
        return requestPerssions(activity, requestCode, Manifest.permission.RECORD_AUDIO, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE);
    }
    /**
     * 獲取定位許可權
     *
     * @return 是否已經獲取許可權,沒有自動申請
     */
    public static boolean getLocationPermissions(@NonNull Activity activity, int requestCode) {
        return requestPerssions(activity, requestCode, Manifest.permission.ACCESS_COARSE_LOCATION);
    }
    /**
     * 獲取讀取聯絡人許可權
     *
     * @return 是否已經獲取許可權,沒有自動申請
     */
    public static boolean getContactsPermissions(@NonNull Activity activity, int requestCode) {
        return requestPerssions(activity, requestCode, Manifest.permission.READ_CONTACTS);
    }
    /**
     * 獲取傳送簡訊許可權
     *
     * @return 是否已經獲取許可權,沒有自動申請
     */
    public static boolean getSendSMSPermissions(@NonNull Activity activity, int requestCode) {
        return requestPerssions(activity, requestCode, Manifest.permission.SEND_SMS);
    }
    /**
     * 獲取撥打電話許可權
     *
     * @return 是否已經獲取許可權,沒有自動申請
     */
    public static boolean getCallPhonePermissions(@NonNull Activity activity, int requestCode) {
        return requestPerssions(activity, requestCode, Manifest.permission.CALL_PHONE);
    }







    public static List<String> getDeniedPermissions(@NonNull Activity activity, @NonNull String... permissions) {
        if (!needCheckPermission()) {
            return null;
        }
        List<String> deniedPermissions = new ArrayList<>();
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(activity, permission) != PackageManager.PERMISSION_GRANTED) {
                deniedPermissions.add(permission);
            }
        }
        if (!deniedPermissions.isEmpty()) {
            return deniedPermissions;
        }

        return null;
    }

    /**
     * 是否擁有許可權
     */
    public static boolean hasPermissons(@NonNull Activity activity, @NonNull String... permissions) {
        if (!needCheckPermission()) {
            return true;
        }
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(activity, permission) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    /**
     * 是否拒絕了再次申請許可權的請求(點選了不再詢問)
     */
    public static boolean deniedRequestPermissonsAgain(@NonNull Activity activity, @NonNull String... permissions) {
        if (!needCheckPermission()) {
            return false;
        }
        List<String> deniedPermissions = getDeniedPermissions(activity, permissions);
        for (String permission : deniedPermissions) {
            if (ContextCompat.checkSelfPermission(activity, permission) != PackageManager.PERMISSION_DENIED) {

                if (!ActivityCompat.shouldShowRequestPermissionRationale(activity, permission)) {
                    //當用戶之前已經請求過該許可權並且拒絕了授權這個方法返回true
                    return true;
                }
            }
        }

        return false;
    }

    /**
     * 開啟app詳細設定介面<br/>
     * <p>
     * 在 onActivityResult() 中沒有必要對 resultCode 進行判斷,因為使用者只能通過返回鍵才能回到我們的 App 中,<br/>
     * 所以 resultCode 總是為 RESULT_CANCEL,所以不能根據返回碼進行判斷。<br/>
     * 在 onActivityResult() 中還需要對許可權進行判斷,因為使用者有可能沒有授權就返回了!<br/>
     */
    public static void startApplicationDetailsSettings(@NonNull Activity activity, int requestCode) {
        Toast.makeText(activity, "點選許可權,並開啟全部許可權", Toast.LENGTH_SHORT).show();

        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", activity.getPackageName(), null);
        intent.setData(uri);
        activity.startActivityForResult(intent, requestCode);


    }

    /**
     * 申請許可權<br/>
     * 使用onRequestPermissionsResult方法,實現回撥結果或者自己普通處理
     *
     * @return 是否已經獲取許可權
     */
    public static boolean requestPerssions(Activity activity, int requestCode, String... permissions) {

        if (!needCheckPermission()) {
            return true;
        }

        if (!hasPermissons(activity, permissions)) {
            if (deniedRequestPermissonsAgain(activity, permissions)) {
                startApplicationDetailsSettings(activity, requestCode);
                //返回結果onActivityResult
            } else {
                List<String> deniedPermissions = getDeniedPermissions(activity, permissions);
                if (deniedPermissions != null) {
                    ActivityCompat.requestPermissions(activity, deniedPermissions.toArray(new String[deniedPermissions.size()]), requestCode);
                    //返回結果onRequestPermissionsResult
                }
            }
            return false;
        }
        return true;
    }

    /**
     * 申請許可權返回方法
     */
    public static void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                                  @NonNull int[] grantResults, @NonNull OnRequestPermissionsResultCallbacks callBack) {
        // Make a collection of granted and denied permissions from the request.
        List<String> granted = new ArrayList<>();
        List<String> denied = new ArrayList<>();
        for (int i = 0; i < permissions.length; i++) {
            String perm = permissions[i];
            if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                granted.add(perm);
            } else {
                denied.add(perm);
            }
        }

        if (null != callBack) {
            if (!granted.isEmpty()) {
                callBack.onPermissionsGranted(requestCode, granted, denied.isEmpty());
            }
            if (!denied.isEmpty()) {
                callBack.onPermissionsDenied(requestCode, denied, granted.isEmpty());
            }
        }


    }


    /**
     * 申請許可權返回
     */
//    public interface OnRequestPermissionsResultCallbacks extends ActivityCompat.OnRequestPermissionsResultCallback {
    public interface OnRequestPermissionsResultCallbacks {

        /**
         * @param isAllGranted 是否全部同意
         */
        void onPermissionsGranted(int requestCode, List<String> perms, boolean isAllGranted);

        /**
         * @param isAllDenied 是否全部拒絕
         */
        void onPermissionsDenied(int requestCode, List<String> perms, boolean isAllDenied);

    }
}

在Activity中使用

public class MainActivity extends AppCompatActivity implements PermissionUtil.OnRequestPermissionsResultCallbacks {

    private final String TAG = MainActivity.class.getSimpleName();
    private final int REQUEST_CODE_CAMERA = 101;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


    }

    public void requestCameraPermisson(View view) {
        //manifest.xml清單中需配置<uses-permission android:name="android.permission.CAMERA" />
        //manifest.xml清單中需配置<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
        //manifest.xml清單中需配置<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
        PermissionUtil.requestPerssions(this, REQUEST_CODE_CAMERA, Manifest.permission.CAMERA, Manifest.permission.READ_SMS, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE);
        PermissionUtil.getCameraPermissions(this, REQUEST_CODE_CAMERA);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionUtil.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms, boolean isAllGranted) {
        Log.e(TAG,"同意:" + perms.size() + "個許可權,isAllGranted=" + isAllGranted);
        for (String perm : perms) {
            Log.e(TAG,"同意:" + perm);
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms, boolean isAllDenied) {
        Log.e(TAG,"拒絕:" + perms.size() + "個許可權,isAllDenied=" + isAllDenied);
        for (String perm : perms) {
            Log.e(TAG,"拒絕:" + perm);
        }
    }

    public void goPermissionsSettings(View view) {
        PermissionUtil.startApplicationDetailsSettings(this, 123);
    }

    public void isReadSMSPermissionDenied(View view) {
        //manifest.xml清單中需配置<uses-permission android:name="android.permission.READ_SMS" />
        boolean isForbidden  = PermissionUtil.deniedRequestPermissonsAgain(this, Manifest.permission.READ_SMS);
        Log.e(TAG,"讀取簡訊許可權是否禁止詢問=" + isForbidden);
    }

    public void readSMS(View view) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                ArrayList<HashMap<String, String>> hashMaps = readAllSMS();
                for (HashMap<String, String> hashMap : hashMaps) {
                    Log.e(TAG,hashMap.get("addr") + "," + hashMap.get("person") + "," + hashMap.get("body"));
                }
            }
        }).run();
    }

    private Uri SMS_INBOX = Uri.parse("content://sms/");

    private ArrayList<HashMap<String, String>> readAllSMS() {
        Cursor cursor = managedQuery(SMS_INBOX, new String[]{"address", "person", "body"},
                null, null, null);
        ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
        if (cursor.moveToFirst()) {
            int addrIdx = cursor.getColumnIndex("address");
            int personIdx = cursor.getColumnIndex("person");
            int bodyIdx = cursor.getColumnIndex("body");
            do {
                String addr = cursor.getString(addrIdx);
                String person = cursor.getString(personIdx);
                String body = cursor.getString(bodyIdx);

                HashMap<String, String> item = new HashMap<String, String>();
                item.put("addr", addr);
                item.put("person", person);
                item.put("body", body);
                list.add(item);
            } while (cursor.moveToNext());
        }
        return list;
    }

}