运行一个简单的后台任务的最简洁方法? [英] Most concise way to run a simple background task?
问题描述
我已经看到了至少五个模式,通过这些模式,您可以在工作线程中运行一些代码.最简单的:
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 Loader
s for data, Service
s 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
orFragment
; - 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
实用程序框架(由Facebook和parse.com使用),就这么简单:
Using the bolts
utility framework (used by Facebook and parse.com), it is simple as that:
Task.callInBackground(new Callable<MyReturnType>() {
@Override
public MyReturnType call() {
MyReturnType obj = doWork();
return obj;
}
});
这篇关于运行一个简单的后台任务的最简洁方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!