【发布时间】:2011-04-22 16:25:52
【问题描述】:
我见过各种代码 sn-ps 可以从各种方法(如 onlocationupdate() 或 onstatusChanged()...一个按钮...
【问题讨论】:
我见过各种代码 sn-ps 可以从各种方法(如 onlocationupdate() 或 onstatusChanged()...一个按钮...
【问题讨论】:
Yogsma 的回答解决了如何接收自动更新。他引用的链接提供了您所需要的一切,但这里是如何进行手动更新的总结版本:
假设您已阅读有关如何制作按钮的教程,那么您只需为您的按钮添加一个侦听器,然后让侦听器调用一个函数来查询您的位置管理器。下面的代码全部内联以向您展示如何操作,但我会在其他地方(例如您的活动)实例化 LocationManager,并且我会为点击监听器创建一个单独的方法来调用以执行更新。
// getLocationButton is the name of your button. Not the best name, I know.
getLocationButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// instantiate the location manager, note you will need to request permissions in your manifest
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// get the last know location from your location manager.
Location location= locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
// now get the lat/lon from the location and do something with it.
nowDoSomethingWith(location.getLatitude(), location.getLongitude());
}
});
当然,您还需要在清单 xml 文件中使用位置管理器服务注册您的活动:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
【讨论】:
LocationManager mLocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener mLocListener = new MyLocationListener();
mLocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mLocListener);
public class MyLocationListener implements LocationListener{
public void onLocationChanged(Location loc) {
String message = String.format(
"New Location \n Longitude: %1$s \n Latitude: %2$s",
loc.getLongitude(), loc.getLatitude()
);
Toast.makeText(LbsGeocodingActivity.this, message, Toast.LENGTH_LONG).show();
}
public void onProviderDisabled(String arg0) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
阅读本文了解详情http://www.javacodegeeks.com/2010/09/android-location-based-services.html
【讨论】:
没有这样的机制可以根据需要立即获取当前位置。由于您需要查询网络或 GPS 提供商,这可能需要一些时间才能真正获得位置。
一种方法是使用立即返回的 getLastKnownLocation。但是,此位置可能已过时。另一种方法是注册一个 PASSIVE_PROVIDER,通过它您可以获得位置修复,希望其他应用程序已请求位置。
【讨论】:
getLastKnwonLocation() 做了什么?它不是自己发出请求吗,它只是检查一些 other 应用程序是否已经更新了位置?我以为手机的 gps 会自动更新位置,getLastKnownLocation() 只会访问 GPS 最后获取的任何内容?你说它可能是stale,但它怎么可能是stale,如果它抓住了手机自己的GPS在说什么?