我正在尝试在后台服务中运行位置更新。该服务正在运行自己的工作线程,它已经在做很多其他事情,比如套接字通信。我希望它也能处理位置更新,但这似乎只适用于一项活动。据我所知,这是由于工作线程上缺少消息循环。我想我需要在Looper.prepare()
某个地方使用,但也许我需要另一个线程来处理位置请求?我似乎无法让模拟器响应任何地理修复事件,所以我一定做错了什么。
下面是服务代码,去掉了所有不相关的部分。
public class MyService extends Service implements LocationListener {
private Thread runner;
private volatile boolean keepRunning;
private LocationManager locationManager = null;
@Override
public void onCreate() {
keepRunning = true;
runner = new Thread(null, new Runnable() {
public void run() { workerLoop(); }
});
runner.start();
startGps();
}
@Override
public void onDestroy() {
keepRunning = false;
runner.interrupt();
}
private void workerLoop() {
//Looper.myLooper(); How does this work??
//Looper.prepare();
// Main worker loop for the service
while (keepRunning) {
try {
if (commandQueue.notEmpty()) {
executeJob();
} else {
Thread.sleep(1000);
}
} catch (Exception e) {
}
}
stopGps();
}
public void onLocationChanged(Location location) {
// Doing something with the position...
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
private void startGps() {
if (locationManager == null)
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (locationManager != null) {
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(true);
criteria.setCostAllowed(false);
criteria.setSpeedRequired(true);
String provider = locationManager.getBestProvider(criteria, true);
if (provider != null)
locationManager.requestLocationUpdates(provider, 10, 5, (LocationListener) this);
}
}
private void stopGps() {
if (locationManager != null)
locationManager.removeUpdates((LocationListener) this);
locationManager = null;
}
}