【发布时间】:2010-06-07 19:44:55
【问题描述】:
编辑:我正在重写这个问题,因为我显然不清楚。
有时,Android 手机上的 GPS 服务需要很长时间才能得到修复。有时它很快,有时需要几个小时。我知道并接受这一点。
我有一个可以做很多事情的应用程序。它必须做的一件事是允许用户单击按钮将其当前坐标发送到服务器。我需要的是手机的坐标当用户点击按钮或在此后相当短的时间内。
因为我知道获得 GPS 定位不是即时的,而且我知道它可能需要几分钟或几小时(在此期间用户移动了很远的距离),所以我需要为此功能编写超时代码。对于此功能,在用户单击按钮后(例如)三分钟后上传用户的 GPS 位置是不可接受的。如果需要 45 秒就可以,如果需要 75 秒就不行。如果该功能未能足够快地获取位置,则可以向用户发出错误通知。
我需要一个功能来“获取 GPS 位置并将其发送到服务器,除非需要超过一分钟”。
我的原始代码如下。自从发布它以来,我已经改变了一些东西。我在 onStartCommand() 方法中添加了一个 Timer。我启动了一个 TimerTask,它会在 60 秒后调用我的 stop() 方法。在 onLocationChanged() 方法的开头,我取消了 TimerTask。
我的问题是:Timer 方案是实现此超时的好方法吗?有没有更好的办法?
原问题:
我正在编写一个 Android 应用程序,除其他外,它需要在用户要求时将当前 GPS 坐标发送到服务器。从上下文菜单中,我运行下面的服务。该服务是一个 LocationListener 并从 LocationManager 请求更新。当它获得一个位置 (onLocationChanged()) 时,它会将自己作为侦听器移除并将坐标发送到服务器。所有这些都有效。
但是,如果 GPS 坐标无法快速获得,我的服务将继续运行,直到获得一些坐标。它通过进度对话框支撑 UI,这很烦人。更糟糕的是,如果用户在启动服务后移动了,第一个 GPS 坐标可能是错误的,应用程序会向服务器发送错误数据。
我需要服务超时。有什么好的方法吗?我对线程不是很有经验。我想我可以在 onStartCommand() 方法中运行一个 Runnable,它会以某种方式倒计时 30 秒,然后,如果还没有 GPS 结果,请调用我的服务的 stop() 方法。这听起来是不是最好的方法?
或者,是否可以判断 GPS 是否无法定位?我该怎么做呢?
编辑:为了进一步澄清,我正在寻找在一段时间后“放弃”获取位置的最佳方式。
public class AddCurrentLocation extends Service implements LocationListener {
Application app;
LocationManager mLocManager;
ProgressDialog mDialog;
@Override
public int onStartCommand(Intent intent, int arg0, int arg1) {
app = getApplication();
// show progress dialog
if (app.getScreen() != null) {
mDialog = ProgressDialog.show(app.getScreen(), "", "Adding Location. Please wait...", true);
}
// find GPS service and start listening
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
mLocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
String bestProvider = mLocManager.getBestProvider(criteria, true);
mLocManager.requestLocationUpdates(bestProvider, 2000, 0, this);
return START_NOT_STICKY;
}
private void stop() {
mLocManager.removeUpdates(this);
if (mDialog != null) {
mDialog.dismiss();
}
stopSelf();
}
@Override
public void onLocationChanged(Location location) {
// done with GPS stop listening
mLocManager.removeUpdates(this);
sendLocation(location); // method to send info to server
stop();
}
// other required methods and sendLocation() ...
}
【问题讨论】:
-
那么你到底做了什么来解决这个问题?我有同样的问题。