0
我在Android中苦苦掙扎着這個Looper。我有一個計時器,每分鐘運行一次。這會向用戶的位置發送一條消息到服務器。Android的TimerTask讓GPS定位凍結
private Looper looper;
public boolean getLocation(Context context, LocationResult result) {
locationResult = result;
lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
//exceptions will be thrown if provider is not permitted.
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
}
// don't start listeners if no provider is enabled
if (!gps_enabled)
return false;
if(Looper.myLooper() == null)
Looper.myLooper().prepare();
looper = Looper.myLooper();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListenerGps);
looper.loop();
return true;
}
LocationListener locationListenerGps = new LocationListener() {
public void onLocationChanged(Location location) {
looper.quit();
lm.removeUpdates(this);
locationResult.gotLocation(location); // broadcast location
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
第一次計時器啓動時,一切正常。第二次,計時器凍結,手機上的GPS圖標表示它有鎖,但不會消失。就好像Looper沒有循環來處理第二次消息,即使我告訴它循環。如果我每次都調用Looper.prepare(),第二次定時器執行,我得到的異常是每個線程只有一個Looper。
當然,這不應該這麼難!