[英]How can I obtain the current GPS location?
我即将在Android中构建一个应用程序,它将作为路上员工的时钟卡。
在工作开始时,用户将点击一个按钮,该按钮将记录GPS位置和当前时间(从而验证他在给定时间应该在哪里),并在作业结束时再次记录时间和GPS位置。
所以我认为这很容易,除了我找不到拉取当前位置数据的方法。 我能找到的最近的是onLocationChanged
,这意味着我无法获得固定的GPS读数。 我知道必须有可能做到这一点,但找不到如何实现它的工作示例。
经过一番研究后,我想出了这个:
public class UseGps extends Activity
{
Button gps_button;
TextView gps_text;
LocationManager mlocManager;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
gps_button = (Button) findViewById(R.id.GPSButton);
gps_text = (TextView) findViewById(R.id.GPSText);
gps_button.setOnClickListener(new OnClickListener() {
public void onClick(View viewParam) {
gps_text.append("\n\nSearching for current location. Please hold...");
gps_button.setEnabled(false);
mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
}
});
}
/* Class My Location Listener */
public class MyLocationListener implements LocationListener
{
@Override
public void onLocationChanged(Location loc)
{
double lon = loc.getLatitude();
double lat = loc.getLongitude();
gps_text.append("\nLongitude: "+lon+" - Latitude: "+lat);
UseGps.this.mlocManager.removeUpdates(this);
gps_button.setEnabled(true);
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
}
这会使用按钮和textview设置活动。 在启动位置管理器的按钮上设置监听器。
我已经设置了一个实现LocationListener
的类MyLocationListener
,然后我重写了onLocationChanged()
方法,基本上告诉它它获取的第一个位置附加到textview然后它删除了位置管理器。
感谢那些帮助过的人,我希望这对其他人有用。
你应该尝试android.location.LocationManager.getLastKnownLocation
并使用Location.getTime(utc time)
检查返回的位置的Location.getTime(utc time)
。
请求位置更新并创建LocationListener(请参阅LocationManager.requestLocationUpdates
)。 您将收到有关准确性信息的定期更新。
在您获得第一次更新之前,您可以(如已发布)使用LocationManager.getLastLocation()
并检查其时间戳和准确性。
警告 - 一些设备扫描需要永远,以获得准确的读数,它是完全随机的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.