- Request runtime permissions from v4.Fragment and have callback go to Fragment?
- How to check permission in fragment
- 10 Answers 10
- Update
- Check Permissions from Fragment (the 2021 way)
- java version
- Handle Runtime Permissions in Android
- Types of Runtime Permissions
- Normal Permissions
- Signature Permissions
- Dangerous Permissions
- Before Marshmallow (API 23)
- Workflow of Runtime Permission
- Case 1:
- Case 2:
- Case 3:
- Solution of Case 2:
- Solution of Case 1 and Case 3:
- Handle the permissions request response
- Asking for Multiple Permissions at a time
- Permissions from Fragment
- Way 1:
- Way 2:
- So the best way is
- ContextCompat vs AcitvityCompat
- Shorten source code with 3rd Party Library
- Android — onRequestPermissionsResult() is deprecated. Are there any alternatives?
- 7 Answers 7
Request runtime permissions from v4.Fragment and have callback go to Fragment?
I’m having a weird issue that is causing a conflict. I had to switch to native Fragments to fix it, but there are bugs with that.
My original problem: I have a navigation drawer setup with v4 Fragments. To ask for permission in one of my Fragments I call ActivityCompat.requestPermissions(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION, 1); The prompt shows up just fine, but when I accept or deny the permission, nothing happens. The callback onRequestPermissionsResult() is never called. Instead it gets called in the Activity that my Fragments are attached to. Useless to me, I need the callback to work in the Fragment.
With this in mind I was told that I need to use FragmentCompat , but that only works with native Fragments (v13+) , so I changed navigation drawer to work from native Fragments instead of the v4 support library Fragments. However, because I’m using AppCompatActivity, certain things do not work, like addToBackStack() and going back to a previous fragment.
Long story short, does anyone know how I can use the v4.Fragment and still call for permission in the Fragment and get the callback to be in the Fragment ? I feel like this is a bug in Android that hasn’t been addressed but I’m not 100%.
Let me know if you need to see my code, it’s just the standard methods that you need for runtime permissions, I would like to work with v4 Fragments though which doesn’t work from my understanding.
Источник
How to check permission in fragment
I want to check a permission inside a fragment.
but onRequestPermissionsResult not called after allow or deny.
10 Answers 10
This is how I did, it works for me. Thanks!
For Activity :
For Fragment :
Fragment has requestPermissions() and onRequestPermissionsResult() methods, use it.
But checkSelfPermission() is from ActivityCompat (not require Activity , only Context ).
I have done following to check a permission inside a fragment.
Update
Since Fragment.requestPermissions is now deprecated, Google advises using registerForActivityResult instead.
I have done the request like this:
For more documentation on this method you can check this link.
Check Permissions from Fragment (the 2021 way)
The registerForActivityResult() method in fragment is now deprecated. The deprecation message suggests to use registerForActivityResult . So after some trial and errors, here is the 2021 way:
Suppose your fragment’s name is AwesomeFragment . Then in the constructor (before the fragment’s onCreate method to be precise), you initialize ActivityResultLauncher activityResultLauncher .
java version
Then maybe on some button click, you invoke the launch method:
Источник
Handle Runtime Permissions in Android
- From beginning with Android 6.0 Marshmallow (API LEVEL 23)(
Marshmallow was released on October 5, 2015 ), Google has introduced a new runtime permission model. - According to this model users are not prompted for permission at the time of installing the app, rather developers need to check for and request permission at runtime (i.e. The particular permission must required before performing any action)
- Users can then allow or deny the permission, users can also grant or revoke permission anytime from settings even if the app is already installed.
- Developers have to handle all the use cases. If not handled properly, it can cause application crashes.
Now here we’ll look into the android runtime permissions and handle them.
Types of Runtime Permissions
Android defines basically three types of permissions:
- Normal Permissions
- Signature Permissions
- Dangerous Permissions
Both Normal and Dangerous permissions must be defined in the Manifest file. But only Dangerous permissions are checked at runtime, Normal permissions are not.
Normal Permissions
Some permissions are automatically granted to the application. Just we need to declare those permissions in AndroidManifest.xml and it will work fine. Those permissions are called Normal Permissions. An example of a normal permission is INTERNET .
Normal Permissions are automatically granted to the application.
Signature Permissions
A permission that the system grants only if the requesting application is signed with the same certificate as the application that declared the permission. If the certificates match, the system automatically grants the permission without notifying the user or asking for the user’s explicit approval.
Dangerous Permissions
Some permissions may affect the users private information, or could potentially affect his data or the operation of other application are called Dangerous Permissions. For example, the ability to read the user’s contacts is a dangerous permission. Some other examples are CONTACTS , CAMERA , CALENDAR, LOCATION , PHONE , STORAGE , SENSORS , MICROPHONE, etc.
Dangerous permissions must be granted by the user at runtime to the app.
Dangerous permissions are grouped into categories that make it easier for the user to understand what they are allowing the application to do. If any permission in a Permission Group is granted. Another permission in the same group will be automatically granted as well. For example , once WRITE_CONTACTS is granted, application will also grant READ_CONTACTS and GET_ACCOUNTS as all three permissions in the same group.
Before Marshmallow (API 23)
Before Marshmallow (API 23) all the requested permissions are presented to the user before installing the application. If the user denies a required permission, the related application cannot be installed. And there was no way to grant or deny any permission after installation.
Workflow of Runtime Permission
Here is the workflow of runtime permission to open camera in android.
First of all we check the SDK Version. If SDK version is less than 23(Marshmallow) then we don’t need to ask for permission as Runtime Permission started from Marshmallow. And we can open camera.
If SDK version is equal to or greater than 23, then we check the permission is already granted or not by calling contextCompat.checkSelfPermission(). If permission is granted then we can open camera. If the permission is not granted we must request for the permission to the user. But in this case, we have to handle three cases.
Case 1:
The permission never asked before.
Case 2:
The permission asked before but user denied without checking ‘Never ask again’.
Case 3:
The permission asked before but user denied with checking ‘Never ask again’.
Only a method can handle our three cases . The method is shouldShowRequestPermissionRationale. the method returns a boolean value.
This method returns true if the the permission asked before but the user denied without checking ‘Never ask again’. which matches our Case 2.
But it will return false in two cases.
- If the permission is requested first time. Which matches our Case 1.
- If the permission asked before but the user denied with checking ‘Never ask again’. Which matches our Case 3.
So here only shouldShowRequestPermissionRationale method can match our three cases. Now just need to solve them with help of this method.
Solution of Case 2:
Solution of case 2 is very easy. Because the method shouldShowRequestPermissionRationale returns true only when the permission asked before but the user denied without checking ‘Never ask again’. So we can just give an explanation about why the app needs this permission. And if the user agree to our explanation we can request for permission again. That’s it.
Solution of Case 1 and Case 3:
But solution of case 1 and case 2 is little tricky. Because we know the method shouldShowRequestPermissionRationale returns false if the permission never asked before (Case 1) or the permission asked but the user denied with checking ‘Never ask again’ (Case 3). But we have to catch this two cases. How can we do that ?
Yes we can do this with the help of Shared Preferences , We can just put a flag on Shared Preferences for checking weather the permission is being asked first time or not. And the problem is solved. By this following code we can put our flag on Shared Preferences.
In firstTimeAsking, we just put a boolean flag with the permission string as key.
In isFirstTimeAsking, we get the value associated with the permission string and return it.
Notice that we set the default value as true. That’s why if the key is not in the preference file or even if the file itself is not created, the android framework will automatically create a file with the name we gave and will return the default value we set.
We will call this method every time when a permission request is required but after first call, we set the flag as false using firstTimeAsking(permission, false).
Here is the code.
We can put all these logic in a method and use a callback to get which case we should handle now. The code would be like this.
Now all the three cases are solved.
If you still getting confused on how to use it and you want to be more clear then see this full project Runtime Permission in Android in Github.
Handle the permissions request response
When the user responds to your app’s permission request, the system invokes your app’s onRequestPermissionsResult() method. So you have to override that method to find out whether the permission was granted or denied. And the same request code that you passed to requestPermissions() method is also passed to the callback. For deeper understanding, you see the following callback method:
Asking for Multiple Permissions at a time
Permissions from Fragment
In Fragment, you can ask for permission in two ways
Way 1:
In this way you will get permission result on onRequestPermissionsResult method of the activity not the fragment. That’s why you have to override the onRequestPermissionsResult method of the activity instead of Fragment.
Way 2:
In this way you will get permission result on onRequestPermissionsResult() method of fragment. But you must call
in activity’s onRequestPermissionsResult() method.
So the best way is
1) In fragment, ask permission just using
2) In activity’s onRequestPermissionsResult, call
so it will pass the result to fragment. Mind it this is the most important call and you must do it.
3) Now in fragment’s onRequestPermissionsResult, write the code that you want to handle the result.
ContextCompat vs AcitvityCompat
ActivityCompat is a subclass (child) of ContextCompat so you can pass either one whenever object of ContextCompat class is required.
This method is used simply for checking whether you are having requested permission available for your app or not.
This method is used for requesting permissions.
Shorten source code with 3rd Party Library
There are many popular permissions libraries that you can use for shorten your code. Some of them are given below:
I hope this article will helpful for you. Feel free to give your feedback in comment below: I would be very happy to get new suggestions.
Источник
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:
instead of my approach:
But both of them show that onRequestPermissionsResult(. ) is deprecated.
Here is my onRequestPermissionsResult(. )-method:
Here is a simple alert dialog, in which I call the onRequestPermissionsResult(. ):
Is there any alternative for onRequestPermissionsResult(. ), that I can use?
7 Answers 7
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.
You can request multiple permissions.
A simple way in Kotlin
This works for me — (kotlin):
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.
Most of the answers address the OP requirement. But I have found few things that are missing so I thought to provide a complete example (in Koltin)
The things that are missing are
A)Fragments must call registerForActivityResult() before they are created (i.e. initialization, onAttach(), or onCreate()). Other wise it won’t work and the app would crash.
java.lang.IllegalStateException: Fragment ProfileFragment
(210ad5a1-3286-4586-a48f-deac1d8e3eef id=0x7f09008b) is attempting to registerForActivityResult after being created. Fragments must call registerForActivityResult() before they are created (i.e. initialization, onAttach(), or onCreate()).
B) It is recommended to request permission when it is really needed. In my example when user clicks on Button with id locBtn , permission dialog is shown rather than showing when activity/fragment is created.
Источник