我发现这个答案的零散部分通过其他帖子散播,但我想在这里为其他人记录它。Android获取位置或提示以启用位置服务,如果禁用
我该如何简单地请求用户的GPS和/或网络位置,如果他们还没有启用服务,提示他们这样做?
我发现这个答案的零散部分通过其他帖子散播,但我想在这里为其他人记录它。Android获取位置或提示以启用位置服务,如果禁用
我该如何简单地请求用户的GPS和/或网络位置,如果他们还没有启用服务,提示他们这样做?
如果你想捕捉按钮按下的位置,这是你怎么做的。如果用户没有启用位置服务,则会将它们发送到设置菜单以启用它。
首先,您必须将权限“android.permission.ACCESS_COARSE_LOCATION”添加到清单中。如果你需要GPS(网络位置是不够敏感),添加许可“android.permission.ACCESS_FINE_LOCATION”代替,并修改“Criteria.ACCURACY_COARSE”到“Criteria.ACCURACY_FINE”
Button gpsButton = (Button)this.findViewById(R.id.buttonGPSLocation);
gpsButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// Start loction service
LocationManager locationManager = (LocationManager)[OUTERCLASS].this.getSystemService(Context.LOCATION_SERVICE);
Criteria locationCritera = new Criteria();
locationCritera.setAccuracy(Criteria.ACCURACY_COARSE);
locationCritera.setAltitudeRequired(false);
locationCritera.setBearingRequired(false);
locationCritera.setCostAllowed(true);
locationCritera.setPowerRequirement(Criteria.NO_REQUIREMENT);
String providerName = locationManager.getBestProvider(locationCritera, true);
if (providerName != null && locationManager.isProviderEnabled(providerName)) {
// Provider is enabled
locationManager.requestLocationUpdates(providerName, 20000, 100, [OUTERCLASS].this.locationListener);
} else {
// Provider not enabled, prompt user to enable it
Toast.makeText([OUTERCLASS].this, R.string.please_turn_on_gps, Toast.LENGTH_LONG).show();
Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
[OUTERCLASS].this.startActivity(myIntent);
}
}
});
我的外部类有这个听众设置
private final LocationListener locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
[OUTERCLASS].this.gpsLocationReceived(location);
}
@Override
public void onProviderDisabled(String provider) {}
@Override
public void onProviderEnabled(String provider) {}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
然后,只要你想停止收听这个电话。您应该至少在您的活动的onStop方法中进行此调用。
LocationManager locationManager = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
locationManager.removeUpdates(this.locationListener);
要提示用户启用定位服务,你应该使用包含在谷歌播放服务的新LocationRequest,你可以发现在LocationRequest
完整指南通过大量的堆栈溢出的答案会后,我发现这种方法工作得很好,甚至不需要很多代码。
将int GPSoff = 0
声明为全局变量。
现在,无论你需要检查的GPS和重新定向用户的当前状态打开GPS上,使用此:
try {
GPSoff = Settings.Secure.getInt(getContentResolver(),Settings.Secure.LOCATION_MODE);
} catch (Settings.SettingNotFoundException e) {
e.printStackTrace();
}
if (GPSoff == 0) {
showMessageOKCancel("You need to turn Location On",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent onGPS = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(onGPS);
}
});
}
什么是getContentResolver(),showMessageOKCancel&startActivity?他们都没有解决 – hfz 2017-05-11 06:50:59
上getBestProvider第二个参数(locationCritera,真)检查哪些提供商因此,理论上,您不需要检查它是否再次启用。 – Eduardo 2012-03-29 07:43:21