1)你在想这整件事!
你的方法比它必须的要复杂得多!出于某种原因,其他答案都没有指出这一点,但GcmNetworkManager
已经做了你想要实现的一切!你不需要自己实现任何东西。
2)实现您正在尝试做的事情的最佳方式。
您似乎没有意识到GcmNetworkManager
已经以最省电的方式通过自动重试等方式对调用进行批处理,并且它还可以在设备启动期间保留任务,并且可以确保它们在电池高效且您的应用程序需要时立即执行。
每当您有数据可以保存计划时,OneOffTask
就像这样:
final OneoffTask task = new OneoffTask.Builder()
// The Service which executes the task.
.setService(MyTaskService.class)
// A tag which identifies the task
.setTag(TASK_TAG)
// Sets a time frame for the execution of this task in seconds.
// This specifically means that the task can either be
// executed right now, or must have executed at the lastest in one hour.
.setExecutionWindow(0L, 3600L)
// Task is persisted on the disk, even across boots
.setPersisted(true)
// Unmetered connection required for task
.setRequiredNetwork(Task.NETWORK_STATE_UNMETERED)
// Attach data to the task in the form of a Bundle
.setExtras(dataBundle)
// If you set this to true and this task already exists
// (just depends on the tag set above) then the old task
// will be overwritten with this one.
.setUpdateCurrent(true)
// Sets if this task should only be executed when the device is charging
.setRequiresCharging(false)
.build();
mGcmNetworkManager.schedule(task);
这将做你想做的一切:
- 任务将被持久化在磁盘上
- 任务将以批量和电池高效的方式执行,最好通过 Wifi
- 您将具有可配置的自动重试和电池高效的退避模式
- 任务将在您可以指定的时间窗口内执行。
我建议初学者阅读本文以了解有关GcmNetworkManager
.
所以总结一下:
您真正需要做的就是在一个Service
扩展中实现您的网络调用,GcmTaskService
然后当您需要执行这样的网络调用时,您安排一个OneOffTask
,其他一切都会为您处理!
当然,您不需要OneOffTask.Builder
像我在上面所做的那样调用每个设置器 - 我这样做只是为了向您展示您拥有的所有选项。在大多数情况下,调度任务看起来就像这样:
mGcmNetworkManager.schedule(new OneoffTask.Builder()
.setService(MyTaskService.class)
.setTag(TASK_TAG)
.setExecutionWindow(0L, 300L)
.setPersisted(true)
.setExtras(bundle)
.build());
如果你把它放在一个辅助方法中,或者更好地为你需要做的所有不同任务创建工厂方法,而不是你试图做的所有事情都应该归结为几行代码!
顺便说一句:是的, an在一个 worker 中一个接一个地依次IntentService
处理。你可以在这里查看相关的实现。它实际上非常简单而且非常直接。Intent
Thread