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());
}
}
Related
If the location is disabled I want to show box and stop the execution process until I turn ON the location and come back to my app. Please Help with necessary suggestions.
function,
alertDialog.setTitle("GPS Setting");
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
alertDialog.setPositiveButton("OK ", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel ", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
Toast.makeText(mContext, "Sorry we cannot proceed", Toast.LENGTH_SHORT).show();
}
});
alertDialog.show();// Showing Alert Message
You should use ProgressDialog at https://developer.android.com/reference/android/app/ProgressDialog.html
see this example:
private ProgressDialog progressDialog;
public void cerrarSession() {
try {
showDialog();
// do something
} catch (InternetException e) {
// some exception
e.printStackTrace();
}
}
private void showDialog() {
progressDialog = new ProgressDialog(SavingsRequestsManager.getActivity());
progressDialog.setCancelable(false);
closeDialog();
progressDialog.setMessage(SavingsRequestsManager.getActivity().getString(R.string.progress));
progressDialog.show();
}
public void closeDialog() {
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
this is my Code. ( it make alertdialog to move Settings)
but I just want to enable GPS when I "ENABLE GPS" button click.
and Does android alway enable button click when I run app not just run once?
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Your GPS is disabled! Would you like to enable it?")
.setCancelable(false)
.setPositiveButton("Enable GPS",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
moveConfigGPS();
}
}).setNegativeButton("Do nothing",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
Update:
/**
* Check if GPS enabled or not
* and request dialog to enable GPS.
*/
private void checkWhetherLocationSettingsAreSatisfied() {
LocationRequest mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(1000)
.setNumUpdates(2);
final LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(mLocationRequest);
builder.setAlwaysShow(true);
builder.setNeedBle(true);
SettingsClient client = LocationServices.getSettingsClient(this);
Task<LocationSettingsResponse> task = client.checkLocationSettings(builder.build());
task.addOnSuccessListener(this, new OnSuccessListener<LocationSettingsResponse>() {
#Override
public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
Log.d(TAG, "onSuccess() called with: locationSettingsResponse = [" + locationSettingsResponse + "]");
hasLocationPermission();
}
});
task.addOnFailureListener(this, new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d(TAG, "onSuccess --> onFailure() called with: e = [" + e + "]");
if (e instanceof ResolvableApiException) {
// Location settings are not satisfied, but this can be fixed
// by showing the user a dialog.
try {
// Show the dialog by calling startResolutionForResult(),
// and check the result in onActivityResult().
ResolvableApiException resolvable = (ResolvableApiException) e;
resolvable.startResolutionForResult(BaseActivity.this,
Constants.REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Constants.REQUEST_CHECK_SETTINGS) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
hasLocationPermission();
} else {
//User clicks No
}
}
}
I think you want to turn on GPS location with one click like Google do.
To prompt the user for permission to modify the location settings, call startResolutionForResult(Activity, int). This method brings up a dialog asking for the user's permission to modify location settings.
You can't just enable GPS, you can only open gps settings with this intent:
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
User these method to on GPS :
intent1 = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent1);
and add these method to check GPS is on or Off ??
public void CheckGpsStatus(){
locationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
GpsStatus = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if(GpsStatus == true)
{
textview.setText("Location Services Is Enabled");
}else {
textview.setText("Location Services Is Disabled");
}
}
I know that the question about turning on/off GPS programmatically on android has been discussed many times. I have the same question that has been discussed in this link:
How can I enable or disable the GPS programmatically on Android?
But is there a way that works for android 6.x?
First you need get runtime permission for gps then this will work
Please check this link to enable and disable directly gps
https://stackoverflow.com/a/33555732
private void buildAlertMessageNoGps() {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(" Your GPS seems to be disabled, do you want to enable it?")
.setCancelable(false)
.setPositiveButton("ّyes", new DialogInterface.OnClickListener() {
public void onClick(#SuppressWarnings("unused") final DialogInterface dialog, #SuppressWarnings("unused") final int id) {
startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
})
.setNegativeButton("no", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, #SuppressWarnings("unused") final int id) {
dialog.cancel();
}
});
final AlertDialog alert = builder.create();
alert.show();
}
private void turnGPSOff(){
String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if(provider.contains("gps")){ //if gps is enabled
final Intent poke = new Intent();
poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
sendBroadcast(poke);
}
}
permission in android 6 down
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
and
permission android 6 up
if ( ContextCompat.checkSelfPermission(this,
android.Manifest.permission.ACCESS_FINE_LOCATION) ==
PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this,
android.Manifest.permission.ACCESS_COARSE_LOCATION) ==
PackageManager.PERMISSION_GRANTED) {
} else {
Toast.makeText(this, R.string.error_permission_map, Toast.LENGTH_LONG).show();
}
I want to give user dialog to set GPS on/off. Can this be done using the new SettingAPI? If so, how: I saw the code below, but not sure if it works for Android 2.3 devices via compatibility library or not? What versions of Android are supported. In particular does user need to be connected to net to use this service for GPS or will it work with settings on device directly no need for internet connection? Also does the dialog show just GPS settings or can user access other parts of settings? I'm trying to restrict to just GPS Settings.
LocationSettingsStates locationSettingsStates = locationSettingsResult.getLocationSettingsStates();
if (!locationSettingsStates.isGpsPresent() || !locationSettingsStates.isGpsUsable()) {
Status status = locationSettingsResult.getStatus();
if (status.getStatusCode() == LocationSettingsStatusCodes.RESOLUTION_REQUIRED) {
try {
status.startResolutionForResult(StilActivity.this, REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException th) {
Log.e(TAG, "Error opening settings activity.", th);
}
}
}
Just call the function and then
public void start() {
mlocManager = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
if (mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
Toast.makeText(getApplicationContext(), "Response ==>" + "GPS is on",
Toast.LENGTH_LONG).show();
} else {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
MainActivity.this);
alertDialogBuilder
.setMessage("GPS is disabled in your device. Enable it?")
.setCancelable(false)
.setPositiveButton("Enable GPS",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
Intent callGPSSettingIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
MainActivity.this.startActivity(callGPSSettingIntent);
}
});
alertDialogBuilder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
}
And just as a slight suggestion you could call the startActivityforResult() and the once the user comes back from the location page you can do your further execution.
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);
}
}