问题
从GCM迁移到FCM时,应该使用什么来代替PeriodictAsk和OneOfftask?FCM包装中有同等的吗?
背景
最近google已经否决了gcm,他们提供了migration guide,但是我在那里找不到任何关于迁移周期任务和oneofftasks的信息。
教程中说要使用play-services-gcm执行replacefirebase-messaging,但我找不到与此package中的任务类似的内容,所以我想知道他们是否完全放弃了这些任务,或者我们是否可以继续使用periodictask/oneofftasks?

最佳答案

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了解更多信息。

关于android - 从GCM迁移到FCM后的PeriodicTask和OneoffTask,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49797085/

10-08 20:42