I have problem with access to camera first time. I installed
my app. Next go to scan to QR Code. I use to scan QR Code google vision. App show dialog, which show about the permissions, next click "Allow",but camera doesn't open. But I go back activity and go to activity which scan QR Code, camera open.
my AdnroidManifest.xml
my class
public class ScanQrCodeActivity extends AppCompatActivity {
protected void attachBaseContext(Context context) {
super.attachBaseContext(CalligraphyContextWrapper.wrap(context));
}
private static final String TAG = "Barcode-reader";
// intent request code to handle updating play services if needed.
private static final int RC_HANDLE_GMS = 9001;
// permission request codes need to be < 256
private static final int RC_HANDLE_CAMERA_PERM = 2;
private DatabaseHandler helper;
private TextView title_app;
private CameraSource mCameraSource;
private CameraSourcePreview mPreview;
private GraphicOverlay<BarcodeGraphic> mGraphicOverlay;
String passwordString, eightChars, barcodeString, decodedBarcodeValue, OTP;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan_qr_code);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setNavigationIcon(R.drawable.ic_arrow_back);
title_app = (TextView) findViewById(R.id.toolbar_title);
helper = new DatabaseHandler(this);
mPreview = (CameraSourcePreview) findViewById(R.id.preview);
mGraphicOverlay = (GraphicOverlay<BarcodeGraphic>) findViewById(R.id.graphicOverlay);
eightChars = getIntent().getStringExtra("eightChars");
passwordString = getIntent().getStringExtra("passwordString");
int rc = ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
if (rc == PackageManager.PERMISSION_GRANTED) {
createCameraSource();
} else {
requestCameraPermission();
}
Snackbar snackbar = Snackbar.make(mGraphicOverlay, R.string.zeskanuj_wygenerowany_kod, Snackbar.LENGTH_INDEFINITE);
View mView = snackbar.getView();
TextView mTextView = (TextView) mView.findViewById(android.support.design.R.id.snackbar_text);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1)
mTextView.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
else
mTextView.setGravity(Gravity.CENTER_HORIZONTAL);
snackbar.show();
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.stage2, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish();
}
return super.onOptionsItemSelected(item);
}
private void requestCameraPermission() {
Log.w(TAG, "Camera permission is not granted. Requesting permission");
final String[] permissions = new String[]{Manifest.permission.CAMERA};
if (!ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.CAMERA)) {
ActivityCompat.requestPermissions(this, permissions, RC_HANDLE_CAMERA_PERM);
return;
}
final Activity thisActivity = this;
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View view) {
ActivityCompat.requestPermissions(thisActivity, permissions,
RC_HANDLE_CAMERA_PERM);
}
};
findViewById(R.id.topLayout).setOnClickListener(listener);
Snackbar.make(mGraphicOverlay, "Aby móc wykryć Qr Koda potrzebny jest dostęp do kamery.",
Snackbar.LENGTH_INDEFINITE)
.setAction(R.string.ok, listener)
.show();
}
#SuppressLint("InlinedApi")
private void createCameraSource() {
boolean autoFocus = false;
boolean useFlash = false;
Context context = getApplicationContext();
BarcodeDetector barcodeDetector = new BarcodeDetector.Builder(context).build();
BarcodeTrackerFactory barcodeFactory = new BarcodeTrackerFactory(mGraphicOverlay);
barcodeDetector.setProcessor(
new MultiProcessor.Builder<>(barcodeFactory).build());
barcodeFactory.setNewBarcodeListener(new BarcodeTrackerFactory.OnNewBarcodeListener() {
#Override
public void onNewItem(final Barcode item) {
Log.d("BarcodeFound", "Found new barcode! " + item.rawValue);
title_app.post(new Runnable() {
#Override
public void run() {
if (!barcodeDetector.isOperational())
{
IntentFilter lowstorageFilter = new IntentFilter(Intent.ACTION_DEVICE_STORAGE_LOW);
boolean hasLowStorage = registerReceiver(null, lowstorageFilter) != null;
if (hasLowStorage) {
Toast.makeText(this, R.string.low_storage_error, Toast.LENGTH_LONG).show();
Log.w(TAG, getString(R.string.low_storage_error));
}
}
CameraSource.Builder builder = new CameraSource.Builder(getApplicationContext(), barcodeDetector)
.setFacing(CameraSource.CAMERA_FACING_BACK)
.setRequestedPreviewSize(1600, 1024)
.setRequestedFps(15.0f);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH)
{
builder = builder.setFocusMode(
autoFocus ? Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE : null);
}
mCameraSource = builder
.setFlashMode(useFlash ? Camera.Parameters.FLASH_MODE_TORCH : null)
.
build();
}
#Override
protected void onResume() {
super.onResume();
startCameraSource();
}
#Override
protected void onPause() {
super.onPause();
if (mPreview != null) {
mPreview.stop();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (mPreview != null) {
mPreview.release();
}
}
private void startCameraSource() throws SecurityException {
// check that the device has play services available.
int code = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(
getApplicationContext());
if (code != ConnectionResult.SUCCESS) {
Dialog dlg =
GoogleApiAvailability.getInstance().getErrorDialog(this, code, RC_HANDLE_GMS);
dlg.show();
}
if (mCameraSource != null) {
try {
mPreview.start(mCameraSource, mGraphicOverlay);
} catch (IOException e) {
Log.e(TAG, "Unable to start camera source.", e);
mCameraSource.release();
mCameraSource = null;
}
}
}
}
In your code immplement the following method
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case 0:
boolean isPerpermissionForAllGranted = false;
if (grantResults.length > 0 && permissions.length==grantResults.length) {
for (int i = 0; i < permissions.length; i++){
if (grantResults[i] == PackageManager.PERMISSION_GRANTED){
isPerpermissionForAllGranted=true;
}else{
isPerpermissionForAllGranted=false;
}
}
Log.e("value", "Permission Granted, Now you can use local drive .");
} else {
isPerpermissionForAllGranted=true;
Log.e("value", "Permission Denied, You cannot use local drive .");
}
if(isPerpermissionForAllGranted){
// Fire here again for camera
createCameraSource();
}
break;
}
}
So what happens is When you fire the dialog for permission, you can implement the result method to come to know whether you were granted permission or not. So here you can check if the permission is granted for your permission request, You can again fire your method to open the camera.
Beginning in Android 6.0 (API level 23), users grant permissions to apps while the app is running, not when they install the app. This approach streamlines the app install process, since the user does not need to grant permissions when they install or update the app.
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public boolean checkPermission()
{
int currentAPIVersion = Build.VERSION.SDK_INT;
if(currentAPIVersion>=android.os.Build.VERSION_CODES.M)
{
if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_CALENDAR) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) context, Manifest.permission.WRITE_CALENDAR)) {
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context);
alertBuilder.setCancelable(true);
alertBuilder.setTitle("Permission necessary");
alertBuilder.setMessage("Write calendar permission is necessary to write event!!!");
alertBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions((Activity)context, new String[]{Manifest.permission.WRITE_CALENDAR}, MY_PERMISSIONS_REQUEST_WRITE_CALENDAR);
}
});
AlertDialog alert = alertBuilder.create();
alert.show();
} else {
ActivityCompat.requestPermissions((Activity)context, new String[]{Manifest.permission.WRITE_CALENDAR}, MY_PERMISSIONS_REQUEST_WRITE_CALENDAR);
}
return false;
} else {
return true;
}
} else {
return true;
}
}
References :
https://developer.android.com/training/permissions/requesting.html
https://www.sitepoint.com/requesting-runtime-permissions-in-android-m-and-n/
http://www.theappguruz.com/blog/runtime-permissions-in-android-marshmallow
Related
I have a splash screen on launching my app. So when showing the splash screen run time permission should show. I got this code below from github. But runtime permissions are not showing. Splash screen works fine, but runtime permission is not working when add this code below. I have added permissions read sms, read external storage, access location. I have given all these permissions in the manifest file also.
public class SplashActivity extends AppCompatActivity {
String loginstatus;
final private int REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS = 124;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splashfile);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
Intent i = new Intent(SplashActivity.this, LoginActivity.class);
startActivity(i);
finish();
}
}, 3000);
/* Thread background = new Thread() {
public void run() {
try {
// Thread will sleep for 10 seconds
sleep(4*1000);
startActivity(new Intent(SplashScreen.this,HomeActivity.class));
finish();
} catch (Exception e) {
}
}
};
// start thread
background.start();*/
}
private void permissioncheck() {
List<String> permissionsNeeded = new ArrayList<String>();
final List<String> permissionsList = new ArrayList<String>();
if (!addPermission(permissionsList, Manifest.permission.READ_EXTERNAL_STORAGE))
permissionsNeeded.add("READ");
if (!addPermission(permissionsList, Manifest.permission.ACCESS_COARSE_LOCATION))
permissionsNeeded.add("COURLOC");
if (!addPermission(permissionsList, Manifest.permission.ACCESS_FINE_LOCATION))
permissionsNeeded.add("FINELOC");
if (!addPermission(permissionsList, Manifest.permission.READ_SMS))
permissionsNeeded.add("SMS");
if (permissionsList.size() > 0) {
if (permissionsNeeded.size() > 0) {
// Need Rationale
String message = "You need to grant access to " + permissionsNeeded.get(0);
for (int i = 1; i < permissionsNeeded.size(); i++)
message = message + ", " + permissionsNeeded.get(i);
showMessageOKCancel(message,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (Build.VERSION.SDK_INT >= 23) {
// Marshmallow+
requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
} else {
// Pre-Marshmallow
}
}
});
return;
}
if (Build.VERSION.SDK_INT >= 23) {
// Marshmallow+
requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
} else {
// Pre-Marshmallow
}
return;
}else
{
// Toast.makeText(this,"Permission",Toast.LENGTH_LONG).show();
LaunchApp();
}
//insertDummyContact();
}
private boolean addPermission(List<String> permissionsList, String permission) {
Boolean cond;
if (Build.VERSION.SDK_INT >= 23) {
// Marshmallow+
if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
permissionsList.add(permission);
// Check for Rationale Option
if (!shouldShowRequestPermissionRationale(permission))
// return false;
cond = false;
}
// return true;
cond = true;
} else {
// Pre-Marshmallow
cond = true;
}
return cond;
}
private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
new AlertDialog.Builder(SplashActivity.this)
.setMessage(message)
.setPositiveButton("OK", okListener)
.setNegativeButton("Cancel", null)
.create()
.show();
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
//Checking the request code of our request
if (requestCode == 23) {
//If permission is granted
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//Displaying a toast
Toast.makeText(this, "Permission granted", Toast.LENGTH_LONG).show();
} else {
//Displaying another toast if permission is not granted
Toast.makeText(this, "Permission Needed To Run The App", Toast.LENGTH_LONG).show();
}
}
if (requestCode == REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS) {
Map<String, Integer> perms = new HashMap<String, Integer>();
// Initial
perms.put(Manifest.permission.READ_EXTERNAL_STORAGE, PackageManager.PERMISSION_GRANTED);
perms.put(Manifest.permission.ACCESS_COARSE_LOCATION, PackageManager.PERMISSION_GRANTED);
perms.put(Manifest.permission.ACCESS_FINE_LOCATION, PackageManager.PERMISSION_GRANTED);
perms.put(Manifest.permission.READ_SMS, PackageManager.PERMISSION_GRANTED);
//Toast.makeText(SplashScreen.this, " Permissions are jddddd", Toast.LENGTH_SHORT).show();
// Fill with results
for (int i = 0; i < permissions.length; i++)
perms.put(permissions[i], grantResults[i]);
// Check for ACCESS_FINE_LOCATION
if (perms.get(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
&& perms.get(Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED &&
perms.get(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED &&
perms.get(Manifest.permission.READ_SMS) == PackageManager.PERMISSION_GRANTED) {
// All Permissions Granted
// insertDummyContact();
//Toast.makeText(SplashScreen.this, " Permissions are l", Toast.LENGTH_SHORT).show();
LaunchApp();
} else {
// Permission Denied
Toast.makeText(SplashActivity.this, "Some Permission is Denied", Toast.LENGTH_SHORT)
.show();
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
//Do something after 100
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", getPackageName(), null);
intent.setData(uri);
startActivityForResult(intent, REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
finish();
}
}, 3000);
}
}
}
public void LaunchApp()
{
Thread background = new Thread() {
public void run() {
try {
// Thread will sleep for 10 seconds
sleep(4*1000);
startActivity(new Intent(getApplicationContext(),LoginActivity.class));
finish();
} catch (Exception e) {
}
}
};
// start thread
background.start();
}
}
You need to call permissioncheck() on onCreate() method after setContentView(). Replace the code provided below with your onCreate() method.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splashfile);
permissioncheck();
}
I removed Handler codes on onCreate() method. Instead, use onRequestPermissionResult() and start LoginActivity from it. Replace the following code to your onRequestPermissionResult().
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
//Checking the request code of our request
if (requestCode == 23) {
//If permission is granted
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//Displaying a toast
Toast.makeText(this, "Permission granted", Toast.LENGTH_LONG).show();
} else {
//Displaying another toast if permission is not granted
Toast.makeText(this, "Permission Needed To Run The App", Toast.LENGTH_LONG).show();
}
}
if (requestCode == REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS) {
Map<String, Integer> perms = new HashMap<String, Integer>();
// Initial
perms.put(Manifest.permission.READ_EXTERNAL_STORAGE, PackageManager.PERMISSION_GRANTED);
perms.put(Manifest.permission.ACCESS_COARSE_LOCATION, PackageManager.PERMISSION_GRANTED);
perms.put(Manifest.permission.ACCESS_FINE_LOCATION, PackageManager.PERMISSION_GRANTED);
perms.put(Manifest.permission.READ_SMS, PackageManager.PERMISSION_GRANTED);
//Toast.makeText(SplashScreen.this, " Permissions are jddddd", Toast.LENGTH_SHORT).show();
// Fill with results
for (int i = 0; i < permissions.length; i++)
perms.put(permissions[i], grantResults[i]);
// Check for ACCESS_FINE_LOCATION
if (perms.get(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
&& perms.get(Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED &&
perms.get(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED &&
perms.get(Manifest.permission.READ_SMS) == PackageManager.PERMISSION_GRANTED) {
// All Permissions Granted
// Here start the activity
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
Intent i = new Intent(SplashActivity.this, LoginActivity.class);
startActivity(i);
finish();
}
}, 3000);
} else {
// Permission Denied
Toast.makeText(SplashActivity.this, "Some Permission is Denied", Toast.LENGTH_SHORT)
.show();
finish();
}
}
}
Please carefully read comments in the code provided above.
Best Code
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
public class Firstclass extends AppCompatActivity {
private int timeoutMillis = 5000;
/** The time when this {#link AppCompatActivity} was created. */
private long startTimeMillis = 0;
/** The code used when requesting permissions */
private static final int PERMISSIONS_REQUEST = 1234;
public int getTimeoutMillis() {
return timeoutMillis;
}
#SuppressWarnings("rawtypes")
public Class getNextActivityClass() {
return SecondActivity.class;
};
public String[] getRequiredPermissions() {
String[] permissions = null;
try {
permissions = getPackageManager().getPackageInfo(getPackageName(),
PackageManager.GET_PERMISSIONS).requestedPermissions;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
if (permissions == null) {
return new String[0];
} else {
return permissions.clone();
}
}
#TargetApi(23)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startTimeMillis = System.currentTimeMillis();
if (Build.VERSION.SDK_INT >= 23) {
checkPermissions();
} else {
startNextActivity();
}
}
#TargetApi(23)
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
if (requestCode == PERMISSIONS_REQUEST) {
checkPermissions();
}
}
private void startNextActivity() {
runOnUiThread(new Runnable() {
#Override
public void run() {
}
});
long delayMillis = getTimeoutMillis() - (System.currentTimeMillis() - startTimeMillis);
if (delayMillis < 0) {
delayMillis = 0;
}
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
startActivity(new Intent(Firstclass.this, getNextActivityClass()));
finish();
}
}, delayMillis);
}
private void checkPermissions() {
String[] ungrantedPermissions = requiredPermissionsStillNeeded();
if (ungrantedPermissions.length == 0) {
startNextActivity();
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(ungrantedPermissions, PERMISSIONS_REQUEST);
}
}
}
#TargetApi(23)
private String[] requiredPermissionsStillNeeded() {
Set<String> permissions = new HashSet<String>();
for (String permission : getRequiredPermissions()) {
permissions.add(permission);
}
for (Iterator<String> i = permissions.iterator(); i.hasNext();) {
String permission = i.next();
if (checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED) {
Log.d(Firstclass.class.getSimpleName(),
"Permission: " + permission + " already granted.");
i.remove();
} else {
Log.d(Firstclass.class.getSimpleName(),
"Permission: " + permission + " not yet granted.");
}
}
return permissions.toArray(new String[permissions.size()]);
}
}
Manifest xml permission
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.SEND_SMS" />
if (Build.VERSION.SDK_INT >= 23) {
if (checkPermission()) {
Log.e("permission", "Permission already granted.");
} else {
requestPermission();
}
}
private boolean checkPermission() {
int result = ContextCompat.checkSelfPermission(SolutionBrouchereActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (result == PackageManager.PERMISSION_GRANTED) {
viewOrDownloadPDF();
return true;
} else {
return false;
}
}
private void requestPermission() {
ActivityCompat.requestPermissions(getParent(), new String[]{Manifest.permission.CAMERA}, PERMISSION_REQUEST_CODE);
}
This functions not worked after denying permission on the splash screen and not able to open permission prompt dialog in another activity.
You can call the shouldShowRequestPermissionRationale method in your new Activity if user did not grant the permission on Splash Screen.
Reference: https://developer.android.com/training/permissions/requesting
If your target SDK version is >=23 then you need to ask for permissions at run time. Otherwise Android will not ask for permission like old Android does.
If this is the case then you should be able to see that no permissions have been granted if you go to Settings > Apps > "Your app" > Permissions.
If you don't want to ask permissions you can reduce your target sdk version to 22 to get the old permission system. You can still compile with sdk version 23 though.
So for >=23 Use this code:
This code will automatically detect which dialog should be shown, because there is a particular limit in android to show that permission dialog. If particular number of attempts made then it will not show permission dialog, and we will have to move user to settings it self.
This code will help you to achieve both scenarios :
CustomPermissionManager.java :
public class CustomPermissionManager {
public static final int STORAGE_PERMISSION = 8;
public HashMap<Integer, ArrayList<PermissionManagerUtil.OnPermissionInterface>> onPermissionInterfaces = new HashMap<>();
public HashMap<Integer, Boolean> hasAlreadyAskedPermission = new HashMap<>();
private MainActivity context;
public void init(MainActivity context) {
this.context = context;
}
private boolean isAskedForFirstTime(String permissionName) {
if (!PreferenceManager.getDefaultSharedPreferences(context).getBoolean(permissionName, false)) {
PreferenceManager.getDefaultSharedPreferences(context).edit().putBoolean(permissionName, true).commit();
return true;
}
return false;
}
public void requestStoragePermission(Activity activity, boolean showAlertForSettingsIfNeeded, PermissionManagerUtil.OnPermissionInterface onPermissionInterface) {
if (PermissionManagerUtil.instance.checkStoragePermission()) {
onPermissionInterface.onPermissionGranted();
return;
}
boolean isAskedFirstTime = isAskedForFirstTime(Manifest.permission.READ_EXTERNAL_STORAGE);
if (showAlertForSettingsIfNeeded && !isAskedFirstTime && !ActivityCompat.shouldShowRequestPermissionRationale(activity, Manifest.permission.READ_EXTERNAL_STORAGE)) {
// if user clicked on "never ask again" then popup will not show by android
//https://stackoverflow.com/questions/33224432/android-m-anyway-to-know-if-a-user-has-chosen-never-to-show-the-grant-permissi
showAlertDialogWithAppSettings(activity, Manifest.permission.READ_EXTERNAL_STORAGE);
} else {
if (onPermissionInterfaces.get(STORAGE_PERMISSION) == null) {
onPermissionInterfaces.put(STORAGE_PERMISSION, new ArrayList<>());
}
if (onPermissionInterface != null) {
onPermissionInterfaces.get(STORAGE_PERMISSION).add(onPermissionInterface);
}
if (!hasAlreadyAskedPermission.containsKey(STORAGE_PERMISSION)) {
hasAlreadyAskedPermission.put(STORAGE_PERMISSION, true);
ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION);
}
}
}
private void callPermissionManagerCallBack(int requestCode, int[] grantResults) {
if (onPermissionInterfaces.containsKey(requestCode) && onPermissionInterfaces.get(requestCode) != null) {
for (PermissionManagerUtil.OnPermissionInterface onPermissionInterface : onPermissionInterfaces.get(requestCode)) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
onPermissionInterface.onPermissionGranted();
} else {
onPermissionInterface.onPermissionNotGranted();
}
}
hasAlreadyAskedPermission.remove(requestCode);
onPermissionInterfaces.get(requestCode).clear();
}
}
private void showAlertDialogWithAppSettings(String permission) {
showAlertDialogWithAppSettings(context, permission);
}
#SuppressLint("RestrictedApi")
private void showAlertDialogWithAppSettings(Activity context, String permission) {
String title = "Allow permissions";
String message = "Please allow this permission to enable this feature.";
switch (permission) {
case Manifest.permission.WRITE_EXTERNAL_STORAGE:
title = "Allow Storage Permission";
message = "Please allow permission to do.... task";
break;
}
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(title);
builder.setMessage(message);
builder.setPositiveButton("Go to settings", (dialog, which) -> {
Intent intent = new Intent();
intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Uri uri = Uri.fromParts("package", context.getPackageName(), null);
intent.setData(uri);
context.startActivity(intent);
});
builder.setNegativeButton("Cancel", (dialog, which) -> dialog.dismiss());
builder.show();
}
public boolean checkStoragePermission() {
int resultExternalStorage = PermissionChecker.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE);
return resultExternalStorage == PackageManager.PERMISSION_GRANTED;
}
}
Call it like this :
CustomPermissionManager customPermissionManager = new CustomPermissionManager();
customPermissionManager.init(context);
customPermissionManager.requestCameraPermission(true, new OnPermissionInterface() {
#Override
public void onPermissionGranted() {
//permission granted
viewOrDownloadPDF();
}
#Override
public void onPermissionNotGranted() {
// permission not granted
}
});
// To check permission is given or not
boolean isGranted = customPermissionManager.checkStoragePermission();
You can add other permission too in future like here STORAGE_PERMISSION is added, by adding same type of method.
Put this function in common file and call whenever you use it will again check
public static boolean checkPermission(final Activity context)
{
int currentAPIVersion = Build.VERSION.SDK_INT;
if(currentAPIVersion>=android.os.Build.VERSION_CODES.M)
{
if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED||ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { //||ContextCompat.checkSelfPermission(context, Manifest.permission.CALL_PHONE)!=PackageManager.PERMISSION_GRANTED
if (ActivityCompat.shouldShowRequestPermissionRationale(context, Manifest.permission.READ_EXTERNAL_STORAGE)||ActivityCompat.shouldShowRequestPermissionRationale(context, Manifest.permission.WRITE_EXTERNAL_STORAGE)||ActivityCompat.shouldShowRequestPermissionRationale(context, Manifest.permission.CALL_PHONE)) {
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context);
alertBuilder.setCancelable(true);
alertBuilder.setTitle("Permission necessary");
alertBuilder.setMessage("External storage permission is necessary");
alertBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions(context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.CALL_PHONE}, MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
}
});
AlertDialog alert = alertBuilder.create();
alert.show();
} else {
ActivityCompat.requestPermissions(context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.CALL_PHONE}, MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
}
return false;
} else {
return true;
}
} else {
return true;
}
}
In my android application,location service is implemented as background service.I have tested it with different phones(like samsung,micromax,Moto,lenovo,nexus) it works fine with all.But when i run in Oppo (colorOS) and MI (MIUI OS),my service is get stopped after some time interval.I have finished MainActivity with MainActivity.this.finish().
put following code on your activity above oncreate() method:
private FusedLocationProviderClient mFusedLocationClient;
EasyPermissionsLocation.PermissionCallbacks permissionCallbacks = new EasyPermissionsLocation.PermissionCallbacks() {
#Override
public void onPermissionsGranted(int requestCode, List perms) {
LocationRequest mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(10000);
mLocationRequest.setFastestInterval(5000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(mLocationRequest);
SettingsClient client = LocationServices.getSettingsClient(SurveyActivity.this);
Task<LocationSettingsResponse> task = client.checkLocationSettings(builder.build());
task.addOnSuccessListener(SurveyActivity.this, new OnSuccessListener<LocationSettingsResponse>() {
#Override
public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(SurveyActivity.this);
if (ActivityCompat.checkSelfPermission(SurveyActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(SurveyActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mFusedLocationClient.getLastLocation()
.addOnSuccessListener(SurveyActivity.this, new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if (location != null) {
((SurveyApp)getApplication()).getUser().getCurrentSurvey().setLat(""+location.getLatitude());
((SurveyApp)getApplication()).getUser().getCurrentSurvey().setLng(""+location.getLongitude());
Toast.makeText(SurveyActivity.this, "Location Captured", Toast.LENGTH_SHORT).show();
}
}
});
}
});
task.addOnFailureListener(SurveyActivity.this, new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
if (e instanceof ResolvableApiException) {
try {
ResolvableApiException resolvable = (ResolvableApiException) e;
resolvable.startResolutionForResult(SurveyActivity.this,
REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException sendEx) {
}
}
}
});
}
#Override
public void onPermissionsDenied(int requestCode, List perms, final boolean isAutoDenied) {
if (isAutoDenied) {
showDialog(getString(R.string.permanently_deny_location));
}
}
#Override
public void onPermissionsPermanentlyDeclined(int requestCode, List perms) {
showDialog(getString(R.string.permanently_deny_location));
}
};
call above code from oncreate method():-
EasyPermissionsLocation.requestPermissions(this, permissionCallbacks, getString(R.string.location_message), 100, Manifest.permission_group.LOCATION);
create this class:
public class EasyPermissionsLocation {
private static final String TAG = "EasyPermissions";
private static long timeWhenRequestingStart;
private static Object object;
private static AlertDialog dialog;
private static PermissionCallbacks callbacks;
private static HashMap<String, String[]> permissionGroups;
private static boolean shouldShowRationale = false;
public static boolean hasPermissions(Context context, String... perms) {
// Always return true for SDK < M, let the system deal with the permissions
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
Log.w(TAG, "hasPermissions: API version < M, returning true by default");
return true;
}
for (String perm : perms) {
boolean hasPerm = (ContextCompat.checkSelfPermission(context, perm) ==
PackageManager.PERMISSION_GRANTED);
if (!hasPerm) {
return false;
}
}
return true;
}
public static void requestPermissions(final Object object, PermissionCallbacks callback, String rationale,
final int requestCode, final String... perms) {
requestPermissions(object, callback, rationale,
android.R.string.ok,
android.R.string.cancel,
requestCode, perms);
}
public static void requestPermissions(final Object obj, final PermissionCallbacks callback, String rationale,
#StringRes int positiveButton,
#StringRes int negativeButton,
final int requestCode, final String... permission) {
callbacks = callback;
object = obj;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
// only for lower of M
callbacks.onPermissionsGranted(requestCode, new ArrayList<String>(Arrays.asList(permission)));
return;
}
checkCallingObjectSuitability(object);
final String[] perms = getActualPermissions(object,
permission);
if (perms.length <= 0) {
callbacks.onPermissionsGranted(requestCode, new ArrayList<String>(Arrays.asList(permission)));
return;
}
shouldShowRationale = false;
for (String perm : perms) {
shouldShowRationale = shouldShowRationale || shouldShowRequestPermissionRationale(object, perm);
}
if (shouldShowRationale) {
if (!TextUtils.isEmpty(rationale)) {
if (dialog == null) {
dialog = new AlertDialog.Builder(getActivity(object))
.setMessage(rationale)
.setCancelable(false)
.setPositiveButton(positiveButton, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog1, int which) {
executePermissionsRequest(object, perms, requestCode);
dialog.dismiss();
}
})
.create();
} else {
dialog.setMessage(rationale);
}
dialog.show();
} else {
executePermissionsRequest(object, perms, requestCode);
}
} else {
timeWhenRequestingStart = System.currentTimeMillis();
executePermissionsRequest(object, perms, requestCode);
}
}
private static String[] getActualPermissions(Object object, String[] permission) {
initPermissionGroups();
ArrayList<String> permissionList = new ArrayList<String>();
for (String indiPerm : permission) {
if (permissionGroups.containsKey(indiPerm)) {
String[] arr = permissionGroups.get(indiPerm);
for (String s : arr) {
if (!EasyPermissionsLocation.hasPermissions(getActivity(object), s)) {
permissionList.add(s);
}
}
} else {
if (!EasyPermissionsLocation.hasPermissions(getActivity(object), indiPerm)) {
permissionList.add(indiPerm);
}
}
}
Set<String> set = new LinkedHashSet<String>(permissionList);
return set.toArray(new String[set.size()]);
}
private static void initPermissionGroups() {
if (permissionGroups == null) {
permissionGroups = new HashMap<String, String[]>();
permissionGroups.put(Manifest.permission_group.CALENDAR, new String[]{Manifest.permission.READ_CALENDAR, Manifest.permission.WRITE_CALENDAR});
permissionGroups.put(Manifest.permission_group.CAMERA, new String[]{Manifest.permission.CAMERA});
permissionGroups.put(Manifest.permission_group.CONTACTS, new String[]{Manifest.permission.READ_CONTACTS, Manifest.permission.WRITE_CONTACTS, Manifest.permission.GET_ACCOUNTS});
permissionGroups.put(Manifest.permission_group.LOCATION, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION});
permissionGroups.put(Manifest.permission_group.MICROPHONE, new String[]{Manifest.permission.RECORD_AUDIO});
permissionGroups.put(Manifest.permission_group.PHONE, new String[]{Manifest.permission.READ_PHONE_STATE, Manifest.permission.CALL_PHONE, Manifest.permission.READ_CALL_LOG, Manifest.permission.WRITE_CALL_LOG, Manifest.permission.ADD_VOICEMAIL, Manifest.permission.USE_SIP, Manifest.permission.PROCESS_OUTGOING_CALLS});
permissionGroups.put(Manifest.permission_group.SENSORS, new String[]{Manifest.permission.BODY_SENSORS});
permissionGroups.put(Manifest.permission_group.SMS, new String[]{Manifest.permission.SEND_SMS, Manifest.permission.RECEIVE_SMS, Manifest.permission.READ_SMS, Manifest.permission.RECEIVE_WAP_PUSH, Manifest.permission.RECEIVE_MMS});
permissionGroups.put(Manifest.permission_group.STORAGE, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE});
}
}
public static void onRequestPermissionsResult(int requestCode, String[] permissions,
int[] grantResults) {
// checkCallingObjectSuitability(object);
// PermissionCallbacks callbacks = (PermissionCallbacks) object;
// Make a collection of granted and denied permissions from the request.
boolean showRationale = false;
ArrayList<String> granted = new ArrayList<>();
ArrayList<String> denied = new ArrayList<>();
for (int i = 0; i < permissions.length; i++) {
String perm = permissions[i];
if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
granted.add(perm);
} else {
showRationale = shouldShowRequestPermissionRationale(object, perm);
if (!showRationale) {
timeWhenRequestingStart = System.currentTimeMillis() - 2;
}
denied.add(perm);
}
}
boolean isPermenantlyDisabled = false;
// Report granted permissions, if any.
if (!granted.isEmpty() && denied.isEmpty()) {
// Notify callbacks
callbacks.onPermissionsGranted(requestCode, granted);
}
//if 100% fail then check for whether timing
else if (granted.isEmpty() && !denied.isEmpty()) {
if (!shouldShowRationale && !showRationale) {
if (callbacks != null) {
callbacks.onPermissionsDenied(requestCode, denied, true);
}
} else {
long diff = System.currentTimeMillis() - timeWhenRequestingStart;
if (diff < 150) {
//means it is permenantly disabled
isPermenantlyDisabled = true;
if (callbacks != null) {
callbacks.onPermissionsPermanentlyDeclined(requestCode, denied);
}
}
Log.i("TAG", diff + "");
}
}
else if (!denied.isEmpty() && !isPermenantlyDisabled) {
callbacks.onPermissionsDenied(requestCode, denied, false);
}
}
#TargetApi(23)
private static boolean shouldShowRequestPermissionRationale(Object object, String perm) {
if (object instanceof Activity) {
return ActivityCompat.shouldShowRequestPermissionRationale((Activity) object, perm);
} else if (object instanceof Fragment) {
return ((Fragment) object).shouldShowRequestPermissionRationale(perm);
} else if (object instanceof android.app.Fragment) {
return ((android.app.Fragment) object).shouldShowRequestPermissionRationale(perm);
} else {
return false;
}
}
#TargetApi(23)
private static void executePermissionsRequest(Object object, String[] perms, int requestCode) {
checkCallingObjectSuitability(object);
if (object instanceof Activity) {
ActivityCompat.requestPermissions((Activity) object, perms, requestCode);
} else if (object instanceof Fragment) {
((Fragment) object).requestPermissions(perms, requestCode);
} else if (object instanceof android.app.Fragment) {
((android.app.Fragment) object).requestPermissions(perms, requestCode);
}
}
#TargetApi(11)
private static Activity getActivity(Object object) {
if (object instanceof Activity) {
return ((Activity) object);
} else if (object instanceof Fragment) {
return ((Fragment) object).getActivity();
} else if (object instanceof android.app.Fragment) {
return ((android.app.Fragment) object).getActivity();
} else {
return null;
}
}
private static void checkCallingObjectSuitability(Object object) {
// Make sure Object is an Activity or Fragment
boolean isActivity = object instanceof Activity;
boolean isSupportFragment = object instanceof Fragment;
boolean isAppFragment = object instanceof android.app.Fragment;
boolean isMinSdkM = Build.VERSION.SDK_INT >= Build.VERSION_CODES.M;
if (!(isSupportFragment || isActivity || (isAppFragment && isMinSdkM))) {
if (isAppFragment) {
throw new IllegalArgumentException(
"Target SDK needs to be greater than 23 if caller is android.app.Fragment");
} else {
throw new IllegalArgumentException("Caller must be an Activity or a Fragment.");
}
}
}
public interface PermissionCallbacks {
void onPermissionsGranted(int requestCode, List<String> perms);
void onPermissionsDenied(int requestCode, List<String> perms, boolean isAutoDenied);
void onPermissionsPermanentlyDeclined(int requestCode, List<String> perms);
}
}
add in manifest:-
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
add following in app gradle file:
implementation 'com.google.android.gms:play-services-location:11.8.0'
I have a Zxing barcode scanner on my app. The result handler when the user scanned the barcode was originally to show the barcode number ina popup on the screen. I want to change this and instead bring the user to a new page where they can see the barcode number and add extra details too like product name, date, category etc. Then when the user clicks save it should add to the firebase database and the barcode number should become the ID.
Then the next time the user scans the same barcode the app will recognise it and show the details you already added.
Here is my code:
public class BarcodeDetect extends AppCompatActivity implements ZXingScannerView.ResultHandler {
private static final int REQUEST_CAMERA = 1;
private ZXingScannerView scannerView;
private static int camId = Camera.CameraInfo.CAMERA_FACING_BACK;
//our database reference object
DatabaseReference databaseFoods;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
scannerView = new ZXingScannerView(this);
setContentView(scannerView);
//getting the reference of artists node
databaseFoods = FirebaseDatabase.getInstance().getReference("foods");
int currentApiVersion = Build.VERSION.SDK_INT;
if(currentApiVersion >= Build.VERSION_CODES.M)
{
if(checkPermission())
{
Toast.makeText(BarcodeDetect.this, "Permission already granted!", Toast.LENGTH_LONG).show();
}
else
{
requestPermission();
}
}
}
private boolean checkPermission()
{
return (ContextCompat.checkSelfPermission(BarcodeDetect.this, CAMERA) == PackageManager.PERMISSION_GRANTED);
}
private void requestPermission()
{
ActivityCompat.requestPermissions(this, new String[]{CAMERA}, REQUEST_CAMERA);
}
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case REQUEST_CAMERA:
if (grantResults.length > 0) {
boolean cameraAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
if (cameraAccepted){
Toast.makeText(BarcodeDetect.this, "Permission Granted, Now you can access camera", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(BarcodeDetect.this, "Permission Denied, You cannot access and camera", Toast.LENGTH_LONG).show();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (shouldShowRequestPermissionRationale(CAMERA)) {
showMessageOKCancel("You need to allow access to both the permissions",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{CAMERA},
REQUEST_CAMERA);
}
}
});
return;
}
}
}
}
break;
}
}
private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
new android.support.v7.app.AlertDialog.Builder(BarcodeDetect.this)
.setMessage(message)
.setPositiveButton("OK", okListener)
.setNegativeButton("Cancel", null)
.create()
.show();
}
#Override
public void onResume() {
super.onResume();
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
if (currentapiVersion >= android.os.Build.VERSION_CODES.M) {
if (checkPermission()) {
if(scannerView == null) {
scannerView = new ZXingScannerView(this);
setContentView(scannerView);
}
scannerView.setResultHandler(this);
scannerView.startCamera();
} else {
requestPermission();
}
}
}
#Override
public void onDestroy() {
super.onDestroy();
scannerView.stopCamera();
}
#Override
public void handleResult(Result result) {
final String myResult = result.getText();
Log.d("QRCodeScanner", result.getText());
Log.d("QRCodeScanner", result.getBarcodeFormat().toString());
Intent intent = new Intent(BarcodeDetect.this, viewBarcode.class);
//starting the activity with intent
startActivity(intent);
// AlertDialog.Builder builder = new AlertDialog.Builder(this);
// builder.setTitle("Scan Result");
// builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
// #Override
// public void onClick(DialogInterface dialog, int which) {
// scannerView.resumeCameraPreview(BarcodeDetect.this);
// }
// });
// builder.setNeutralButton("Visit", new DialogInterface.OnClickListener() {
// #Override
// public void onClick(DialogInterface dialog, int which) {
// Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(myResult));
// startActivity(browserIntent);
// }
// });
// builder.setMessage(result.getText());
// AlertDialog alert1 = builder.create();
// alert1.show();
}
}
I have commented out the original code in the event handler and added my own code to bring you to a new page.
This can be thought as a 2 step process:
Pass the data to the next activity
Validate if the data exist in the
database
Once you get the codebar pass it to the next Activity using putExta method
#Override
public void handleResult(Result result) {
Intent intent = new Intent(this, OtherActivity.class);
intent.putExtra("SOME_KEY", result.getText());
startActivity(intent);
}
Then in the second activity get the extra and validate if it is available in the RTD
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_other);
String codebar = getIntent().getStringExtra("SOME_KEY");
//Once you get the codebar use it as key to query on the Firebase RTD
DatabaseReference root = FirebaseDatabase.getInstance().getReference();
root.child("products").child(codebar).addValueEventListener(...
//Auto generated methods
if (dataSnapshot.exists()) {
//Show the user the data
} else {
//Ask the user to fill a form and upload the data to the same node you are asking for
}
)
}
on my app I have implemented a control permission for Android 6 and 7.
When app run show splash screen with message and after permission start the main activity. On Android 6 and 7 works fine but on Android 19 / 20 when i run app appear the message but the app remain blocked on splash screen and don't start main activity.
this is my code:
public class splashscreen extends Activity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener{
private GoogleApiClient googleApiClient;
private Location myLocation;
private static final int MY_PERMISSIONS_REQUEST_GET_ACCOUNTS = 1;
private SparseIntArray mErrorString;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
mErrorString = new SparseIntArray();
GoogleApiAvailability api = GoogleApiAvailability.getInstance();
int code = api.isGooglePlayServicesAvailable(this);
if (code != ConnectionResult.SUCCESS)
{
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Attenzione");
alert.setMessage("Google Play Services non installati o non aggiornati!");
alert.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
finish();
}
});
alert.show();
}
// Create an instance of GoogleAPIClient.
if (googleApiClient == null) {
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
}
protected void onStart() {
googleApiClient.connect();
super.onStart();
}
protected void onStop() {
googleApiClient.disconnect();
super.onStop();
}
// Permessi
public void onPermissionsGranted(int requestCode) {
Toast.makeText(getApplicationContext(), "Permission granted", Toast.LENGTH_SHORT).show();
}
public void requestAppPermissions(final String[]requestedPermissions, final int stringId, final int requestCode) {
mErrorString.put(requestCode, stringId);
int permissionCheck = PackageManager.PERMISSION_GRANTED;
boolean showRequestPermissions = false;
for(String permission: requestedPermissions) {
permissionCheck = permissionCheck + ContextCompat.checkSelfPermission(this, permission);
showRequestPermissions = showRequestPermissions || ActivityCompat.shouldShowRequestPermissionRationale(this, permission);
}
if (permissionCheck!=PackageManager.PERMISSION_GRANTED) {
if(showRequestPermissions) {
Snackbar.make(findViewById(android.R.id.content), stringId, Snackbar.LENGTH_INDEFINITE).setAction("GRANT", new View.OnClickListener() {
#Override
public void onClick(View v) {
ActivityCompat.requestPermissions(splashscreen.this, requestedPermissions, requestCode);
}
}).show();
} else {
ActivityCompat.requestPermissions(this, requestedPermissions, requestCode);
}
} else {
onPermissionsGranted(requestCode);
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case 1: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//Toast.makeText(getApplicationContext(), "Permission granted", Toast.LENGTH_SHORT).show();
Intent i = new Intent(splashscreen.this, MainActivity.class); //start activity
splashscreen.this.startActivity(i);
} else {
Intent i = new Intent();
i.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
i.setData(Uri.parse("package:" + getPackageName()));
i.addCategory(Intent.CATEGORY_DEFAULT);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
i.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
startActivity(i);
/*Toast.makeText(getApplicationContext(), "Permission denied", Toast.LENGTH_SHORT).show();
Snackbar.make(findViewById(android.R.id.content), mErrorString.get(requestCode),
Snackbar.LENGTH_INDEFINITE).setAction("ENABLE", new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent();
i.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
i.setData(Uri.parse("package:" + getPackageName()));
i.addCategory(Intent.CATEGORY_DEFAULT);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
i.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
startActivity(i);
}
}).show();*/
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
#Override
public void onConnected(Bundle connectionHint) {
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
myLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
}
SharedPreferences getPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
boolean isFirstStart = getPrefs.getBoolean("firstStart", true);
if (isFirstStart) {
android.app.AlertDialog alertDialog = new android.app.AlertDialog.Builder(splashscreen.this).create();
alertDialog.setTitle(getResources().getString(R.string.titolo_intro_sms));
alertDialog.setMessage(getResources().getString(R.string.intro_sms));
alertDialog.setButton(android.app.AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions(splashscreen.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
//Intent i = new Intent(splashscreen.this, MainActivity.class);
//startActivity(i);
}
});
alertDialog.show();
SharedPreferences.Editor e = getPrefs.edit();
e.putBoolean("firstStart", false);
e.apply();
} else {
startApp();
}
}
private void startApp() {
if(googleApiClient != null) {
googleApiClient.disconnect();
}
startActivity(new Intent(splashscreen.this, MainActivity.class));
finish();
}
#Override
public void onConnectionSuspended(int i) {
googleApiClient.connect();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
}
That happens because you are not starting the Activity if permissions are granted without requesting them. Before api 23 this check fails:
if (permissionCheck!=PackageManager.PERMISSION_GRANTED) {
// Not called before api 23 unless the permissions are not specified in the manifest.
}
So you have to modify your method onPermissionsGranted() as follow:
public void onPermissionsGranted(int requestCode) {
Toast.makeText(getApplicationContext(), "Permission granted", Toast.LENGTH_SHORT).show();
// Start the Activity if permissions are granted.
startActivity(new Intent(this, MainActivity.class));
}