Skip to content

Instantly share code, notes, and snippets.

@thejakeofink
Created March 11, 2016 18:28
Show Gist options
  • Save thejakeofink/1cd06105f5e3698ee9db to your computer and use it in GitHub Desktop.
Save thejakeofink/1cd06105f5e3698ee9db to your computer and use it in GitHub Desktop.
// All requesting permissions needs to happen inside of an Activity.
// When you request a permission it is like calling startActivityForResult()
// So you need to be able to have the call back that will handle whether the
// permission was granted or not. Checking permissions can be done from any context
// Also keep in mind for this implementation of runtime permissions you need to
// have included the support library in your build.gradle file.
// this is for your use only so this just needs to be distinct for your purposes.
private static final int REQUEST_LOCATION_PERMISSION = 101;
// Check for the permission you need
String permission = Manifest.permission.ACCESS_FINE_LOCATION;
if (ContextCompat.checkSelfPermission(this, permissionString) == PackageManager.PERMISSION_GRANTED) {
// access location to your heart's content!
} else {
// This checks if the user has been prompted for this permission already in this app. If so you may want to explain
// why you need this permission.
if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,permissionString) {
// Show something that will explain why they should allow, then prompt from there.
} else {
ActivityCompat.requestPermissions(this, new String[] {permissionString}, REQUEST_LOCATION_PERMISSION);
}
}
// This is the callback that will fire after the user is prompted
// It is important to note that if someone checks the "Do not ask again"
// box this callback will always return a deny without prompting.
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode) {
case REQUEST_LOCATION_PERMISSION:
if (grantResults.length > 0) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// access location to your heart's content!
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment