【发布时间】:2012-09-14 20:33:01
【问题描述】:
我目前正在编写一个与 GPS 配合使用的 Android 应用。目前我能够确定是否启用了 GPS。我的问题是,如果 GPS 被禁用,我想在应用程序启动时启用它。我怎样才能以编程方式做到这一点? 另外,我想创建打开和关闭 GPS 的功能,我阅读了 stackoverflow 上关于它的所有线程,但是我尝试的所有功能我都得到了“不幸的是你的应用程序必须停止”(我没有忘记添加权限)
有人可以帮助我启用或禁用 GPS 的工作功能吗?
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS"/>
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
<uses-permission android:name="android.permission.CONTROL_LOCATION_UPDATES" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS" />
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
起初,我使用了这些功能:
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);
}
}
然后我尝试使用:
ENABLE GPS:
Intent intent=new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", true);
sendBroadcast(intent);
DISABLE GPS:
Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", false);
sendBroadcast(intent);
两者都不适合我
有人知道吗?
【问题讨论】:
-
获得强制关闭对话框并不意味着该方法不好。您尝试调试该问题还是放弃了?也许您应该发布一个您尝试过的代码示例以及您收到的错误,以便我们更好地帮助您。
-
感谢回复,我添加了我尝试使用的功能..希望有人能帮助我解决问题
-
在 Android 中,您不能(也不应该顺便说一句)以编程方式激活 GPS。你可以做的就是打开定位设置菜单,让用户自己打开它。
-
嗨,我从这里拿它:stackoverflow.com/questions/6925832/… 还有我如何打开 GPS 设置窗口?
标签: android