即使我安装了 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/