0

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 using.

private void gps()
{
Intent intent=new Intent("android.location.GPS_ENABLED_CHANGE");
Button gps = (Button)findViewById(R.id.gpsButton);
if(isGPSon())
    {
    intent.putExtra("enabled", true);
    gps.setText(R.string.f2_gps_deact);
    }
else
    {
    intent.putExtra("enabled", false);
    gps.setText(R.string.f2_gps_act);
    }
sendBroadcast(intent);
narendranathjoshi
  • 2,876
  • 2
  • 19
  • 19
  • possible duplicate of [Enable GPS programatically like Tasker](http://stackoverflow.com/questions/4721449/enable-gps-programatically-like-tasker) – FoamyGuy Jul 23 '12 at 17:07

3 Answers3

2

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);
MobileCushion
  • 7,065
  • 7
  • 42
  • 62
  • Then how do 3rd party apps like Go Switch widgets do it? – narendranathjoshi Jul 23 '12 at 19:09
  • As far as I know, there seemed to be some kind of exploit that enabled to switch access to GPS data. But apparently that was fixed in 2.3 or so. These subjects have been discussed exhaustively in SO, and everyone seems to reach the same conclusion. If there are widgets that can do it, either they are firmware wids or they exploit any other kind of security flaw, and they shouldn't. – MobileCushion Jul 23 '12 at 20:18
1

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.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
0
// location manager

LocationManager locationManager; LocationListener locationListener;

obj_tgl_gps.setOnClickListener(new OnClickListener() {

        public void onClick(View v)
        {
            if (obj_tgl_gps.isChecked())
            {
                Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
                intent.putExtra("enabled", true);
                sendBroadcast(intent);
            }
            else
            {
                Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
                intent.putExtra("enabled", false);
                sendBroadcast(intent);
            }

        }
    });