在安卓优先级队列中以串行方式运行作业



我想在串行队列中运行作业(等待第一个作业启动第二个(。我正在使用 android 优先级队列库,它允许您通过设置相同的组 ID 来串行运行作业,但它在我的情况下不起作用。

我在队列中添加了三个作业

jobManager.addJobInBackground(new FetchQuestionsJob(this((; 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

public class FetchQuestionsApi implements 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) {
}

尝试使用 .groupBy(FETCH_REQUESTS) 而不是 .setGroupId(FETCH_REQUESTS) 。在我的情况下,它工作正常。

最新更新