java - 如何在新的 ActivityResult API (1.3.0-alpha05) 中获取权限请求?
问题描述
因此,我尝试使用新的 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);
}
});
这是我的日志: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.
}
});
在同一个活动/片段中的某处:
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);
}
如果您一直收到不合理的“权限被拒绝”,也许您没有在您的manifest.xml
?
推荐阅读
- postgresql - postgres 列从父级自动更新
- html - HTML5 视频不显示控件
- php - 无法使用 PHP 连接到我在 mysql 工作台中创建的数据库?
- javascript - 如何使用带有事件处理程序的自定义钩子?
- r - 细微差别的模糊匹配
- flutter - 两个 BLE 特性上的 setNotifyValue
- javascript - 我如何动态创建现有对象 JavaScript 的键、值
- vba - 在受密码保护的情况下进入 VBA
- angular - 如何在每次测试后停止重新登录(Cypress-Angular)?
- cadence-workflow - 在任何低优先级工作流之前执行所有高优先级节奏工作流