Created
May 28, 2019 00:53
-
-
Save guilhermealveslopes/2e34b38c1261ff7e70734e2209b834d1 to your computer and use it in GitHub Desktop.
Check for user permissions, on current activity.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* permissions request code | |
*/ | |
private final static int REQUEST_CODE_ASK_PERMISSIONS = 1; | |
/** | |
* Permissions that need to be explicitly requested from end user. | |
*/ | |
private static final String[] REQUIRED_SDK_PERMISSIONS = new String[]{ | |
Manifest.permission.CAMERA, | |
Manifest.permission.INTERNET, | |
Manifest.permission.READ_EXTERNAL_STORAGE, | |
Manifest.permission.WRITE_EXTERNAL_STORAGE, | |
Manifest.permission.BLUETOOTH, | |
Manifest.permission.BLUETOOTH_ADMIN, | |
Manifest.permission.ACCESS_COARSE_LOCATION}; | |
/** | |
* Checks the dynamically-controlled permissions and requests missing permissions from end user. | |
*/ | |
protected void checkPermissions() { | |
final List<String> missingPermissions = new ArrayList<String>(); | |
// check all required dynamic permissions | |
for (final String permission : REQUIRED_SDK_PERMISSIONS) { | |
final int result = ContextCompat.checkSelfPermission(this, permission); | |
if (result != PackageManager.PERMISSION_GRANTED) { | |
missingPermissions.add(permission); | |
} | |
} | |
if (!missingPermissions.isEmpty()) { | |
// request all missing permissions | |
final String[] permissions = missingPermissions | |
.toArray(new String[missingPermissions.size()]); | |
ActivityCompat.requestPermissions(this, permissions, REQUEST_CODE_ASK_PERMISSIONS); | |
} else { | |
final int[] grantResults = new int[REQUIRED_SDK_PERMISSIONS.length]; | |
Arrays.fill(grantResults, PackageManager.PERMISSION_GRANTED); | |
onRequestPermissionsResult(REQUEST_CODE_ASK_PERMISSIONS, REQUIRED_SDK_PERMISSIONS, | |
grantResults); | |
} | |
} | |
@Override | |
public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], | |
@NonNull int[] grantResults) { | |
switch (requestCode) { | |
case REQUEST_CODE_ASK_PERMISSIONS: | |
for (int index = permissions.length - 1; index >= 0; --index) { | |
if (grantResults[index] != PackageManager.PERMISSION_GRANTED) { | |
// exit the app if one permission is not granted | |
Toast.makeText(this, "Required permission '" + permissions[index] | |
+ "' not granted, exiting", Toast.LENGTH_LONG).show(); | |
finish(); | |
return; | |
} | |
} | |
// all permissions were granted | |
break; | |
} | |
} | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_home); | |
checkPermissions(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment