相信我,我在大型企業項目中嘗試了很多第三方方法(服務總線,觀察...),結果證明原生Android機制是最快和最健壯的方法,因爲他們利用框架的好處。
這就是爲什麼我會建議使用LocalBroadcastManager與BroadcastReceiver一起使用。在你的活動(或你的罐頭事件做這個每個片段!)註冊在onStart
和取消註冊在專用的接收器。
在您的服務中使用LocalBroadcastManager與所有潛在訂戶進行通信。
例子:
public class YourActivity extends Activity{
private BroadcastReceiver receiver = new BroadcastReceiver(){
@Override
public void onReceive(Context context, Intent intent) {
//...do the stuff you need to do depending on the received broadcas
}
};
private IntentFilter filter = new IntentFilter(UploadService.INTENT_ACTION_UPLOAD);
protected onStart(){
LocalBroadcastManager.getInstance(this).registerReceiver(receiver, filter);
}
protected onPause(){
LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver);
}
}
public class UploadService extends IntentService{
public static final String INTENT_ACTION_UPLOAD = "com.your.package.INTENT_ACTION_UPLOAD";
public onHandleIntent(){
//upload
LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(INTENT_ACTION_UPLOAD));
}
}
在廣播接收器的onReceive
那麼你可以做你需要根據接收到的廣播做的東西。如果您需要更多的差異化,你可以在你的服務使用不同的動作或演員,比如:
...send(new Intent(INTENT_ACTION_SOMETHING_ELSE));
或
send(new Intent(...).putExtra(WAS_SUCCESSFUL, false));
send(new Intent(...).putExtra(DOWNLOADED_CONTENT, downloadedStuff);
使用LocalBroadcastManager時,沒有安全隱患。 http://developer.android.com/reference/android/support/v4/content/LocalBroadcastManager.html – a11n 2014-12-02 15:59:17