android - GPS OnPause 代码不会关闭 GPS

标签 android

即使我安装了 OnPause 代码来停止 GPS 服务,GPS 也不会停止。这是我的代码。

    @Override
    protected void onPause() {
        if(lm != null) {
            lm.removeUpdates(ll);
        }
        ll = null;
        lm = null;
        super.onPause();
    }

只要 lm 和 ll 被声明为全局 protected 变量,这段代码就可以正常运行。问题是在我离开程序后 GPS 图标仍然亮着。如何关闭 GPS?我已经在手机和模拟器上对此进行了测试。

最佳答案

正如文档所说 removeUpdates(LocationListener listener) :

Removes any current registration for location updates of the current activity with the given LocationListener.

仅您的当前代码使用给定的 LocationListener 删除当前 Activity 的位置更新的任何当前注册,而不是停止 GPS 或删除图标 来自状态栏。所以你想停止 GPS 那么你有两个解决方案

第一个解决方案:通过代码停止(仅适用于 Android 2.3 以下):

  try{
    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);
     }
     }
     catch(Exception e)
     {
      Log.d("Location", " exception thrown in enabling GPS "+e);
     }

Manifest.xml 中的权限:

android.permission.WRITE_SECURE_SETTINGS

第二个解决方案:启动 Gps 设置 Activity :

startActivityForResult(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS), 1);

关于android - GPS OnPause 代码不会关闭 GPS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11408018/

相关文章:

java - 如何解析 Android XML 中的同名标签?

android - 以正确的方式过滤游标?

android - ListView 不显示任何项目

java - 如何使用触摸监听器并仅在触摸按钮时播放声音?

java - Android与PC之间的双向通信

java - 如何更改来自不同类的变量?

java - 将 Shift_JIS 格式转换为 UTF-8 格式

android - 谷歌地图无法在普通设备上加载,但会在测试设备(真实设备)上加载

android - 安装应用程序时如何使用应用程序链接将参数传递给要检索的android playstore

java - 如何在android中加密和解密字符串值?