Question

[Solved] Android – onRequestPermissionsResult() is deprecated. Are there any alternatives?

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.

It was suggested simply to call:

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

instead of my approach:

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

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

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

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

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

Enquirer: ashley

||

Solution #1:

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

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

You can refer this URL.

Following is kotlin code. but you can refer it.

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

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

        }
    });

You can request multiple permissions.

    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
       )
    )
Respondent: ashley

Solution #2:

This works for me – (kotlin):

private fun checkPermissions() {
    if (mContext?.let {
        ContextCompat.checkSelfPermission(
            it,
            READ_EXTERNAL_STORAGE
        )
    } != PackageManager.PERMISSION_GRANTED) {
    Log.d(TAG, "Request Permissions")
    requestMultiplePermissions.launch(
        arrayOf(READ_EXTERNAL_STORAGE, WRITE_EXTERNAL_STORAGE))
 } else {
        Log.d(TAG, "Permission Already Granted")
    }
}

private val requestMultiplePermissions =
    registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { permissions ->
        permissions.entries.forEach {
            Log.d(TAG, "${it.key} = ${it.value}")
        }
        if (permissions[READ_EXTERNAL_STORAGE] == true && permissions[WRITE_EXTERNAL_STORAGE] == true) {
            Log.d(TAG, "Permission granted")
        } else {
            Log.d(TAG, "Permission not granted")
        }
    }
Respondent: Daniel.Wang

Solution #3:

You can use some external library for permission handling to reduce some boilerplate code. I use Dexter library. Rx Permissions is also good choice if you are using RxJava2.

Respondent: Andy Cass

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Most Popular

To Top
India and Pakistan’s steroid-soaked rhetoric over Kashmir will come back to haunt them both clenbuterol australia bossier man pleads guilty for leadership role in anabolic steriod distribution conspiracy