EventBus看起來很有前途。
另一種選擇是使用意圖和廣播接收器。
例子:
在MainActivity.java:
@Override
public void onResume() {
super.onResume();
IntentFilter iFilter= new IntentFilter("updatelocation");
iFilter.addAction("someOtherAction"); //if you want to add other actions to filter
this.registerReceiver(br, iFilter);
}
@Override
public void onPause() {
this.unregisterReceiver(br);
super.onPause();
}
private BroadcastReceiver br = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals("UpdateLocation")){
//set these to member variables for later retrieval
double lat = intent.getExtras().getDouble("lat");
double lon = intent.getExtras().getDouble("lon");
this.runOnUiThread(mUpdateLocation);
}
}
};
private final Runnable mUpdateLocation = new Runnable() {
@Override
public void run() {
//TODO: Update your UI here
}
};
然後,在你LocationWorker類,當位置改變發送意圖。確保您在LocationWorker類中具有對應用程序上下文的引用。
看到這個職位:passing GPS coordinates to activity
//Make sure you have a reference to the application context
Intent updateLocation= new Intent(context, MainActivity.class);
updateLocation.setAction("UpdateLocation");
updateLocation.putExtra("lon", xLocation.getLongitude());
updateLocation.putExtra("lat", xLocation.getLatitude());
context.sendBroadcast(i);
好主意,儘管如果我使用描述的方法來獲取某個位置,我已經有了一個OnConnected回調方法。 所以,如果我理解正確,我需要的只是從OnConnected回調調用異步任務? (在這種情況下,異步任務準備好所有數據並將其返回到UI線程)。如果是,只需在MainActivity中實現一個OnConnected回調? – 2015-02-24 19:28:44
回調是一個好方法是的,我同意。雖然你知道有很多選擇:) – 2015-02-24 19:31:07
等待數據是否與回調一起來,沒有必要在異步中準備它,只用於可能會阻止用戶界面的異步 – 2015-02-24 19:33:18