在onStartJob()
的{{1}}中注册广播接收器,然后返回JobService
而从不调用true
是一种好习惯吗?
类似这样的东西:
jobFinished()
某些背景:
当用户打开屏幕时,我需要做一些工作;当用户关闭屏幕时,我需要停止工作。我无法使用前台服务注册广播接收器。但是,这种解决方法是我设法完成这项工作的唯一方法。但是,我不确定这是否是使用 public boolean onStartJob(@NonNull JobParameters job) {
Log.e(JobFormActivity.TAG, "onStartJob() called");
if (screenBroadcast == null){
screenBroadcast = new ScreenBroadcast();
Log.e(JobFormActivity.TAG, "onStartJob() --> receiver is null, registering receiver");
IntentFilter screenStateFilter = new IntentFilter();
screenStateFilter.addAction(Intent.ACTION_SCREEN_ON);
screenStateFilter.addAction(Intent.ACTION_SCREEN_OFF);
registerReceiver(screenBroadcast, screenStateFilter);
}
return true;
}
public boolean onStopJob(@NonNull JobParameters job) {
Log.e(JobFormActivity.TAG, "onStopJob() called");
if(screenBroadcast != null) {
Log.e(JobFormActivity.TAG, "onStopJob() --> receiver is not null, unregistering receiver");
try {
unregisterReceiver(screenBroadcast);
screenBroadcast=null;
}catch (IllegalStateException e){
e.printStackTrace();
}
}
return false; // No more work to do
}
的好方法,还是应该将JobService
用于后台的小任务?