Reputation: 349
I am currently working with permissions in Android Studio.
I've checked how the tutorial does it, and I've seen that it's really obnoxious and long. The current code is this:
String[] InternetPermission = new String[]{Manifest.permission.INTERNET};
if (ContextCompat.checkSelfPermission(ViewingWindow.this, Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(ViewingWindow.this,
Manifest.permission.INTERNET)) {
InternetExplanation();
} else {
ActivityCompat.requestPermissions(ViewingWindow.this,
new String[]{Manifest.permission.INTERNET},
MY_PERMISSIONS_REQUEST_INTERNET);
}
}
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_INTERNET: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] != PackageManager.PERMISSION_GRANTED){
this.finishAffinity();
}
}
}
}
This is obviously rather long for a single permission check in my opinion. I've always wondered why the entire permission check isn't a simple if statement check.
Is there a reason for permission checks to be this long? If not, is there a way to try and optimise it?
Upvotes: 2
Views: 161
Reputation: 8149
In API 23 Or Android 6.0
we have to asked permission from user and you better know it already.
If user need single permission then you have to ask from user for so
ContextCompat.checkSelfPermission(ViewingWindow.this, Manifest.permission.INTERNET)
this line will came up.ActivityCompat.requestPermissions(ViewingWindow.this,
new String[]{Manifest.permission.INTERNET},
MY_PERMISSIONS_REQUEST_INTERNET);
this line came up.public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_INTERNET: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] != PackageManager.PERMISSION_GRANTED){
this.finishAffinity();
}
}
}
So you dont have write all code for single permission everytime so you just write it once and use OOPs power/features.
Upvotes: 2