Refreshing activity after user changed location settings - android

User flow: Clicks a button, is redirected to MapActivity where a google maps is shown. A location is given, there is a button to make a route using current location to the given location. When location services is turned off the user is prompted to turn it on.
private void goToLocationSettings(){
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS );
startActivityForResult(intent, 1);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == 1) {
switch (requestCode) {
case 1: Log.e("test", "onActivityResult");
break;
}
}
}
When the user returns the function should be able to complete. But the program again to turn the settings on. The log is never shown.
If I wait a bit after turning on location services on my device I do not get the question to turn it on, but the log message is still not shown.
I have no idea what I am doing wrong.

You are checking for the wrong resultCode, to avoid confusion use constants Activity#RESULT_OK and Activity#RESULT_CANCELED. If you check the docs you can see that RESULT_OK has an int value of -1.
In the case of starting Location Settings Activity for result, the resultCode will always be 0 because the user exits the Settings Activity with a back button, so to the system it looks like he canceled the request.
static final int LOCATION_SETTINGS_REQUEST = 1;
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
if (requestCode == LOCATION_SETTINGS_REQUEST) {
// user is back from location settings - check if location services are now enabled
checkGPS();
}
}

The dialog box with out a result intent can be like this we need to allow the user to navigate and check the location services
accepted
In the case of starting Location Settings Activity for result, the resultCode will always be 0 because the user exits the Settings Activity with a back button, so to the system it looks like he canceled the request.
The code is here like which allow the dilog to navigate to setting page .
public void showLocationAlert() {
if (!ismctLocationEnabled(this)) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(ContentTransferBaseActivity.this);
alertDialog.setTitle(R.string.mct_enable_Location_title);
alertDialog.setMessage(R.string.mct_enable_location_message);
alertDialog.setCancelable(true);
alertDialog.setPositiveButton(R.string.mct_button_Enable,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
});
alertDialog.setNegativeButton(R.string.mct_button_Dismiss,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
if(!ismctLocationEnabled(this)) {
alertDialog.show();
}else
{
AlertDialog dialog=alertDialog.create();
dialog.dismiss();
}
}
}
public static boolean ismctLocationEnabled(Context context) {
int locationMode = 0;
String locationProviders;
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P) {
try {
locationMode = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE);
} catch (Settings.SettingNotFoundException e) {
e.printStackTrace();
return false;
}
return locationMode != Settings.Secure.LOCATION_MODE_OFF;
} else {
locationProviders = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
return !TextUtils.isEmpty(locationProviders);
}
}

Related

Freeze activity after Dialog prompt on onActivityResult function

I want my application to continue accepting image from the gallery if I chose Upload Image from the dialog box, but the problem is that the function will continue to finish (the log for count is printed even if I didn't pressed any button, and the conditional statement will set cont = false). The decision variable is a global string variable.
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
boolean cont = true;
while (cont == true) {
if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {
functionHere();
}
if (requestCode == OPEN_DOCUMENT_CODE && resultCode == RESULT_OK) {
if (data != null) {
// this is the image selected by the user
try {
functionHere();
} catch (Exception ex) {
Log.i("Error", ex.toString());
}
}
}
continuePrompt();
if(decision == "Upload"){
requestCode = OPEN_DOCUMENT_CODE;
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(intent, OPEN_DOCUMENT_CODE);
}
else if(decision == "Take Picture"){
//code here
}
else if(decision == "End"){
cont = false;
}
else{
cont = false;
}
Log.d("Count", Integer.toString(count));
}
if (cont == false) {
//output result
}
}
Here is my code for my dialog which I get from another question here in stackoverflow
public void continuePrompt() {
// setup the alert builder
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Platelet detection");
builder.setMessage("Are all microscopic slide image uploaded?");
// add the buttons
builder.setPositiveButton("Upload Image", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
decision = "Upload";
}
});
builder.setNeutralButton("Take Picture", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
decision = "Take Picture";
}
});
builder.setNegativeButton("End", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
decision = "End";
}
});
// create and show the alert dialog
builder.show();
}
you still have below line in your code
while (cont == true)
even when you show your dialog this loop is iterating over and over again. you should fix your logic, there shouldn't be any while loop, everything is already in UI thread and with above line you are hanging it showing dialogs one after another. you should show your prompt once and instead of setting global decision variable just place your code response for action in listener
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {
functionHere();
continuePrompt();
}
else if (requestCode == OPEN_DOCUMENT_CODE && resultCode == RESULT_OK) {
if (data != null) {
// this is the image selected by the user
try {
functionHere();
continuePrompt();
} catch (Exception ex) {
Log.i("Error", ex.toString());
}
}
}
else{
super.onActivityResult(requestCode, resultCode, data);
}
}
private void continueFlow(){
if("Upload".equals(decision)){
requestCode = OPEN_DOCUMENT_CODE;
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(intent, OPEN_DOCUMENT_CODE);
}
else if("Take Picture".equals(decision)){
//code here
}
}
just call continueFlow(); after every decision change (in every listener). or move code form if("Upload".equals(decision)){ straight to setPositiveButton and so on
btw. decision == "Upload" won't ever be true as == operator is comparing same objects. decision is already declared variable and "Upload" String is freshly created in if statement, its brand new variable. for comparing content of Strings (same text) use stringOne.equals(stringTwo);

How to combine insert code and bar code code together in android?

I have two sets of code. Both sets require the same name onActivityResult but I'm not sure how to combine them without clashing.
The two sets of code are:
1st Set: Users are required to click on the no-image ImageView to select an image from their mobile device and then it will display the image that they have selected.
2nd Set: Users are required to click a Button to scan a barcode. It will open a camera for the user to scan the barcode and after scanning, it will display the number from the barcode.
Here is the code for two sets:
1st Set of Code:
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Check for Image Request , If user get the image is ok, and the image is not null
if(requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null){
//Put the image data into this mImageUri
mImageUri = data.getData();
//This line take the data from mImageUri and load into mImageView so basically changing the uri to image
Picasso.with(this).load(mImageUri).into(ItemORFoodImg);
}
}
2nd Set of Code:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
final IntentResult result = IntentIntegrator.parseActivityResult(requestCode,resultCode,data);
if(result != null){
if(result.getContents() == null){
Toast.makeText(this, "Result Not Found", Toast.LENGTH_SHORT).show();
}
else{
AlertDialog.Builder alertdialogbuilder = new AlertDialog.Builder(this);
alertdialogbuilder.setMessage(result.getContents()+"\n\nWant to add as new item?");
alertdialogbuilder.setTitle("ResultScanned");
alertdialogbuilder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
String barcode = result.getContents();
Intent intent = new Intent(BarcodeTest.this,AddNewItem.class);
intent.putExtra(BarID, barcode);
startActivity(intent);
}
});
alertdialogbuilder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
}
});
AlertDialog alertDialog = alertdialogbuilder.create();
alertDialog.show();
}
}
else {
super.onActivityResult(requestCode,resultCode,data);
}
}
Can someone help me combine these two code snippets without clashing?
You can use IntentService.
You can create two java class one for insert code and one for QR code.
When pressed ImageView go to insert code class and when pressed button go to QR code class.
And then pass data to your Activity.
Follow this link
https://developer.android.com/reference/android/app/IntentService

How to get the result of the qr code to the dialog box then will open to the another activity?

I have an app that will scan Qr code. The Qr code have a default value that if you scan it will go to a dialog box with the result and will call the activity with the same result
I want to happen is when the result of the qr scan is in the dialog box if the result of it is the same with the activity it will open the activity if not it will call a wrong qr.
#Override
protected 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) {
// Toast.makeText(this, "Scan Cancelled", Toast.LENGTH_LONG).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) {
AlertDialog.Builder builder;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
builder = new AlertDialog.Builder(this, android.R.style.Theme_Material_Dialog_Alert);
} else {
builder = new AlertDialog.Builder(this);
}
builder.setTitle("Scan Result")
.setMessage(result)
.setPositiveButton("View your Location", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("Scan Result", result);
clipboard.setPrimaryClip(clip);
Intent nxt = new Intent(MainActivity.this, Acad1.class);
startActivity(nxt);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
dialog.dismiss();
}
})
.show();
}
No. What i want is when you scan a qr code with the same name with activity it will open first the dialog box and then when you click the view location it will go to the activity with the same name of the result.

Starting Settings Activity for result

In my application I'm checking whether the GPS is enabled on the user's device, and if not I would like to send him to the Settings to let him turn it on.
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivityForResult(intent, LocationHelper.LOCATION_SETTINGS_REQUEST_CODE);
After the user closes Settings screen, I would to perform an action right inside the onActivityResult().
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == LocationHelper.LOCATION_SETTINGS_REQUEST_CODE) {
LogUtils.d("onActivityResult from settings");
fetchCurrentLocation();
}
}
However, the onActivityResult() doesn't get called. Am I doing something wrong or this approach doesn't work in general? Thanks in advance.
lauch the setting intent :
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
and fetch the current location in onResume method :
public void onResume(){
super.onResume();
if(isGPSEnabled){
fetchCurrentLocation();
}
}
after backing from setting screen , your onResume method will be call and here you can fetch your location.
Enable GPS programmatically using the following code,
private void askToEnableGPS(){
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setPriority(Priority.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(10 * 1000);
locationRequest.setFastestInterval(2 * 1000);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest);
LocationSettingsRequest mLocationSettingsRequest = builder.build();
SettingsClient settingsClient = LocationServices.getSettingsClient(this);
settingsClient.checkLocationSettings(mLocationSettingsRequest)
.addOnSuccessListener(new OnSuccessListener<LocationSettingsResponse>() {
#Override
public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull #NotNull Exception e) {
int statusCode = ((ApiException) e).getStatusCode();
switch (statusCode) {
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
try {
// Show the dialog by calling startResolutionForResult(), and check the
// result in onActivityResult().
ResolvableApiException rae = (ResolvableApiException) e;
rae.startResolutionForResult(MainActivity.this, 5678);
} catch (IntentSender.SendIntentException sie) {
Log.i(TAG, "PendingIntent unable to execute request.");
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
String errorMessage = "Location settings are inadequate, and cannot be " +
"fixed here. Fix in Settings.";
Log.e(TAG, errorMessage);
// notify user
new androidx.appcompat.app.AlertDialog.Builder(new ContextThemeWrapper(MainActivity.this,
R.style.Theme_MaterialComponents_DayNight_DarkActionBar)).setMessage("Please enable location services").setCancelable(false).setPositiveButton("Open location settings", (dialog, which) -> {
startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}).create().show();
break;
}
}
});
}
And get the results in onActivityResult with Request Code 5678.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 5678 && resultCode == RESULT_OK) {
// GPS Enabled
}
}
Have you defined ACCESS_FINE_LOCATION permission in your manifest?
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>

How to notify the user to enable gpsprovider

i'm working on gpsprovider,If user click on a gps based applications for suppose map application it has check whether the gps provider enabled or not if not alert the user enable the gpsprovider .
There will be a Broadcast Receivier.
Will define a message for requesting the service from any application. Will start service if not started.
Will define a message for stating that the application no longer needs it. Will stop service if no app needs it anymore
String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if(provider != null ){
if(! provider.contains("gps")){
// Notify users and show settings if they want to enable GPS
new AlertDialog.Builder(MessagePage.this)
.setMessage("GPS is switched off. enable?")
.setPositiveButton("Enable GPS", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivityForResult(intent, 5);
}
})
.setNegativeButton("Don't do it", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
}
})
.show();
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if(requestCode == 5 && resultCode == 0){
String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if(provider != null){
switch(provider.length()){
case 0:
//GPS still not enabled..
break;
default:
Toast.makeText(this, "GPS is now enabled.", Toast.LENGTH_LONG).show();
break;
}
}
}
else{
//the user did not enable his GPS
}
}
AFAIK it is still not possible to start the GPS service programatically. The only thing you can do is open the settings page for the user to change the setting them selves:
if(!LocationManager.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER ))
{
Intent myIntent = new Intent( Settings.ACTION_SECURITY_SETTINGS ); startActivity(myIntent);
}
In your CommonUtils.java
public class CommonUtils {
public static void displayPromptForEnablingGPS(
final Activity activity)
{
final AlertDialog.Builder builder =
new AlertDialog.Builder(activity);
final String action = Settings.ACTION_LOCATION_SOURCE_SETTINGS;
final String message = "Enable either GPS or any other location"
+ " service to find current location. Click OK to go to"
+ " location services settings to let you do so.";
builder.setMessage(message)
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface d, int id) {
activity.startActivity(new Intent(action));
d.dismiss();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface d, int id) {
d.cancel();
}
});
builder.create().show();
}
}
In your activity
private void getGPSInfo() {
LocationManager locationmanager = (LocationManager) getActivity()
.getSystemService(Context.LOCATION_SERVICE);
if (locationmanager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
// YOUR MAPS ACTIVITY CALLING or WHAT YOU NEED
} else {
CommonUtils.displayPromptForEnablingGPS(getActivity());
}
}

Categories

Resources