Android 4.1.2 How to turn off GPS programmatically

前端 未结 5 614
有刺的猬
有刺的猬 2020-12-05 22:20

I am trying to switch on GPS by code. The following is the code I\'ve used.

String provider = Settings.Secure.getString(context.getContentResolver(),Settings         


        
5条回答
  •  再見小時候
    2020-12-05 22:40

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

    Method1:

     // automatic turn off the 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);
            }
        }
    

    try this if above method doesn't work

    Method 2:

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

提交回复
热议问题