Archive for June, 2012

Toggle on/off GPS in Android

Posted: June 3, 2012 in Android
Tags: ,

Hello folks, here am again with android simple code of GPS toggle on/off from code.
what you have to do is just copy the following code in Global.java (where you set your global variables and functions)

when you need to turn on GPS, just call Global.turnGPSOn(“your context”)

here, “your context” will be the class file from where you are calling this function,
let say, i have a class file, named “SplashActivity.java” so what i have to pass as a parameter in that function is,
Global.turnGPSOn(SplashActivity.this);

you can also use, getApplicationContext() as a parameter. But I recommend to use class file name.

Now here is the code,

public static void turnGPSOn(Context context){
        String provider = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);

        if(!provider.contains("gps"))
{ //if gps is disabled
            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")); 
            context.sendBroadcast(poke);
        }
    }
    
    public static void turnGPSOff(Context context){
        String provider = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);

        if(provider.contains("gps")){
            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")); 
            context.sendBroadcast(poke);
        }
    }    

we heard and face so many times that our phone battery is drawn and all that, its due to constant pinging of GPS from any application, which will cause the battery issues. So when you need to fetch location from GPS provider, just turn on the GPS from code and after using it, turn off it.