java任务即使在满足约束后也会排队

ykejflvf  于 2021-07-07  发布在  Java
关注(0)|答案(0)|浏览(221)

我对一个简单的项目有点小问题。
我在做什么
我正在设置setrequirescharging约束,因此如果满足该约束,则任务应该运行。
问题是什么
因此,当我手动禁用计费(创建约束)时,任务将进入队列,但在启用计费后,任务不会运行。
请帮帮我。这是我的密码。

public class MainActivity extends AppCompatActivity {

FloatingActionButton fab;
TextView status;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

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

    final OneTimeWorkRequest oneTimeWorkRequest = new
            OneTimeWorkRequest.Builder(DemoWorker.class)
            .setConstraints(constraints).build();

    status = (TextView) findViewById(R.id.status);

    fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            WorkManager.getInstance().enqueue(oneTimeWorkRequest);
        }
    });

    WorkManager.getInstance()
            .getWorkInfoByIdLiveData(oneTimeWorkRequest.getId()).observe(this, new Observer<WorkInfo>() {
        @Override
        public void onChanged(WorkInfo workInfo) {
            // this workinfo contains our status
            // we can add validation to avoid null point exception

            if (workInfo!=null){

                status.setText(workInfo.getState().name());

            }
        }
    });
}

}
以及扩展worker类的自定义类。

public class DemoWorker extends Worker {

public DemoWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
    super(context, workerParams);
}

@NonNull
@Override
public Result doWork() {

    for (int i=0; i<100000; i++) {

        Log.i("TAG", "doWork: count is  " + i);
    }

    return Result.success();
}

}

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题