我即将在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
}
}
}
Run Code Online (Sandbox Code Playgroud)
这将设置一个带有按钮和文本视图的活动。在启动位置管理器的按钮上设置侦听器。
我已经设置了一个类,MyLocationListener它实现了LocationListener,然后我重写该onLocationChanged()方法,基本上告诉它它获取的第一个位置将附加到文本视图,然后删除位置管理器。
感谢那些提供帮助的人,我希望这对其他人有用。
| 归档时间: |
|
| 查看次数: |
2742 次 |
| 最近记录: |