我对此并不陌生,我已经实现了一个从 firebase 作业调度 API 的官方仓库引用的演示。
我想每 2 分钟运行一次特定任务,然后调用 Firebase 并从那里获取一个值并更新我的 TextView。
发生的事情是几次我等了 5 分钟但没有被调用,我调试了应用程序,我发现它onStartJob()
没有被调用。
很多时候它只调用了一次然后停止并且再也没有调用过。
这是代码:
设备空间服务
public class DeviceSpaceService extends JobService {
private static final String TAG = "DeviceSpaceService";
private int val = 0;
@Override
public boolean onStartJob(final JobParameters job) {
Log.e(TAG, "onStartJob() called with: job = [" + job + "]");
// if (Build.VERSION.SDK_INT >= 18)
// Log.e("DEVICE_SPACE",
// "Free space is " +
// (statFs.getAvailableBlocksLong() * statFs.getBlockSizeLong() / 1024) + " Kb"
// );
new Thread(new Runnable() {
@Override
public void run() {
complteJob(job);
}
}).start();
return true;
}
private void complteJob(JobParameters job) {
if (val == 10) {
jobFinished(job, false);
return;
}
Home.setAndSend(String.valueOf(val));
val++;
Log.e(TAG, "complteJob() called with: job = [" + val + "]");
}
@Override
public boolean onStopJob(JobParameters job) {
Log.e(TAG, "onStopJob() called with: job = [" + job + "]");
return false;
}
}
家庭活动
public class Home extends AppCompatActivity {
static TextView tvMain;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
tvMain = (TextView) findViewById(R.id.tv_main);
//Added dispatcher object as it is must to diapatch the job declared.
FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(this));
Job job = dispatcher.newJobBuilder().setLifetime(Lifetime.UNTIL_NEXT_BOOT)
.setService(DeviceSpaceService.class).setTag("DeviceSpaceCheck").setRecurring(true).setReplaceCurrent(false)
.setTrigger(Trigger.executionWindow(0,120)).build();
dispatcher.mustSchedule(job);
}
public static void setAndSend(String val) {
// Write a message to the database
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("message" + val);
myRef.setValue("Hello, World!" + val);
myRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (tvMain != null)
tvMain.setText(dataSnapshot.getValue().toString());
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}