![](/img/trans.png)
[英]Send arraylist of objects results to Activity back from IntentService
[英]How to get results from an IntentService back into an Activity?
我正在使用IntentService通過JSON處理與服務器的網絡通信。 JSON /服務器部分工作正常,但我無法將結果返回到需要的地方。 以下代碼顯示了我如何從onClick()內部啟動intent服務,然后讓服務更新一個全局變量以將結果傳遞回主活動。
public class GXActivity extends Activity {
private static final String TAG = "GXActivity";
@Override
public void onCreate(Bundle savedInstanceState) {
// === called when the activity is first created
Log.i(TAG, "GXActivity Created");
super.onCreate(savedInstanceState);
setContentView(R.layout.start);
View.OnClickListener handler = new View.OnClickListener() {
public void onClick(View v) {
// === set up an application context to hold a global variable
// === called user, to contain results from the intent service
GXApp appState = ((GXApp) getApplicationContext());
User user = new User(-1); // initialize user id to -1
appState.setUser(user);
// === next start an intent service to get JSON from the server;
// === this service updates the user global variable with
// === results from the JSON transaction
Intent intent = new Intent(this, GXIntentService.class);
startService(intent);
// === check app context for results from intent service
appState = ((GXApp) getApplicationContext());
if (appState.getUser().getId() != -1)...
}
}
}
}
我遇到的問題是,在onCreate()完成之后,才會調用解析JSON的intent服務,因此我正在尋找結果的代碼看不到未初始化的結果。
我應該做些什么,以便在檢查結果之前調用intent服務? 如果我將click偵聽器從onCreate()函數中拉出來會有用嗎? 是否有另一個/更好的結構代碼? 非常感謝。
您應該在活動中查看創建自己的ResultReceiver
子類。 ResultReceiver
實現了Parcelable
因此可以作為額外的Intent
從您的Activity
傳遞到您的Service
。
你需要做這樣的事情:
在您的活動類中實現ResultReceiver
的子類。 實現的關鍵方法是onReceiveResult()
。 這種方法為您提供與Bundle
結果數據可以用來傳遞你在你所擷取的任何信息Service
。 只需解壓縮您需要的數據並使用它來更新您的活動。
在您的活動中,創建自定義ResultReceiver
的新實例,並將其添加到用於啟動服務的Intent
。
在Service
的onStartCommand()
方法中,檢索在Intent
onStartCommand()
入的ResultReceiver
並將其存儲在本地成員變量中。
一旦您的Service
完成其工作,讓它在ResultReceiver上調用send()
,將您要發送的任何數據傳遞回Bundle
的活動。
這是一個非常有效的模式,意味着您不會將數據存儲在令人討厭的靜態變量中。
有很多方法可以在后台獲取結果(AsyncTask,將一個Activity綁定到一個服務......),但如果你想保留你的IntentService代碼,你可以簡單地:
1-在IntentService工作結束時發送廣播意圖(包含其擴展數據中的狀態)
2-在Activity中實現一個使用Intent數據的LocalBroadcastReceiver
這也是官方文檔中推薦的方法(如果你想保留你的IntentService):
https://developer.android.com/training/run-background-service/report-status.html
如果你需要做的只是從服務器獲取JSON而不鎖定UI線程,那么使用AsyncTask可能更簡單。
您可以使用Otto庫。 Otto是一個開源項目,旨在提供事件總線實現,以便組件可以發布和訂閱事件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.