Skip to content

Instantly share code, notes, and snippets.

@Sren-Hmkn
Last active August 6, 2018 10:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Sren-Hmkn/53468e16c0de6b9149583be1dc92f8fb to your computer and use it in GitHub Desktop.
Save Sren-Hmkn/53468e16c0de6b9149583be1dc92f8fb to your computer and use it in GitHub Desktop.
Permissions in MainActivity
static final Integer CAMERA = 0x5;
// ...
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// ...
// public void onClick(View v) {
if(ask()) {
// Intent intent = new Intent(MainActivity.this, CameraActivity.class);
// startActivity(intent);
}
// ...
// }
private boolean askForPermission(String permission, Integer requestCode) {
if (ContextCompat.checkSelfPermission(MainActivity.this, permission) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, permission)) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{permission}, requestCode);
} else {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{permission}, requestCode);
}
return false;
} else {
Toast.makeText(this, "" + permission + " is already granted.", Toast.LENGTH_SHORT).show();
return true;
}
}
public boolean ask() {
boolean answer = false;
if (askForPermission(Manifest.permission.CAMERA, CAMERA)) {
answer= true;
} else {
answer=false;
}
return answer;
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (ActivityCompat.checkSelfPermission(MainActivity.this, permissions[0]) == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Permission granted", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment