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

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

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

You can refer this URL.

Following is Kotlin code, but you can refer it:

val requestPermissionLauncher = registerForActivityResult(
    ActivityResultContracts.RequestPermission()
) { isGranted ->
    if (isGranted) {
        // PERMISSION GRANTED
    } else {
        // PERMISSION NOT GRANTED
    }
}

// Ex. Launching ACCESS_FINE_LOCATION permission.
private fun startLocationPermissionRequest() {
    requestPermissionLauncher.launch(Manifest.permission.ACCESS_FINE_LOCATION)
}

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

private ActivityResultLauncher<String> requestPermissionLauncher = registerForActivityResult(
    new ActivityResultContracts.RequestPermission(),
    new ActivityResultCallback<Boolean>() {
        @Override
        public void onActivityResult(Boolean result) {
            if (result) {
                // PERMISSION GRANTED
            } else {
                // PERMISSION NOT GRANTED
            }
        }
    }
);

// Ex. Launch the permission window -- this is in onCreateView()
floatingActionButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        requestPermissionLauncher.launch(Manifest.permission.ACCESS_FINE_LOCATION);    
    }
});

You can also request multiple permissions:

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

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

Leave a Comment