问题
从GCM迁移到FCM时,我应该使用什么来代替PeriodicTask和OneOffTask? FCM包中有没有相应的东西?
背景
最近Google已弃用GCM并提供migration guide,但我找不到有关迁移PeriodicTasks和OneOffTasks的任何信息。
教程用play-services-gcm
向replace firebase-messaging
说,但我找不到任何与此package内的任务相似的内容,所以我想知道他们是否已完全退出他们还是实际上我们可以继续使用PeriodicTask / OneOffTasks?
答案 0 :(得分:3)
PeriodicTask和OneoffTask类(GcmNetworkManager组件的一部分)可以替换为Firebase Job Dispatcher,它是一个开源库,用于调度将在应用程序进程中执行的工作单元。它公开的服务端API镜像了框架的JobScheduler API,它与GcmNetworkManager略有不同。升级应该是一个相当容易的机械变化。
将以下内容添加到build.gradle
的依赖项部分:
implementation 'com.firebase:firebase-jobdispatcher:0.8.5'
改为使GcmTaskService
实施扩展JobService
。由此:
public class MyTaskService extends GcmTaskService {
@Override
public int onRunTask(TaskParams params) {
// Runs in its own thread
// ...
return RESULT_SUCCESS;
}
}
对此:
public class MyJobService extends JobService {
@Override
public boolean onStartJob(JobParameters job) {
// Runs on the main thread!
// ...
return false; // "Did we start any background work?"
}
@Override
public boolean onStopJob(JobParameters job) {
// Runs on the main thread!
// ...
return false; // "Should this job be retried?"
}
}
如果您不想管理自己的线程,可以利用库附带的SimpleJobService
:
public class MyJobService extends SimpleJobService {
@Override
public int onRunJob(JobParameters job) {
// Runs on its own thread!
// ...
return JobService.RESULT_SUCCESS;
}
}
确保调整清单。用以下内容替换以前的GcmTaskService
条目:
<service
android:exported="false"
android:name=".MyJobService">
<intent-filter>
<action android:name="com.firebase.jobdispatcher.ACTION_EXECUTE"/>
</intent-filter>
</service>
调度很简单:
// Create a new dispatcher using the Google Play driver.
FirebaseJobDispatcher dispatcher =
new FirebaseJobDispatcher(new GooglePlayDriver(context));
Job myJob = dispatcher.newJobBuilder()
// the JobService that will be called
.setService(MyJobService.class)
// uniquely identifies the job
.setTag("my-unique-tag")
// one-off job (only runs once unless a retry is requested)
.setRecurring(false)
// don't persist past a device reboot (requires RECEIVE_BOOT_COMPLETE)
.setLifetime(Lifetime.UNTIL_NEXT_BOOT)
// start between 0 and 60 seconds from now
.setTrigger(Trigger.executionWindow(0, 60))
// don't overwrite an existing job with the same tag
.setReplaceCurrent(false)
// retry with exponential backoff
.setRetryStrategy(RetryStrategy.DEFAULT_EXPONENTIAL)
// constraints that need to be satisfied for the job to run
.setConstraints(
// only run on an unmetered network
Constraint.ON_UNMETERED_NETWORK,
// only run when the device is charging
Constraint.DEVICE_CHARGING
)
.setExtras(myExtrasBundle)
.build();
dispatcher.mustSchedule(myJob);
查看repo以获取更多信息。