Android-Priority-Jobqueue Survive Orientation Change

Android-Priority-Jobqueue Surviving Orientation Change

我正在尝试实现下面的库以适应方向变化: 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);
}

当我旋转设备时,相同的作业再次开始。所以如果我没记错的话,如果我正在进行网络呼叫,当方向改变时它会重复请求。

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

我猜你是在轮换时重新创建工作,所以你最终得到了 2 个工作。当 activity 更改配置 (a.k.a.rotation).

时,你不应该将它入队两次

我找到了解决方案:您可以给一个组 ID,然后给作业一个 ID,这样它就不会再 运行 了。这是 javadoc:

/////// 对于群组 ///////

/** * 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;
}

////////对于 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;
}

你在构造方法中设置它

  public Step1Jobs() {
        super(new Params(Priority.LOW).requireNetwork().groupBy(STEPS).singleInstanceBy(STEP1));
    }