gpt4 book ai didi

android - GcmTaskService 可以运行异步任务吗?

转载 作者:太空宇宙 更新时间:2023-11-03 13:16:39 26 4
gpt4 key购买 nike

我需要在 Android 应用程序的后台定期运行网络任务。

我最初打算使用 AlarmManager(不能使用 JobScheduler 因为它必须在 Lollipop 之前的设备上工作),但后来我遇到了GcmNetworkManager 似乎更易于使用并提供更简单的 API,如果设备连接到互联网,它会负责运行任务(也不需要使用广播接收器,所以类更少维护)。

我遇到的问题是我需要运行的任务由 3 个异步步骤组成,并且 GcmTaskService 似乎是为运行同步任务而创建的。

我已经对此进行了测试,发现我的异步任务在 GcmTaskService 中一直运行到最后(我的服务然后自行停止),但是我担心这可能更像是巧合因为我的异步任务非常快,而不是服务没有在 GcmTaskService 代码中停止(我试图查看代码,但它被混淆了,所以很难理解它是什么确实)。

有谁知道 GcmTaskService 是否实际上一直运行到扩展类停止它,或者它是否会在同步任务结束时停止?

最佳答案

经过一些调查和调试,我找到了答案。我将在此处对其进行描述,以便将来可能对其他人有所帮助。

正如我所怀疑的,GcmTaskService 在它需要运行的所有任务都完成时自行停止(这很有意义)。对此的证明是在这个方法上(在 GcmTaskService 类中):

private void zzdJ(String var1) {
Set var2 = this.zzaIU;
synchronized(this.zzaIU) {
this.zzaIU.remove(var1);
if(this.zzaIU.size() == 0) {
this.stopSelf(this.zzaIV);
}

}
}

此方法在任务完成后(也就是在 onRunTask() 返回后)从运行任务的线程中调用。

var1是开发者在创建任务时分配给任务的标签,zzaIU是这个服务需要运行的任务列表。因此,正如我们所见,已完成的任务已从列表中删除,如果没有更多任务可运行,则服务将停止。

可能的解决方案:

不过,有一种可能的解决方案可以在 GcmTaskService 中运行异步任务。为此,我们需要覆盖 onStartCommand() 方法,以防止 GcmTaskService 在另一个线程中启动任务。

代码如下所示:

private boolean taskRunning = false;

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
String intentAction = intent.getAction();
if (SERVICE_ACTION_EXECUTE_TASK.equals(intentAction)) {
taskRunning = true;

// Run your async tasks. Make sure to stop the service when they end.
} else if (SERVICE_ACTION_INITIALIZE.equals(intentAction)) {
// Initialize tasks if needed (most likely not needed if they are running asynchronously)

// If this step is not needed, make sure to stop the service if the tasks already run (this could be called after
// the service run all the tasks, and if we don't stop the service it'll stay running on the background without doing
// anything)
if (!taskRunning) {
stopSelf();
}
}

return START_NOT_STICKY;
}


@Override
public int onRunTask(TaskParams taskParams) {
// IMPORTANT: This method will not be run, since we have overridden the onStartCommand() to handle the tasks run ourselves,
// which was needed because our tasks are asynchronous

return GcmNetworkManager.RESULT_SUCCESS;
}

这仅在服务开发为运行 1 个任务时有效,如果需要运行多个任务,则需要使用列表而不是 taskRunning bool 值,并检查大小查看在停止服务之前是否需要运行更多任务(就像原始的 GcmTaskService 代码那样)。

尽管这是一个解决方案,但它不是面向 future 的,因为 GcmTaskService 上的代码可能会在未来的 Google Play 服务版本中发生根本性变化,在这种情况下,它可能会破坏此功能(不太可能,但可能)。所以我想我会使用 AlarmManager 而不是为了安全起见。

关于android - GcmTaskService 可以运行异步任务吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35028601/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com