这个问题已被多次询问,我发现了许多结果,但没有一个真正帮助过我。
使用以下代码打开GPS
String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
Log.i("GPS IS ON", "GPS IS ON"+provider.contains("gps"));
if(!provider.contains("gps")){ //if gps is disabled
Log.i("GPS IS ON", "GPS IS ON");
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);
}
并关闭:
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);
}
我在2个不同的点击上调用这两种不同的方法。它应该自动打开设备上的GPS,但它不起作用。
我甚至添加了这些权限:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
我已经在4.4和4.3中对这些进行了测试,并自动开启了GPS。
同样LOCATION_PROVIDERS_ALLOWED在4.4中已弃用,那么它的替代方案是什么?
修改
LocationManager locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener locListener = new MyLocationListener();
try {
gps_enabled = locManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
}
try {
network_enabled = locManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
}
// don't start listeners if no provider is enabled
// if(!gps_enabled && !network_enabled)
// return false;
if (gps_enabled) {
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
0, locListener);
}
if (gps_enabled) {
location = locManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
if (network_enabled && location == null) {
locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
0, 0, locListener);
}
if (location != null) {
MyLat = location.getLatitude();
MyLong = location.getLongitude();
}
我已经使用了此代码,但似乎如果互联网不存在则无法使用GPS关闭。
答案 0 :(得分:3)
我认为无法从任何应用程序更改用户的个人电话设置(如GPS开关,声音开关,显示等)。这将是安全的声音。
在我看来,这里只有选项是检查GPS是打开还是关闭,并将用户重定向到设置屏幕。
LocationManager manager = (LocationManager) getSystemService( Context.LOCATION_SERVICE );
if ( !manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
showPopupToRedirectToSettings();
}
通过使用以下Intent,您可以启动设置屏幕:
startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
答案 1 :(得分:0)
注意:如果您同时使用NETWORK_PROVIDER和GPS_PROVIDER,则只需要请求ACCESS_FINE_LOCATION权限,因为它包含两个提供商的权限。 (ACCESS_COARSE_LOCATION的权限仅包含NETWORK_PROVIDER的权限。)