android - 在队列中调用 Asynctask

标签 android android-asynctask

我正在开发一个应用程序并想将一些数据发送到服务器。当我发送到服务器的更新是周期性的时,我能够将数据发送到服务器。

但现在它取决于用户交互。我必须向服务器发送 1 个或多个调用。我不能跳过和省略对服务器的任何调用。假设有以下情况:

案例:

假设我点击了一个按钮,我启动了一个将一些数据放在服务器上的异步任务,假设它需要 5 到 6 秒。但是如果用户多次按下按钮,我想触发多个 asyntask 。假设他连续按下按钮 7 次。所以7个AsyncTask必须在一个队列中依次运行。

我听说过 schedular 和所有其他的,但我无法理解如何使用 asynctask 来处理它们。

可能的解决方案: 我可以禁用按钮直到并且除非第一个异步任务未完成,但我真的不想这样做,因为在要求和需要下我必须将异步任务称为用户按下按钮多次。

请帮助我,任何源代码将不胜感激。

注意:有了 asynctask,我无需更新 UI。

更新:

根据我的需要,我想将具有特定数据的异步任务排队,并且它必须在上一个任务完成时自动运行,如果用户退出应用程序,它应该继续运行,直到并且除非它完成所有排队的异步任务的执行。

最佳答案

Let suppose he presses the button 7 time in a row. so the 7 AsyncTask must run in a queue one after an other.

根据您的应用程序的目标 API,您可能不需要做任何特别的事情。 Official documentation reads:

Order of execution

When first introduced, AsyncTasks were executed serially on a single background thread. Starting with DONUT, this was changed to a pool of threads allowing multiple tasks to operate in parallel. Starting with HONEYCOMB, tasks are executed on a single thread to avoid common application errors caused by parallel execution

因此从 Android 3.0 开始,execute() 就是您真正需要的,这意味着除非您支持该平台的旧版本,否则您应该默认看到串行执行。

或者,您可以放弃 AsyncTask,转而使用一个接一个执行的 IntentService。

关于android - 在队列中调用 Asynctask,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46808514/

相关文章:

android - 是否有 ADB 命令来切换允许模拟位置?

Android Google MAPS API 2 JSON 路由

java - 实现静态菜单

Android:尝试设置到 ImageView 时联系人照片像素化

android - 在 Android Gradle 构建中,如何从包含的 jar 文件中排除依赖项?

Android - 更改 Activity 时的多线程问题

java - 从可绘制对象设置背景墙纸

android - AndroidManifest 中的多个 ComponentDiscoveryService --> 合并冲突

android - `doInBackground()` 不接受类型为 void 的 `AsyncTask`?

android - 在 Android 的 doinbackground() 中执行 UI 任务