我想在串行隊列中運行作業(等待第一個作業從第二個作業開始)。我正在使用android優先級隊列庫,它允許您通過設置相同的組ID來串行運行作業,但它不適用於我的情況。在android優先級隊列中以串行方式運行作業
我在隊列中增加了三個工作
jobManager.addJobInBackground(新FetchQuestionsJob(本)); jobManager.addJobInBackground(new FetchUsersJob(this)); jobManager.addJobInBackground(new FetchTeamsJob(this));
我所有的三個工作都類似於這個班,但所有的工作同時運行。我從FetchUsersJob/FetchTeamsJob獲得來自FetchQuestionsJob的響應。
public class FetchQuestionsJob extends Job{
Context context;
public FetchQuestionsJob(Context context){
super(new Params(9).requireNetwork().setGroupId(FETCH_REQUESTS));
this.context = context;
}
@Override
public void onAdded() {
}
@Override
public void onRun() throws Throwable {
new FetchQuestionsApi(context);
}
@Override
protected void onCancel(int cancelReason, @Nullable Throwable throwable) {
}
@Override
protected RetryConstraint shouldReRunOnThrowable(@NonNull Throwable throwable, int runCount, int maxRunCount) {
return null;
}
FetchQuestionApi
公共類FetchQuestionsApi實現IDataReceiveListener {
VolleyNetworkController networkController;
Context context;
Realm realm;
public FetchQuestionsApi(Context context) {
this.context = context;
networkController = new VolleyNetworkController(context);
networkController.getRequest(URL_GET_QUESTIONS, null, null, this);
}
@Override
public void onDataReceived(JSONObject jsonObject) {
try {
if (jsonObject.getBoolean(RESPONSE_SUCCESS)) {
JSONArray data = jsonObject.getJSONArray("Data");
Gson gson = new Gson();
Question[] question = gson.fromJson(data.toString(), Question[].class);
realm = Realm.getDefaultInstance();
realm.beginTransaction();
realm.copyToRealmOrUpdate(Arrays.asList(question));
realm.commitTransaction();
Question specificCountry = realm.where(Question.class).findFirst();
String id = specificCountry.getId();
Log.d("", jsonObject.toString());
AppController.getInstance().getJobManager().addJobInBackground(new FetchUsersJob(context));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void OnError(String message) {
}
有幾種不同的方法來處理這個問題。如果您需要這些請求按順序運行。你不能讓他們工作,但只是pojos,併爲每個有爭議的pojos做出同步網絡請求。如果線程池中有一個打開的插槽,JobManager按其設計將並行運行作業。 – kingargyle