Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a permission request in new ActivityResult API (1.3.0-alpha05)?

so, I tried to get a permission with the new registerForActivityResult() method and ask for with button click with .launch() and it doesn´t seem to be opening any window to ask for it. I´m always getting false in 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);

        }
    });

This is my LOG always: onActivityResult: PERMISSION DENIED

like image 436
markato Avatar asked Jun 04 '20 19:06

markato


People also ask

How do I get the result of an activity request?

Actually receiving the result requires some slightly tedious code. You need to check the request code to see if it was your activity that requested what’s being returned, then you need to check to see whether or not the request was successful. After that, you pull the data out of the Intent object.

How does the requestpermissions () method work?

If your app doesn't already have the permission it needs, the app must call one of the requestPermissions () methods to request the appropriate permissions. Your app passes the permissions it wants and an integer request code that you specify to identify this permission request. This method functions asynchronously.

What is the difference between registerforactivityresult () and onrequestpermissionsresult () methods in Android?

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. I added java code from following URL.

Is onrequestpermissionsresult deprecated in Android?

Android - onRequestPermissionsResult () is deprecated. Are there any alternatives? Bookmark this question. Show activity on this post. 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.


2 Answers

UPDATE
This answer works, but I found a better solution for permission requests with no open holes here.


From docs:

In your Activity/Fragment, create this field:

// 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.
        }
    });

Somewhere in the same Activity/Fragment:

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

If you are getting unreasonable "Permission denied" all the time, maybe you did not declare it in your manifest.xml?

like image 114
Ace Avatar answered Sep 23 '22 05:09

Ace


Looking at Update to androidx.fragment:fragment:1.3.0-alpha08: registerForActivityResult not allowed after onCreate anymore. How to use after onCreate?,

private lateinit var checkLocationPermission: ActivityResultLauncher<Array<String>>

// Initialize checkLocationPermission in onAttach or onCreate.
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

    checkLocationPermission = registerForActivityResult(
        ActivityResultContracts.RequestMultiplePermissions()) { permissions ->
        if (permissions[Manifest.permission.ACCESS_FINE_LOCATION] == true ||
            permissions[Manifest.permission.ACCESS_COARSE_LOCATION] == true) {
            initUserLocation()
        } else {
            // Permission was denied. Display an error message.
        }
    }
}

fun showMap() {
    if (ActivityCompat.checkSelfPermission(requireContext(),
        Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED ||
        ActivityCompat.checkSelfPermission(requireContext(),
            Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
        initUserLocation()
    } else {
        checkLocationPermission.launch(arrayOf(Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION))
    }
}

private fun initUserLocation() {
    googleMap?.isMyLocationEnabled = true
}
like image 39
CoolMind Avatar answered Sep 22 '22 05:09

CoolMind