mar*_*ato 7 java android android-fragments android-permissions
因此,我尝试使用新的 registerForActivityResult() 方法获得许可,并使用 .launch() 按钮单击请求,但它似乎没有打开任何窗口来请求它。我总是在 registerForActivityResult() 中出错。
// Permission to get photo from gallery, gets permission and produce boolean
private ActivityResultLauncher<String> mPermissionResult = registerForActivityResult(
new ActivityResultContracts.RequestPermission(),
new ActivityResultCallback<Boolean>() {
@Override
public void onActivityResult(Boolean result) {
if(result) {
Log.e(TAG, "onActivityResult: PERMISSION GRANTED");
} else {
Log.e(TAG, "onActivityResult: PERMISSION DENIED");
}
}
});
// Launch the permission window -- this is in onCreateView()
floatingActionButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mPermissionResult.launch(Manifest.permission.ACCESS_BACKGROUND_LOCATION);
}
});
Run Code Online (Sandbox Code Playgroud)
这是我的日志:onActivityResult: PERMISSION DENIED
更新
这个答案有效,但我找到了一个更好的解决方案来解决这里没有开放漏洞的权限请求。
从文档:
在您的活动/片段中,创建此字段:
// Register the permissions callback, which handles the user's response to the
// system permissions dialog. Save the return value, an instance of
// ActivityResultLauncher, as an instance variable.
private ActivityResultLauncher<String> requestPermissionLauncher =
registerForActivityResult(new RequestPermission(), isGranted -> {
if (isGranted) {
// Permission is granted. Continue the action or workflow in your
// app.
} 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.
}
});
Run Code Online (Sandbox Code Playgroud)
在同一活动/片段中的某处:
if (ContextCompat.checkSelfPermission(
context, Manifest.permission.ACCESS_BACKGROUND_LOCATION) ==
PackageManager.PERMISSION_GRANTED) {
performAction(...);
} else if (shouldShowRequestPermissionRationale(...)) {
// In an educational UI, explain to the user why your app requires this
// permission for a specific feature to behave as expected. In this UI,
// include a "cancel" or "no thanks" button that allows the user to
// continue using your app without granting the permission.
showInContextUI(...);
} else {
// You can directly ask for the permission.
// The registered ActivityResultCallback gets the result of this request.
requestPermissionLauncher.launch(Manifest.permission.ACCESS_BACKGROUND_LOCATION);
}
Run Code Online (Sandbox Code Playgroud)
如果您一直收到不合理的“权限被拒绝”,也许您没有在您的manifest.xml?
| 归档时间: |
|
| 查看次数: |
3865 次 |
| 最近记录: |