开启关闭GPS的Android
问题描述:
可能重复:
How to programmatically enable GPS in Android Cupcake开启关闭GPS的Android
我目前正在写在Android的一个应用程序,与GPS的工作原理。目前我能够确定GPS是否启用。我的问题是,我想要启用应用程序启动时的GPS,如果它被禁用。我怎样才能做这个programmaticaly? 另外,我想创建打开和关闭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);
两者不是为我工作
任何一个有想法?
答
您无法以编程方式打开和关闭GPS。你可以做的最好的事情是将用户发送到设置屏幕,让他们自己做。
final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
存在着黑客打开GPS /关闭程序,但他们只在旧版Android的工作。即使你可以,也不要这样做。用户可能已经关闭了GPS,因为他们不想让应用程序精确地跟踪它们。试图强迫改变他们的决定是非常糟糕的形式。
如果您需要启用GPS,请在您的应用程序启动时检查它,如果用户不启用它,则保释。
+0
这就是我想要的! – GeekHades
仅仅因为你得到一个强制关闭对话框并不意味着该方法是不好的。你尝试过调试这个问题还是放弃了?也许你应该发布一个你试过的代码示例,并收到了什么错误,以便我们能够更好地帮助你。 – Samuel
感谢您的回复,我添加了功能,我尝试使用..我希望有人会帮助我解决问题 –
在Android中,你不能(也不应该btw)以编程方式激活GPS。您只需打开“定位设置菜单”并让用户自行打开。 – alex