1

我正在尝试实现下面的库以适应方向变化: https ://github.com/yigit/android-priority-jobqueue

这是我的配置:

 Configuration config = new Configuration.Builder(getApplication())
                .consumerKeepAlive(45)
                .maxConsumerCount(3)
                .minConsumerCount(1)
                .build();
        return new JobManager(config);

这是我的示例工作:

public class CounterJob extends Job {
    private int countTo;

    protected CounterJob(int countTo, Params params) {
        super(params);
        this.countTo = countTo;
    }

    @Override
    public void onAdded() {
        Log.e("counting to", "" + countTo);
    }

    @Override
    public void onRun() throws Throwable {
        Log.e("running job", "" + countTo);
        int total = 0;
        for (int i = 0; i < countTo; i++) {
            total += i;
        }

        Log.e("total", "" + total);
    }

    @Override
    protected void onCancel(int cancelReason, @Nullable Throwable throwable) {

    }

    @Override
    protected RetryConstraint shouldReRunOnThrowable(@NonNull Throwable throwable, int runCount, int maxRunCount) {
        return null;
    }
}

这是一个用于计数的示例控制器:

public class CounterController {
    private JobManager mJobManager;

    public CounterController(JobManager jobManager) {
        this.mJobManager = jobManager;
    }

    public void count(int countTo) {
        mJobManager.addJobInBackground(new CounterJob(countTo, new Params(1).requireNetwork().persist()));
    }
}

我打电话给:

@Override
protected void onResume() {
    super.onResume();
    mCounterController.count(1000000000);
}

当我旋转设备时,同样的工作再次开始。因此,如果我没记错的话,如果我正在进行网络调用,那么当方向改变时,它会复制请求。

我认为我的实施存在问题。我试图在库页面中作为示例实现。有什么建议么?谢谢。

4

2 回答 2

2

我猜你在轮换时正在重新创建工作,所以你最终会得到 2 个工作。当活动更改配置(又名轮换)时,您不应将其排入队列两次。

于 2016-11-08T07:07:50.463 回答
0

I found the solution : you can give a group ID then a ID to the job so it won t be running again. Here is the javadoc :

/////// for the group ///////

/** * Sets the group id. Jobs in the same group are guaranteed to execute sequentially. * @param groupId which group this job belongs (can be null of course) * @return this */

public Params groupBy(String groupId) {
    this.groupId = groupId;
    return this;
}

////////for the ID ////////

/** * Sets the single instance id. If there is another Job with the same single id queued and * not yet running, this Job will get {@link Job#onCancel(int, Throwable)} called immediately after * {@link Job#onAdded()} and only the previous Job will run. That is, {@link Job#onRun()} * will only be called once. *

If no group id was set, one will be set automatically. * @param singleId which single instance group this job belongs to (can be null of course) * @return this */

public Params singleInstanceBy(String singleId) {
    this.singleId = singleId;
    return this;
}

You set it in the constructor methods

  public Step1Jobs() {
        super(new Params(Priority.LOW).requireNetwork().groupBy(STEPS).singleInstanceBy(STEP1));
    }
于 2017-09-05T13:43:06.060 回答