我即将在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
}
}
}
这段代码设置了一个带有按钮和文本视图的活动。在按钮上设置一个监听器,用于启动位置管理器。
我创建了一个名为MyLocationListener
的类,该类实现了LocationListener
接口,然后我重写了onLocationChanged()
方法,基本上告诉它第一次获取到的位置将被附加到文本视图中,然后移除位置管理器。
感谢那些提供帮助的人,我希望这对其他人有所帮助。
你应该尝试使用android.location.LocationManager.getLastKnownLocation
函数。
并且可以使用Location.getTime(utc time)
来检查返回的位置时间。
请求位置更新并创建一个LocationListener(参见LocationManager.requestLocationUpdates
)。您将定期收到有关准确度的信息。
在获得第一个更新之前,您可以(如发布的那样)使用LocationManager.getLastLocation()
并检查其时间戳和准确性。
警告 - 一些设备可能需要很长时间才能为您提供准确的读数,并且这是完全随机的。