我尝试使用WorkManager实现计时器。
“定时器按钮被击中”是出现在日志猫,但没有任何来自工人。我做错了什么?
这是我的viewmodel类:
public class MainViewModel extends ViewModel {
public static final String LOG_TAG = "MainActivity";
private final WorkManager workManager;
public MainViewModel(WorkManager workManager) {
this.workManager = workManager;
}
public void count() {
Log.d(LOG_TAG, "Timer button was hit!");
OneTimeWorkRequest request = new OneTimeWorkRequest.Builder(MainWorker.class).build();
workManager.beginUniqueWork("count-work", ExistingWorkPolicy.APPEND, request).enqueue();
}
}
这是我的工人。从这里看logcat里什么都没有。我不知道为什么。
public class MainWorker extends Worker {
public MainWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
super(context, workerParams);
Log.d(MainViewModel.LOG_TAG, "Created");
}
@NonNull
@Override
public Result doWork() {
Log.d(MainViewModel.LOG_TAG, "Work start");
return Result.success();
}
}
这是我的活动:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MainViewModel viewModel = new MainViewModel(WorkManager.getInstance(this));
ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
binding.setMainViewModel(viewModel);
}
}
1条答案
按热度按时间kx5bkwkv1#
viewmodels没有像您那样初始化。如果必须将某些内容传递给viewmodel构造函数,则应该考虑使用
ViewModelProvider.Factory()
.您可以创建自己的viewmodelprovider.factory()
参考这个,https://medium.com/koderlabs/viewmodel-with-viewmodelprovider-factory-the-creator-of-viewmodel-8fabfec1aa4f#:~:text=和%20it%20is%20因为%20it%20将%20创建%20your%20viewmodel。