【发布时间】:2011-03-29 02:15:42
【问题描述】:
我在其他帖子中发现了这个答案的零碎,但我想在这里记录下来以供其他人使用。
我怎样才能简单地请求用户的 GPS 和/或网络位置,如果他们没有启用该服务,提示他们这样做?
【问题讨论】:
标签: android geolocation gps
我在其他帖子中发现了这个答案的零碎,但我想在这里记录下来以供其他人使用。
我怎样才能简单地请求用户的 GPS 和/或网络位置,如果他们没有启用该服务,提示他们这样做?
【问题讨论】:
标签: android geolocation 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);
【讨论】:
在查看了 Stack Overflow 上的大量答案后,我发现这种方法工作得非常好,甚至不需要很多代码。
将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);
}
});
}
【讨论】:
要提示用户启用位置服务,您应该使用 google play 服务中包含的新 LocationRequest,您可以在 LocationRequest 中找到完整指南
【讨论】: