narendranathjoshi
narendranathjoshi

Reputation: 3096

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

Upvotes: 0

Views: 2778

Answers (3)

Karan Mavadhiya
Karan Mavadhiya

Reputation: 31

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

        }
    });

Upvotes: 0

MobileCushion
MobileCushion

Reputation: 7095

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

Upvotes: 2

CommonsWare
CommonsWare

Reputation: 1007554

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.

Upvotes: 1

Related Questions