WorkManager的onStopped()方法调用了两次

时间:2018-11-06 08:00:37

标签: android android-workmanager

我在项目中实现了WorkManager。在完成doWork()中的任务后,我打电话给stop(true);,并向onStopped()中的另一个活动发送广播。一切工作正常,但问题是onStopped()被称为两次(我已经通过应用断点进行了测试)。结果,BroadcastReceiver也被两次调用。

我知道WorkManager处于alpha阶段。但是我实际上不确定这是一个错误还是做错了什么。请帮忙。代码如下:

public Result doWork() {

    startGettingData();

    stop(true);

    return Result.SUCCESS;
}

@Override
public void onStopped(boolean cancelled) {
    super.onStopped(cancelled);

    Intent intent=new Intent(SERVER_SYNC_BROADCAST);
    intent.putExtra(SYNC_RESULT_MESSAGE,responseCodes);
    LocalBroadcastManager.getInstance(MyApplication.getContext()
            .getApplicationContext())
            .sendBroadcast(intent);

}

仅从活动的onCreate()调用一次:

WorkUtil.startSyncing(SyncWorker.class);

WorkUtil.java

public class WorkUtil {

private static WorkManager mWorkManager;

public static WorkUtil workUtil;

private WorkUtil() {

     mWorkManager = WorkManager.getInstance();

}

public static WorkUtil getInstance() {

    if(workUtil == null) {
        workUtil = new WorkUtil();
    }

    return workUtil;

}

public static void startSyncing(Class workerClass) {

    Constraints constraints = new Constraints.Builder().build();

    OneTimeWorkRequest someWork = new OneTimeWorkRequest.Builder(workerClass)
            .setConstraints(constraints)
            .build();
    OneTimeWorkRequest oneTimeWorkRequest = someWork;
    mWorkManager.enqueue(oneTimeWorkRequest);

}

public static void cancelAllWork() {
    mWorkManager.cancelAllWork();
}


}

1 个答案:

答案 0 :(得分:1)

如果我对您的理解正确,那么您想在工作完成后发送广播。

您不应该在onStopped内部进行操作,而是将其移动到doWork上:

public Result doWork() {

  startGettingData(); // this method should be synchronous

  Intent intent=new Intent(SERVER_SYNC_BROADCAST);
  intent.putExtra(SYNC_RESULT_MESSAGE,responseCodes);
  LocalBroadcastManager.getInstance(MyApplication.getContext()
        .getApplicationContext())
        .sendBroadcast(intent);

  return Result.SUCCESS;
}

onStopped方法并不是要在工作完成时调用,而是在停止或取消时调用。

Source