Dar*_*tel 4 gps android location
我已经看到了各种代码片段,它们可以找到来自onlocationupdate()或onstatusChanged()等各种方法的坐标....我想要的是一个简单的代码,点击按钮即可获取当前的GPS坐标...
gna*_*nac 12
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());
}
});
Run Code Online (Sandbox Code Playgroud)
当然,您还需要在清单xml文件中使用位置管理器服务注册您的活动:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Run Code Online (Sandbox Code Playgroud)
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) {
}
}
Run Code Online (Sandbox Code Playgroud)
阅读详细信息http://www.javacodegeeks.com/2010/09/android-location-based-services.html
| 归档时间: |
|
| 查看次数: |
29298 次 |
| 最近记录: |