先貼上這個(gè)開源庫的主頁地址:
這是一個(gè)不錯(cuò)的老外寫的開源庫挤忙,用來簡化Android動(dòng)態(tài)權(quán)限檢測赢赊,因?yàn)锳ndroid 6.0以及以后的版本加入了動(dòng)態(tài)權(quán)限的檢測索抓,來優(yōu)化系統(tǒng)的安全性险领。但是當(dāng)我們自己去寫代碼的時(shí)候就會(huì)遇到去動(dòng)態(tài)申請權(quán)限的問題宅倒,Android明確規(guī)定了一些權(quán)限一定要?jiǎng)討B(tài)申請才能使用躏啰,不然會(huì)報(bào)SecurityException卓嫂。
當(dāng)然了榔昔,Android原生肯定是提供了申請這些權(quán)限的接口艳狐,以及獲取當(dāng)前權(quán)限是否被用戶確認(rèn)申請等定硝,但是在使用過程中比較復(fù)雜,所以下面介紹這個(gè)開源庫的使用毫目,非常簡單蔬啡。
首先新建Android工程項(xiàng)目,并且在build.gradle中添加依賴:
dependencies {
//...
implementation 'com.karumi:dexter:5.0.0'
}
使用起來也是非常方便镀虐,
public MyActivity extends Activity {
@Override public void onCreate() {
super.onCreate();
Dexter.withActivity(activity)
.withPermission(permission)
.withListener(listener)
.check();
}
}
單個(gè)權(quán)限箱蟆,
Dexter.withActivity(this)
.withPermission(Manifest.permission.CAMERA)
.withListener(new PermissionListener() {
@Override public void onPermissionGranted(PermissionGrantedResponse response) {/* ... */}
@Override public void onPermissionDenied(PermissionDeniedResponse response) {/* ... */}
@Override public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) {/* ... */}
}).check();
多個(gè)權(quán)限,
Dexter.withActivity(this)
.withPermissions(
Manifest.permission.CAMERA,
Manifest.permission.READ_CONTACTS,
Manifest.permission.RECORD_AUDIO
).withListener(new MultiplePermissionsListener() {
@Override public void onPermissionsChecked(MultiplePermissionsReport report) {/* ... */}
@Override public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {/* ... */}
}).check();
是不是很簡單刮便,最后給出一個(gè)示例空猜,申請三個(gè)權(quán)限,當(dāng)某個(gè)全選被拒絕時(shí),提示跳轉(zhuǎn)設(shè)置辈毯,
MultiplePermissionsListener mMultiplePermissionListener =
SnackbarOnAnyDeniedMultiplePermissionsListener.Builder
.with(findViewById(android.R.id.content), "Some permissions need to access!")
.withOpenSettingsButton("Settings")
.withCallback(new Snackbar.Callback() {
@Override
public void onShown(Snackbar sb) {
super.onShown(sb);
}
@Override
public void onDismissed(Snackbar transientBottomBar, int event) {
super.onDismissed(transientBottomBar, event);
}
}).build();
Dexter.withActivity(this)
.withPermissions(Manifest.permission.CAMERA,
Manifest.permission.READ_CONTACTS,
Manifest.permission.RECORD_AUDIO)
.withListener(mMultiplePermissionListener).check();
Very Easy, Right?
最后附上demo視頻: