【问题标题】:Disable GPS Location禁用 GPS 定位
【发布时间】:2014-05-25 05:56:27
【问题描述】:

我想启用和禁用 GPS。我想要像谷歌地图应用程序一样,当运行应用程序时,应用程序询问我启用我的位置,当我的应用程序进入后台(暂停状态)gps 禁用时,我的意思是我在屏幕顶部看不到 gps 图标,然后再次应用程序进入前台,我的位置再次启用。我没有使用 LocationOverlay 。我在onPause() 方法中写了locationManager.removeUpdates(locationListener);,但是当我的应用程序进入后台时,我看到gps 打开并启用并尝试检测我的位置!

我写了启用位置,但我不知道如何禁用 gps 然后隐藏 gps 图标!

请帮帮我

感谢您的建议。

【问题讨论】:

    标签: android gps


    【解决方案1】:

    Disable GPS programmatically on Android

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

    移除图标并关闭 GPS:

    locationManager.removeUpdates(myLocationListener); 
    locationManager = null;
    

    【讨论】:

    • 感谢您的回答。我编写了没有 removerUpdates() 的 turnGPSOff() 方法,并且当应用程序进入后台时。全球定位系统关闭。 removeUpdates() 和 turnGPSOff() 有什么区别?
    • 和另一个问题。我想在您的发送链接中使用第二个答案禁用 gps 时,我的 gps 禁用但打开,并且当我再次进入应用程序时,在 onResume() 中,我如何在启用此功能后检测 gps 禁用它并且如果 gps 已关闭,我打开gps!我使用此代码检测 gps 的开启和关闭: (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
    【解决方案2】:

    试试这些:

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

    请注意您需要设置适当的应用权限。

    【讨论】:

    • 看起来关闭和打开使用相同的代码,所以我们可以只使用一个切换功能来打开和关闭
    猜你喜欢
    • 2019-01-04
    • 2015-12-18
    • 2019-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多