Skip to content Skip to sidebar Skip to footer

Enabling Gps Programmatically Not Working

I am trying to enable/disable (toggle) GPS programmatically in my app via a button click, but it is not working. Please help. My target devices are not rooted. Here's the code I'm

Solution 1:

You can't enable GPS programatically. The most you can do is open the settings for the user to do that.

You can do it like this:

startActivityForResult(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS), 100);

Solution 2:

I am trying to enable/disable (toggle) GPS programmatically in my app via a button click

This is not possible on modern versions of Android, for obvious privacy reasons.

but it is not working

There is no android.location.GPS_ENABLED_CHANGE action in the Android SDK. There is one used internally, but it merely announces a state change -- it does not actually change the state itself.

Solution 3:

you can force your app to see if you get a gps signal. if your not receiving signal, you can make a choise dialog, so the user can chose to go to the setings and turn on the gps.

// GPSTracker class
GPSTracker gps;

// CHECK GPS!
gps = newGPSTracker(YourActivityClass.this);
if (gps.canGetLocation()) {
} else {
    gps.showSettingsAlert();

        }

Then make a new class file and paste this code in it.. I did not write this code. i found it somewhere, dont remember where i got it from.

import android.app.AlertDialog;
 import android.app.Service;
 import android.content.Context;
 import android.content.DialogInterface;
 import android.content.Intent;
 import android.location.Location;
 import android.location.LocationListener;
 import android.location.LocationManager;
 import android.os.Bundle;
 import android.os.IBinder;
 import android.provider.Settings;
 import android.util.Log;

 publicclassGPSTrackerextendsServiceimplementsLocationListener {

privatefinal Context mContext;

// flag for GPS statusbooleanisGPSEnabled=false;

// flag for network statusbooleanisNetworkEnabled=false;

// flag for GPS statusbooleancanGetLocation=false;

Location location; // locationdouble latitude; // latitudedouble longitude; // longitude// The minimum distance to change Updates in metersprivatestaticfinallongMIN_DISTANCE_CHANGE_FOR_UPDATES=10; // 10 meters// The minimum time between updates in millisecondsprivatestaticfinallongMIN_TIME_BW_UPDATES=1000 * 60 * 1; // 1 minute// Declaring a Location Managerprotected LocationManager locationManager;

publicGPSTracker(Context context) {
    this.mContext = context;
    getLocation();
}

public Location getLocation() {
    try {
        locationManager = (LocationManager) mContext
                .getSystemService(LOCATION_SERVICE);

        // getting GPS status
        isGPSEnabled = locationManager
                .isProviderEnabled(LocationManager.GPS_PROVIDER);

        // getting network status
        isNetworkEnabled = locationManager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (!isGPSEnabled || !isNetworkEnabled) {
            // no network provider is enabled
        } else {
            this.canGetLocation = true;
            // if GPS Enabled get lat/long using GPS Servicesif (isGPSEnabled) {
                locationManager.requestLocationUpdates(
                        LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                Log.d("GPS Enabled", "GPS Enabled");
                if (locationManager != null) {
                    location = locationManager
                            .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                    if (location != null) {
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                    }
                }
            }
            if (isNetworkEnabled) {
                if (locationManager == null) {
                    locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("Network", "Network");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return location;
}

/**
 * Stop using GPS listener
 * Calling this function will stop using GPS in your app
 * */publicvoidstopUsingGPS(){
    if(locationManager != null){
        locationManager.removeUpdates(GPSTracker.this);
    }
}

/**
 * Function to get latitude
 * */publicdoublegetLatitude(){
    if(location != null){
        latitude = location.getLatitude();
    }

    // return latitudereturn latitude;
}

/**
 * Function to get longitude
 * */publicdoublegetLongitude(){
    if(location != null){
        longitude = location.getLongitude();
    }

    // return longitudereturn longitude;
}

/**
 * Function to check GPS/wifi enabled
 * @return boolean
 * */publicbooleancanGetLocation() {
    returnthis.canGetLocation;
}

/**
 * Function to show settings alert dialog
 * On pressing Settings button will lauch Settings Options
 * */publicvoidshowSettingsAlert(){
    AlertDialog.BuilderalertDialog=newAlertDialog.Builder(mContext);

    // Setting Dialog Title
    alertDialog.setTitle("GPS settings");

    // Setting Dialog Message
    alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

    // On pressing Settings button
    alertDialog.setPositiveButton("Settings", newDialogInterface.OnClickListener() {
        publicvoidonClick(DialogInterface dialog,int which) {
            Intentintent=newIntent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            mContext.startActivity(intent);
        }
    });

    // on pressing cancel button
    alertDialog.setNegativeButton("Cancel", newDialogInterface.OnClickListener() {
        publicvoidonClick(DialogInterface dialog, int which) {
        dialog.cancel();
        }
    });

    // Showing Alert Message
    alertDialog.show();
}

@OverridepublicvoidonLocationChanged(Location location) {
}

@OverridepublicvoidonProviderDisabled(String provider) {
}

@OverridepublicvoidonProviderEnabled(String provider) {
}

@OverridepublicvoidonStatusChanged(String provider, int status, Bundle extras) {
}

@Overridepublic IBinder onBind(Intent arg0) {
    returnnull;
}
 }

in my app i have put in the shared prefs so the user can decide if he wants to check the gps or not. you can do it like this..

SharedPreferencesgetData= PreferenceManager
            .getDefaultSharedPreferences(getBaseContext());
    StringenableGPS= getData.getString("gps", "true");
    booleanenableGPSboolean= Boolean.parseBoolean(enableGPS);

    if (enableGPSboolean == (true)) {

        // CHECK GPS!// create class object
        gps = newGPSTracker(AddFish.this);

        if (gps.canGetLocation()) {

        } else {

            gps.showSettingsAlert();

        }
    }

Solution 4:

// location manager

LocationManager locationManager; LocationListener locationListener;

obj_tgl_gps.setOnClickListener(new OnClickListener() {

publicvoidonClick(View v)
        {
            if (obj_tgl_gps.isChecked())
            {
                Intentintent=newIntent("android.location.GPS_ENABLED_CHANGE");
                intent.putExtra("enabled", true);
                sendBroadcast(intent);
            }
            else
            {
                Intentintent=newIntent("android.location.GPS_ENABLED_CHANGE");
                intent.putExtra("enabled", false);
                sendBroadcast(intent);
            }

        }
    });

Post a Comment for "Enabling Gps Programmatically Not Working"