Last active
August 6, 2018 10:09
-
-
Save Sren-Hmkn/53468e16c0de6b9149583be1dc92f8fb to your computer and use it in GitHub Desktop.
Permissions in MainActivity
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
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