我打算在 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 的 Activity 。在启动位置管理器的按钮上设置监听器。
我设置了一个类,MyLocationListener
,它实现了LocationListener
,然后我覆盖了onLocationChanged()
方法,基本上就是告诉它它获得的第一个位置附加到 TextView ,然后删除位置管理器。
感谢那些提供帮助的人,我希望这对其他人有用。
关于java - 如何获取当前的 GPS 位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3428188/