我已经看到了至少五个模式,通过这些模式,您可以在工作线程中运行一些代码.最简单的:
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 实用程序框架(由Facebook和parse使用),就这么简单:
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; } });更多推荐
运行一个简单的后台任务的最简洁方法?
发布评论