How can i enable and disable GPS programatically

天涯浪子 提交于 2019-12-04 15:49:01

Here is the code...

 private void turnGPSOn(){   

    String provider = Settings.Secure.getString(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"));      
        sendBroadcast(poke);  
   }  }    

You can start the GPS by using

LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
    LocationListener locationListener = new CTLocationListener();
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 1.0f, locationListener);

To stop the gps provider use

locationManager.removeUpdates(locationListener);

I researched about this subject on all web sites. and I found this code like below. I tried its working.

Method-1

Enable GPS
Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", true);
sendBroadcast(intent);
Disable GPS
Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", false);
sendBroadcast(intent);

Method-2

 // If GPS is OFF
    private void turnGPSOn(){
        String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
        if(!provider.contains("gps")){
            final Intent intent = new Intent();
            intent.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
            intent.addCategory(Intent.CATEGORY_ALTERNATIVE);
            intent.setData(Uri.parse("3"));
            sendBroadcast(intent);
        }
    }
    // If GPS is ON
    private void turnGPSOff(){
        String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
        if(provider.contains("gps")){
            final Intent intent = new Intent();
            intent.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
            intent.addCategory(Intent.CATEGORY_ALTERNATIVE);
            intent.setData(Uri.parse("3"));
            sendBroadcast(intent);
        }
    }

Fore more information you can visit this web site : http://androidmaterial.blogspot.com/2012/04/how-to-enabledisable-gps-in-android.html

Here is all I can find (my code doesn't run in an activity so I have an ApplicationContext class that I call a static method getInstance. You don't have to do this in an activity. Sorry for the code formatting):

public static boolean isGPSEnabled(){
        LocationManager locationManager = (LocationManager)ApplicationContext.getInstance().getSystemService(Context.LOCATION_SERVICE);
        boolean enabled = locationManager.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER );
        if(enabled) return enabled;
        String provider = Settings.Secure.getString(ApplicationContext.getInstance().getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
        return provider.contains("gps");
    }

private static boolean canToggleGPSDirectly() {
        PackageManager pacman = ApplicationContext.getInstance().getPackageManager();
        PackageInfo pacInfo = null;

        try {
            pacInfo = pacman.getPackageInfo("com.android.settings", PackageManager.GET_RECEIVERS);
        } catch (NameNotFoundException e) {
            return false; //package not found
        }

        if(pacInfo != null){
            for(ActivityInfo actInfo : pacInfo.receivers){
                //test if recevier is exported. if so, we can toggle GPS.
                if(actInfo.name.equals("com.android.settings.widget.SettingsAppWidgetProvider") && actInfo.exported){
                    return true;
                }
            }
        }

        return false; //default
    }

//this only works in older versions of android (it woks on 2.2)
private static void toggleGPS(){
        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")); 
        ApplicationContext.getInstance().sendBroadcast(poke);
    }

private static void showGPSSettingsScreen(){
        //show the settings screen
        Intent myIntent = new Intent( Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        ApplicationContext.getInstance().startActivity(myIntent);

        // this doens't work if your app isn't signed as firmware....Settings.Secure.setLocationProviderEnabled(ApplicationContext.getInstance().getContentResolver(), LocationManager.GPS_PROVIDER, true);
    }

public static void ensureGPSStatus(boolean on){
        boolean isGPSEnabled = isGPSEnabled();
        if((isGPSEnabled && !on) || (!isGPSEnabled && on)){
            if(canToggleGPSDirectly()){
                toggleGPS();
            }else{
                showGPSSettingsScreen();
            }
        }
    }

To Disable the GPS through your code,

    Intent my_intent = new Intent();
    my_intent.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
    my_intent.addCategory(Intent.CATEGORY_ALTERNATIVE);
    my_intent.setData(Uri.parse("3")); 
     sendBroadcast(my_intent);  //use context.sendBroadcast(my_intent) if you are in any Broadcast activity

If I am not mistaken, you can't do it entirely programmatically. The best is to fire an intent to start the settings page but subsequently user must enable the gps setting in the settings page.

You can't do it in the background without user intervention.

I know it is too late but directly starting location service will not work. Instead use below code to start location service.

Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);

GpsSettings

public class GpsSettings
{
    @SuppressWarnings("deprecation")
    public static void turnGPSOn(Context context)
    {

        Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");

        intent.putExtra("enabled", true);

        context.sendBroadcast(intent);  

        String provider = Settings.Secure.getString(context.getContentResolver(),
                Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
        Settings.Secure.setLocationProviderEnabled(context.getContentResolver(), "gps", true);

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

    @SuppressWarnings("deprecation")
    public static void turnGPSOff(Context context)
    {

        Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");

        intent.putExtra("enabled", false);

        context.sendBroadcast(intent);  
        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);
        }
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!