private boolean hasPermissions() {
int res = 0;
// list all permissions which you want to check are granted or not.
String[] permissions = new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
for (String perms : permissions) {
res = checkCallingOrSelfPermission(perms);
if (!(res == PackageManager.PERMISSION_GRANTED)) {
// it return false because your app dosen't have permissions.
return false;
}
}
// it return true, your app has permissions.
return true;
}
private void requestNecessaryPermissions() {
// make array of permissions which you want to ask from user.
String[] permissions = new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// have arry for permissions to requestPermissions method.
// and also send unique Request code.
requestPermissions(permissions, REQUEST_CODE_STORAGE_PERMS);
}
}
/* when user grant or deny permission then your app will check in
onRequestPermissionsReqult about user's response. */
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grandResults) {
// this boolean will tell us that user granted permission or not.
boolean allowed = true;
switch (requestCode) {
case REQUEST_CODE_STORAGE_PERMS:
for (int res : grandResults) {
// if user granted all required permissions then 'allowed' will return true.
allowed = allowed && (res == PackageManager.PERMISSION_GRANTED);
Toast.makeText(this, "Camera permission granted", Toast.LENGTH_SHORT).show();
}
break;
default:
// if user denied then 'allowed' return false
Toast.makeText(this, "Camera permission denied", Toast.LENGTH_SHORT).show();
allowed = false;
break;
}
if (allowed) {
// if user granted permissions then do your work.
//startCamera();
doRestart(this);
} else {
// else give any custom waring message.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (shouldShowRequestPermissionRationale(Manifest.permission.CAMERA)) {
Toast.makeText(MainActivity.this, "Camera Permissions denied", Toast.LENGTH_SHORT).show();
} else if (shouldShowRequestPermissionRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
Toast.makeText(MainActivity.this, "Storage Permissions denied", Toast.LENGTH_SHORT).show();
}
}
}
}