Android Studio barcode scanner how to add to firebase - android

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
}
)
}

Related

Get Location Permission from User in Android App

I am implementing Access Location from user.Following is my Code. My problem is When I am clicking on Location permission it not getting the location.Bt when i am manually turn on the location from setting after that it giving me the location.My requirement is i Want compulsory check the Location permission from my App i.e. (it goes to setting and turn on location) .I gave all Permission in AndroidMeanifest file.And following is my SpashScreen.
package com.example.sbaapp;
public class SpashScreen extends AppCompatActivity {
AlertDialog.Builder alertDialog;
String[] perms = {"android.permission.ACCESS_FINE_LOCATION", "android.permission.READ_SMS"};
int permsRequestCode = 200;
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_spash_screen);
alertDialog = new AlertDialog.Builder(SpashScreen.this, R.style.Theme_AppCompat_DayNight_DarkActionBar);
FirebaseApp.initializeApp(getApplicationContext());
//requestPermissions(perms, permsRequestCode);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if(!CheckPermissions()){
requestPermissions(perms,permsRequestCode);
}
}
}
#RequiresApi(api = Build.VERSION_CODES.M)
private boolean CheckPermissions() {
int LocationPermission=checkSelfPermission(perms[0]);
int ReadSmsPermission=checkSelfPermission(perms[1]);
Log.d("Inside Permission","");
return LocationPermission== PackageManager.PERMISSION_GRANTED && ReadSmsPermission==PackageManager.PERMISSION_GRANTED;
}
#Override
protected void onStart() {
super.onStart();
SubscribeToTopic();
if (new SessionManager(getApplicationContext()).ISLOGIN()) {
Intent intent = new Intent(SpashScreen.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
} else {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
Intent intent = new Intent(SpashScreen.this, Activity_home.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}, 60000);
}
}
private void SubscribeToTopic() {
FirebaseMessaging.getInstance().subscribeToTopic("SBASURVEY")
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
String msg = "SuccessGeneralNot";
if (!task.isSuccessful()) {
msg = "Failed";
}
Log.d("TopicstatusForGeneral", msg);
}
});
}
#Override
public void onRequestPermissionsResult(int permsRequestCode, String[] permissions, int[] grantResults){
switch(permsRequestCode){
case 200:
boolean locationAccepted = false;
boolean smspermissionaccepted=false;
if(grantResults.length>=2) {
locationAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
smspermissionaccepted = grantResults[1] == PackageManager.PERMISSION_GRANTED;
}else if(grantResults.length>=1){
if(permissions[0].equals("android.permission.ACCESS_FINE_LOCATION")){
locationAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
smspermissionaccepted=true;
}else {
locationAccepted=true;
smspermissionaccepted = grantResults[1] == PackageManager.PERMISSION_GRANTED;
}
}
if(!(locationAccepted || smspermissionaccepted)){
new AlertDialog.Builder(SpashScreen.this).setMessage("You Need Accept Both the permissions In Order to Smooth Working Of Application Functionality")
.setPositiveButton("Ok",new SpashScreen.OkListenerForBoth())
.setNegativeButton("Cancel",null)
.create()
.show();
}else if(!locationAccepted){
new AlertDialog.Builder(SpashScreen.this).setMessage("You Need Accept This Location Based permissions In Order to Smooth Working Of Application Functionality")
.setPositiveButton("Ok",new SpashScreen.OkListenerForLocation())
.setNegativeButton("Cancel",null)
.create()
.show();
}
else if(!smspermissionaccepted){
new AlertDialog.Builder(SpashScreen.this).setMessage("You Need Accept This SMS Read permissions In Order to Smooth Working Of Application Functionality")
.setPositiveButton("Ok",new SpashScreen.OkListenerForSmS())
.setNegativeButton("Cancel",null)
.create()
.show();
}
break;
}
}
public class OkListenerForBoth implements AlertDialog.OnClickListener{
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onClick(DialogInterface dialog, int which) {
requestPermissions(perms,permsRequestCode);
}
}
public class OkListenerForLocation implements AlertDialog.OnClickListener{
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onClick(DialogInterface dialog, int which) {
requestPermissions(new String[]{perms[0]},permsRequestCode);
}
}
public class OkListenerForSmS implements AlertDialog.OnClickListener{
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onClick(DialogInterface dialog, int which) {
requestPermissions(new String[]{perms[1]},permsRequestCode);
}
}
}
Use the code below it will open a location request dialog and then you will be able to get the location.
if (googleApiClient == null) {
googleApiClient = new GoogleApiClient.Builder(getActivity())
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
googleApiClient.connect();
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(30 * 1000);
locationRequest.setFastestInterval(5 * 1000);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest);
builder.setAlwaysShow(true);
PendingResult<LocationSettingsResult> result =
LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
#Override
public void onResult(LocationSettingsResult result) {
final Status status = result.getStatus();
final LocationSettingsStates state = result.getLocationSettingsStates();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
try {
status.startResolutionForResult(
getActivity(), 1000);
} catch (IntentSender.SendIntentException e) {
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
break;
}
}
});
}
Please do this way
add library in app from gradle
// Dexter runtime permissions
implementation 'com.karumi:dexter:5.0.0'
// add permissions in manifest
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
// please call this method in your oncreate() method of splash.
requestPermission();
/**
* Requesting multiple permissions (storage and location) at once
* This uses multiple permission model from dexter
* On permanent denial opens settings dialog
*/
private void requestPermission() {
Dexter.withActivity(this)
.withPermissions(
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION)
.withListener(new MultiplePermissionsListener() {
#Override
public void onPermissionsChecked(MultiplePermissionsReport report) {
// check if all permissions are granted
if (report.areAllPermissionsGranted()) {
Log.e(TAG, "All permissions are granted!");
}
// check for permanent denial of any permission
if (report.isAnyPermissionPermanentlyDenied()) {
// show alert dialog navigating to Settings
showSettingsDialog();
}
}
#Override
public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {
token.continuePermissionRequest();
}
}).
withErrorListener(new PermissionRequestErrorListener() {
#Override
public void onError(DexterError error) {
Toast.makeText(getApplicationContext(), "Error occurred! ", Toast.LENGTH_SHORT).show();
}
})
.onSameThread()
.check();
}
/**
* Showing Alert Dialog with Settings option
* Navigates user to app settings
* NOTE: Keep proper title and message depending on your app
*/
private void showSettingsDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Need Permissions");
builder.setMessage("This app needs permission to use this feature. You can grant them in app settings.");
builder.setPositiveButton("GOTO SETTINGS", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
openSettings();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
// navigating user to app settings
private void openSettings() {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", getPackageName(), null);
intent.setData(uri);
startActivityForResult(intent, 101);
}
Hope it will help

How to fix "QR scanner is not scanning QR codes"?

I'm trying to develop an Android app that can scan QR codes. But the problem is, it only auto focus on the QR code but not returning any results. Is there a way to fix this?
I'm using zxing libraries.
Hello guys, can someone help me?
I guess you dont have onActivityResult in your code and that is why you cant capture and return any result.
So I am attaching my work and it would help you.
cameraView = (SurfaceView) v.findViewById(R.id.cameraView);
textResult = (TextView) v.findViewById(R.id.textView);
barcodeDetector = new BarcodeDetector.Builder(v.getContext())
.setBarcodeFormats(Barcode.QR_CODE)
.build();
cameraSource = new CameraSource.Builder(v.getContext(), barcodeDetector)
.setRequestedPreviewSize(640, 640).build();
cameraView.getHolder().addCallback(new SurfaceHolder.Callback() {
#Override
public void surfaceCreated(SurfaceHolder holder) {
if (ActivityCompat.checkSelfPermission(v.getContext(), android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
//Request permission
ActivityCompat.requestPermissions(getActivity(),
new String[]{android.Manifest.permission.CAMERA}, RequestCameraPermissionID);
return;
}
try {
cameraSource.start(cameraView.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
}
#Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
cameraSource.stop();
}
});
barcodeDetector.setProcessor(new Detector.Processor<Barcode>() {
#Override
public void release() {
}
#Override
public void receiveDetections(Detector.Detections<Barcode> detections) {
final SparseArray<Barcode> qrcodes = detections.getDetectedItems();
if (qrcodes.size() != 0) {
textResult.post(new Runnable() {
#Override
public void run() {
//Create vibrate
Vibrator vibrator = (Vibrator) getContext().getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(1000);
textResult.setText(qrcodes.valueAt(0).displayValue);
showResultDialogue(qrcodes.valueAt(0).displayValue);
}
});
}//End if Statement
}
});
Here is the onActivityResult and I think you dont have it.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
//We will get scan results here
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
//check for null
if (result != null) {
if (result.getContents() == null) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(getContext());
alertDialog.setTitle("Error");
alertDialog.setMessage("Scanning Error. Please try Again");
alertDialog.show();
} else {
//show dialogue with result
showResultDialogue(result.getContents());
}
} else {
// This is important, otherwise the result will not be passed to the fragment
super.onActivityResult(requestCode, resultCode, data);
}
}
//method to construct dialogue with scan results
public void showResultDialogue(final String result) {
final AlertDialog.Builder builder;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
builder = new AlertDialog.Builder(getContext(), android.R.style.Theme_Material_Dialog_Alert);
} else {
builder = new AlertDialog.Builder(getContext());
}
//If the text of QR Code is success then Check-in Successful.
//if(result.equalsIgnoreCase("success")){
//Stop the scanner
barcodeDetector.release();
builder.setTitle("Successfully Scan QR Code")
.setMessage("Result ---> " + result)
.setPositiveButton("DONE", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(getContext(), MainActivity.class);
startActivity(intent);
//Click ok and Back to Main Page
}
}).create().show();

When first open camera I don't have permissions

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

Android permission splash screen error API 19

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));
}

android call runtime permission with dialog

I have app that requests runtime permission for call on app start with dialog, but somehow my code doesn't request any permission or work. I need that when the app starts; ask the user for permission to call and in case the user refused, ask again for permission and move to in permissions settings.
Here's my code:
public class MainActivity extends AppCompatActivity {
private FirebaseAnalytics mFirebaseAnalytics;
private AdView mAdView;
private Button button_id;
private Button button_mobily;
private Button button_stc;
private Button button_zain;
private Button button_share;
private Button button_exit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dash);
NativeExpressAdView adView = (NativeExpressAdView)findViewById(R.id.adView);
AdRequest request = new AdRequest.Builder().build();
adView.loadAd(request);
mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
Bundle bundle = new Bundle();
bundle.putString(FirebaseAnalytics.Param.ITEM_ID, "main");
bundle.putString(FirebaseAnalytics.Param.ITEM_NAME, "opened");
bundle.putString(FirebaseAnalytics.Param.CONTENT_TYPE, "image");
mFirebaseAnalytics.logEvent(FirebaseAnalytics.Event.SELECT_CONTENT, bundle);
isPermissionGranted();
button_exit = (Button) findViewById(R.id.exit_buton_id);
button_share = (Button) findViewById(R.id.Share_buton);
button_id = (Button) findViewById(R.id.edit_id);
button_mobily = (Button) findViewById(R.id.mobily_buton);
button_stc = (Button) findViewById(R.id.stc_buton);
button_zain = (Button) findViewById(R.id.zain_buton);
button_id.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent myIntent = new Intent(MainActivity.this, NationalId.class);
MainActivity.this.startActivity(myIntent);
}
});
button_share.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
try {
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_SUBJECT, "test");
String sAux = "\n download my app\n\n";
sAux = sAux + "https://play.google.com/store/apps/details?id=Orion.Soft \n\n";
i.putExtra(Intent.EXTRA_TEXT, sAux);
startActivity(Intent.createChooser(i, "share on"));
} catch (Exception e) {
//e.toString();
}
}
});
button_exit.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
close();
}
});
button_mobily.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent myIntent = new Intent(MainActivity.this, OpreatorMobily.class);
MainActivity.this.startActivity(myIntent);
}
});
button_stc.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent myIntent = new Intent(MainActivity.this, OpreatorSTC.class);
MainActivity.this.startActivity(myIntent);
}
});
button_zain.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent myIntent = new Intent(MainActivity.this, OpreatorZain.class);
MainActivity.this.startActivity(myIntent);
}
});
}
public boolean isPermissionGranted() {
if (Build.VERSION.SDK_INT >= 23) {
if (checkSelfPermission(android.Manifest.permission.CALL_PHONE)
== PackageManager.PERMISSION_GRANTED) {
Log.v("TAG", "Permission is granted");
return true;
} else {
Log.v("TAG", "Permission is revoked");
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CALL_PHONE}, 1);
return false;
}
} else { //permission is automatically granted on sdk<23 upon installation
Log.v("TAG", "Permission is granted");
return true;
}
}
#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();
} else {
Toast.makeText(getApplicationContext(), "Permission denied", Toast.LENGTH_SHORT).show();
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
public void close() {
// TODO Auto-generated method stub
finish();
System.exit(0);
}
}
You don't need to check the Android version, Android is smart enough to know what the OS version is on the user's device.
Also if you're trying to get the ability to Call you need to change how the permission is called.
public boolean isPermissionGranted() {
Intent callOfficeIntent = new Intent(Intent.ACTION_CALL);
callOfficeIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
callOfficeIntent.setData(Uri.parse("tel:" + mNumberToCall));
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.CALL_PHONE},
10);
return;
} else {
try {
startActivity(callOfficeIntent);
} catch (ActivityNotFoundException e) {
Toast.makeText(getApplicationContext(), "No number to call", Toast.LENGTH_SHORT).show();
}
}
}
If you just want to get the permission but not make the call right away place this inside your method. This just asks for permission as a DialogBox.
if(ActivityCompat.checkSelfPermission(getActivity(),Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED){
if(ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),Manifest.permission.READ_PHONE_STATE)){
//Show Information about why you need the permission
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Need Permission");
builder.setMessage("This app needs phone permission.");
builder.setPositiveButton("Grant", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
requestPermissions(new String[]{Manifest.permission.READ_PHONE_STATE},PERMISSION_CALLBACK_CONSTANT);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
} else if (permissionStatus.getBoolean(Manifest.permission.READ_PHONE_STATE,false)) {
//Previously Permission Request was cancelled with 'Dont Ask Again',
// Redirect to Settings after showing Information about why you need the permission
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Need Permission");
builder.setMessage("This app needs storage permission.");
builder.setPositiveButton("Grant", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
sentToSettings = true;
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", getActivity().getPackageName(), null);
intent.setData(uri);
startActivityForResult(intent, REQUEST_PERMISSION_SETTING);
Toast.makeText(getActivity(), "Go to Permissions to Grant Phone", Toast.LENGTH_LONG).show();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
} else {
//just request the permission
requestPermissions(new String[]{Manifest.permission.READ_PHONE_STATE},PERMISSION_CALLBACK_CONSTANT);
}
txtPermissions.setText("Permissions Required");
SharedPreferences.Editor editor = permissionStatus.edit();
editor.putBoolean(Manifest.permission.READ_PHONE_STATE,true);
editor.commit();
} else {
//You already have the permission, just go ahead.
proceedAfterPermission();
}
}
});
}
private void proceedAfterPermission() {
txtPermissions.setText("We've got the permission");
Toast.makeText(getActivity(), "We got All Permissions", Toast.LENGTH_LONG).show();
}
Don't have to use the last method, just change the textView to a toast.
I found a simple Github library developed by "Nabin Bhandari". It is easy to implement and can be customized directly. Github library link...
Please add this dependency to add this library to your code.
implementation 'com.nabinbhandari.android:permissions:3.8'
This allow you to request single permission, multiple permission and do customize your own dialog.
Furthermore,
You can also override other methods like onDenied, onJustBlocked, etc if you want to change the default behaviour.
Dialogue messages and texts can be modified by building the options parameter.
See documentation in the source code for more customizations.
Use this code to ask multiple permissions samuntanely.
String[] permissions = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
Permissions.check(this/*context*/, permissions, null/*rationale*/, null/*options*/, new PermissionHandler() {
#Override
public void onGranted() {
// do your task.
}
});
Use this code if you want to Customized permissions request:
String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION};
String rationale = "Please provide location permission so that you can ...";
Permissions.Options options = new Permissions.Options()
.setRationaleDialogTitle("Info")
.setSettingsDialogTitle("Warning");
Permissions.check(this/*context*/, permissions, rationale, options, new PermissionHandler() {
#Override
public void onGranted() {
// do your task.
}
#Override
public void onDenied(Context context, ArrayList<String> deniedPermissions) {
// permission denied, block the feature.
}
});

Categories

Resources