onRequestPermissionsResult

onRequestPermissionsResult

本文介绍了Android - onRequestPermissionsResult() 已弃用.有没有其他选择?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试实现写入和读取存储的请求权限.一切正常,但今天 Android 向我展示了 onRequestPermissionsResult(...) 方法已被弃用.StackOverflow 中有很多关于这个主题的问题,但不幸的是,它们已经过时了.

I tried to implement request permissions for writing and reading from storage. Everything worked good but today Android showed me that the method onRequestPermissionsResult(...) is deprecated. There are so many questions about this topic in StackOverflow, but unfortunately, they are outdated.

我在一个片段中调用了下面的方法.

I called the methods below in a fragment.

建议简单地调用:

requestPermissions(new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE},
StorageKeys.STORAGE_PERMISSION_CODE)

而不是我的方法:

ActivityCompat.requestPermissions(getActivity(),
new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE},
StorageKeys.STORAGE_PERMISSION_CODE))

但它们都表明 onRequestPermissionsResult(...) 已被弃用.

But both of them show that onRequestPermissionsResult(...) is deprecated.

这是我的 onRequestPermissionsResult(...) 方法:

Here is my onRequestPermissionsResult(...)-method:

  @Override
  public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                         @NonNull int[] grantResults) {

    if (requestCode == StorageKeys.STORAGE_PERMISSION_CODE) {

      if (grantResults.length > 0
          && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

        exportBibTex.createBibFile();
        exportBibTex.writeBibFile(exportBibTex
            .getBibDataLibrary(libraryModel, bookDao, noteDao));

        Toast.makeText(getContext(),
            getString(R.string.exported_file_stored_in) + '
'
                + File.separator + StorageKeys.DOWNLOAD_FOLDER + File.separator + fileName
                + StorageKeys.BIB_FILE_TYPE, Toast.LENGTH_LONG).show();

      } else {
        Toast.makeText(getContext(), R.string.storage_permission_denied,
            Toast.LENGTH_SHORT).show();
      }
    }
  }

这是一个简单的警报对话框,我在其中调用了 onRequestPermissionsResult(...):

Here is a simple alert dialog, in which I call the onRequestPermissionsResult(...):

  private void showRequestPermissionDialog() {
    AlertDialog.Builder reqAlertDialog = new AlertDialog.Builder(getContext());
    reqAlertDialog.setTitle(R.string.storage_permission_needed);
    reqAlertDialog.setMessage(R.string.storage_permission_alert_msg);

    reqAlertDialog.setPositiveButton(R.string.ok,
        (dialog, which) -> ActivityCompat.requestPermissions(getActivity(),
            new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE},
            StorageKeys.STORAGE_PERMISSION_CODE));
    reqAlertDialog.setNegativeButton(R.string.cancel,
        (dialog, which) -> dialog.dismiss());

    reqAlertDialog.create().show();
  }

我可以使用 onRequestPermissionsResult(...) 的替代方法吗?

Is there any alternative for onRequestPermissionsResult(...), that I can use?

推荐答案

onRequestPermissionsResult() 方法在 androidx.fragment.app.Fragment 中已弃用.

onRequestPermissionsResult() method is deprecated in androidx.fragment.app.Fragment.

所以你使用 registerForActivityResult() 方法代替 onRequestPermissionsResult().

So you use registerForActivityResult() method instead onRequestPermissionsResult().

你可以参考这个URL.

以下是 kotlin 代码.但你可以参考它.

Following is kotlin code. but you can refer it.

val permReqLuncher = registerForActivityResult(ActivityResultContracts.RequestPermission()){
  if (it) {
     // Good pass
  } else {
     // Failed pass
  }
}

我从以下 URL 添加了 java 代码.
如何获得新 ActivityResult API (1.3.0-alpha05) 中的权限请求?

I added java code from following URL.
How to get a permission request in new ActivityResult API (1.3.0-alpha05)?

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);

        }
    });

您可以请求多个权限.

    val requestMultiplePermissions = registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { permissions ->
        permissions.entries.forEach {
            Log.e("DEBUG", "${it.key} = ${it.value}")
        }
    }

    requestMultiplePermissions.launch(
        arrayOf(
            Manifest.permission.READ_CONTACTS,
            Manifest.permission.ACCESS_FINE_LOCATION
       )
    )

这篇关于Android - onRequestPermissionsResult() 已弃用.有没有其他选择?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-20 11:49