我正试图按照本教程为我的项目实现Job Dispatcherhttps://github.com/googlearchive/firebase-jobdispatcher-android但不知道如何安排工作,或者它不起作用。
我想在每周六展示挑战;从firebase数据库获得挑战。
我尝试了下面的代码,但它不起作用。
有人能给我指路吗?有什么文章/文档可以帮助理解这个概念吗?
挑战。服务
public class ChallengeService extends JobService {
public static final String TAG = "ChallengeService";
@Override
public boolean onStartJob(final JobParameters job) {
Log.d(TAG, "completeJob: " + "jobStarted");
new Thread(new Runnable() {
@Override
public void run() {
codeYouWantToRun(job);
}
}).start();
return true;
}
@Override
public boolean onStopJob(JobParameters job) {
return false;
}
public void codeYouWantToRun(final JobParameters parameters) {
try {
Log.d(TAG, "completeJob: " + "jobStarted");
//This task takes 2 seconds to complete.
Thread.sleep(2000);
Calendar mCalendar = Calendar.getInstance();
final String mWeekofyear = String.valueOf(getWeekOfYear(mCalendar));
Log.d("ChallengeService", "mWeekofyear:: " + mWeekofyear);
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference().child("Challenges").child(mWeekofyear);
myRef.keepSynced(true);
myRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String mChallengeOfWeek = dataSnapshot.getValue(Challenge.class).getName();
Log.d(TAG, "mChallengeOfWeek: " + mChallengeOfWeek);
}
@Override
public void onCancelled(DatabaseError error) {
Log.w(TAG, "Failed to read value.", error.toException());
}
});
Log.d(TAG, "completeJob: " + "jobFinished");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
jobFinished(parameters, true);
}
}
private int getWeekOfYear(Calendar mCalendar) {
return mCalendar.get(Calendar.WEEK_OF_YEAR);
}
}
主片段
if (mDayName.equals("Saturday")) {
scheduleJob(this);
}
private static void scheduleJob(Context context) {
FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(context));
Job job = createJob(dispatcher);
dispatcher.mustSchedule(job);
Log.d(TAG,"job::"+job);
}
private static Job createJob(FirebaseJobDispatcher dispatcher) {
Job job = dispatcher.newJobBuilder()
.setLifetime(Lifetime.FOREVER)
.setService(ChallengeService.class)
.setTag("UniqueTagForYourJob")
.setReplaceCurrent(false)
.setRecurring(true)
.setTrigger(Trigger.executionWindow(30, 60))
.setRetryStrategy(RetryStrategy.DEFAULT_LINEAR)
.setConstraints(Constraint.ON_ANY_NETWORK, Constraint.DEVICE_CHARGING)
.build();
return job;
}
您是否将ChallengeService添加到清单文件并通过android.permission.BIND_JOB_SERVICE权限对其进行保护?
<service android:name="ChallengeService"
android:permission="android.permission.BIND_JOB_SERVICE" >
...
</service>
JobService也不推荐使用,您可以使用Android Jetpack WorkManager。
这是入门指南https://developer.android.com/topic/libraries/architecture/workmanager/basics