I am testing my app on Marshmallow 6.0
and it's getting force closed for the android.permission.READ_EXTERNAL_STORAGE
, even if it is defined in the Manifest already. Somewhere I have read that if I request permission at runtime then it would not force close your application. I have read this android document also, which is for requesting runtime permission.
So, I came to know that we can request a permission like below which is mentioned in the android document.
// Here, thisActivity is the current activity
if (ContextCompat.checkSelfPermission(thisActivity,
Manifest.permission.READ_CONTACTS)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
Manifest.permission.READ_CONTACTS)) {
// Show an expanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(thisActivity,
new String[]{Manifest.permission.READ_CONTACTS},
MY_PERMISSIONS_REQUEST_READ_CONTACTS);
// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// app-defined int constant. The callback method gets the
// result of the request.
}
}
The above code has a callback method onRequestPermissionsResult
which gets the result.
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
}
}
My question is where to exactly request the permission to user? Should we use the requesting permission at start of the app or should we do it as when the permission is required?
I like short code. I use RxPermission for permissions.
RxPermission is best library, which makes permission code unexpected just 1 line.
add in your
build.gradle
Isn't this easy?
This is worked for me !!! In Your Splash Activity of your application do the following,
1) Declare an int variable for request code,
2) Declare a string array with the number of permissions you need,
3) Next Check the condition for runtime permission on your onCreate method,
4) Now Declare onRequestPermissionsResult method to check the request code,
For requesting runtime permission i use GitHub Library
Add library in
Build.gradle
fileCreate Activity and add
PermissionListener
string.xml
https://material.io/guidelines/patterns/permissions.html This link will give you different type of scenario where permissions can be asked. Choose accordingly to your needs.