嗨,最近我开始在 android studio 中编码,我添加了 dexter 来获取访问用户存储的权限,但主要担心的是,即使不请求权限,代码也会直接显示拒绝阻止的消息。请帮忙
Dexter.withContext(this)
.withPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
.withListener(new PermissionListener() {
@Override
public void onPermissionGranted(PermissionGrantedResponse permissionGrantedResponse) {
Toast.makeText(MainActivity.this, "Thanks !", Toast.LENGTH_SHORT).show();
}
@Override
public void onPermissionDenied(PermissionDeniedResponse permissionDeniedResponse) {
Toast.makeText(MainActivity.this, "not granted", Toast.LENGTH_SHORT).show();
}
@Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permissionRequest, PermissionToken permissionToken) {
permissionToken.continuePermissionRequest();
}
})
.check();
可能是您的应用程序还没有权限。
从 Android 6 开始,某些权限被视为“危险权限”,即使您将所需的权限添加到 Android 清单中,您也不应该假设您的应用程序已经拥有它,并且您应该始终在运行时请求权限,然后再继续执行操作需要它们。
READ_EXTERNAL_STORAGE
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="your.package.name"
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application>
...
</application>
</manifest>
ActivityResultLauncher
并将其注册为活动结果,必须在{初始化、
onAttach()
或onCreate()
}片段创建方法之前,所以唯一的方法是将其初始化为全局片段变量
ActivityResultLauncher
来发起所需权限的请求。
public class myFragment extends Fragment {
...
ActivityResultLauncher<String> requestPermissionLauncher =
registerForActivityResult(new ActivityResultContracts.RequestPermission(), isGranted -> {
if (isGranted){
//continue your work flow
goDoSomething();}
else{
// Explain to the user that the feature is unavailable because
// the features requires a permission that the user has denied.
// At the same time, respect the user's decision. Don't link to
// system settings in an effort to convince the user to change
// their decision.
Toast.makeText(getContext(), "Can't continue without the required permissions", Toast.LENGTH_LONG).show();
}
});
public void getNecessaryPermissionsAndDoSomething() {
if (ActivityCompat.checkSelfPermission(getContext(),
Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
//check first if you have the permission or not
//if you don't then launch permission request dialog
requestPermissionLauncher.launch(Manifest.permission.READ_EXTERNAL_STORAGE);
}else goDoSomething(); //continue your work naturally
}
}
有关此内容的更多信息,您应该查看android开发人员文档更新
if (ActivityCompat.checkSelfPermission(getContext(),
Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
Log.e("permission","not granted");
else Log.e("permission","granted");
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<uses-feature android:name="android.hardware.camera.any" />
<uses-permission android:name="android.permission.CAMERA" />