How to enable/disable gps and mobile data in android programmatically?

后端 未结 2 739
[愿得一人]
[愿得一人] 2021-01-01 04:49

I want my application to be able to enable/disable gps and mobile data programmatically as there are many apps like tasker, profile flow, lookout extra which can do this so

2条回答
  •  Happy的楠姐
    2021-01-01 05:24

    Try this for turning on gps

    public void turnGPSOn()
    {
         Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
         intent.putExtra("enabled", true);
         this.ctx.sendBroadcast(intent);
    
        String provider = Settings.Secure.getString(ctx.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")); 
            this.ctx.sendBroadcast(poke);
    
    
        }
    }
    

    for turning off gps,

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

    For mobile data, did you added the permission in manifest? If not try adding and check it.

    
    

    Let me know if everything worked.

提交回复
热议问题