运行一个简单的后台任务的最简洁方法?

编程入门 行业动态 更新时间:2024-10-09 10:25:20
本文介绍了运行一个简单的后台任务的最简洁方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我已经看到了至少五个模式,通过这些模式,您可以在工作线程中运行一些代码.最简单的:

I've seen at least five patterns through which you can have some code to run in a worker thread. Most simple:

new Thread(new Runnable() { public void run() { // } }).start();

我们可以扩展AsyncTask;我们有AsyncTaskLoader和其他Loader用于数据,Service等等.

We can extend AsyncTask; we have AsyncTaskLoader and other Loaders for data, Services and so on.

我认为这些优点中的每一个都有一些优点,这些优点我不在这里讨论.我想知道的是:哪种是运行简单动作的最合适,最简洁的方法?

I assume each one of those has some advantages which I'm not discussing here. What I'm wondering is: which is the most appropriate, concise way to run a simple action?

定义简单:

  • 很短的动作,<1s;
  • 无需处理UI元素;
  • 单行命令或类似命令,因此用新类扩展AsyncTask似乎不合适;
  • 在Activity或Fragment中无需通知任务成功;
  • 无需显示进度;
  • 只需要具有某种return.
  • Quite short action, <1s;
  • No need to deal with UI elements;
  • One line command or such, so it looks inappropriate to extend AsyncTask with a new class;
  • No need to be notified about the success of the task in an Activity or Fragment;
  • No need to display progress;
  • Just need to have some kind of return.

我最初的想法是:

boolean myReturn; new Thread(new Runnable() { public void run() { myReturn = myExtensiveTask(); } }).start(); public boolean myExtensiveTask() { ... }

这是否正确(甚至可能)?应该怎么做?

Would this be correct (or even possible)? How should this be done?

推荐答案

使用 bolts

Using the bolts utility framework (used by Facebook and parse), it is simple as that:

Task.callInBackground(new Callable<MyReturnType>() { @Override public MyReturnType call() { MyReturnType obj = doWork(); return obj; } });

更多推荐

运行一个简单的后台任务的最简洁方法?

本文发布于:2023-10-12 16:20:01,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1485254.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:简洁   后台   简单   方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!