java 在 Android 中异步执行方法的最佳方式(紧凑且正确)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16317201/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Best way to execute method asynchronously in Android (compact and correct)
提问by Misha
Say I have an Activity showing some content on screen. I need to execute some method (asyncMethod) asynchronously and when it is done, I need to update data on screen. What is the most correct and simple way to do this?
假设我有一个 Activity 在屏幕上显示一些内容。我需要异步执行一些方法 (asyncMethod),完成后,我需要更新屏幕上的数据。执行此操作的最正确和最简单的方法是什么?
Currently the most simple way I know is using thread:
目前我知道的最简单的方法是使用线程:
new Thread(new Runnable() {
public void run() {
asyncMethod();
}
}).start();
I'm familiar with AsyncTask, but it is more complex than using thread and for each method i need to run asynchronously there is a need to create new AsyncTask while this is greatly increases code size.
我熟悉 AsyncTask,但它比使用线程更复杂,对于我需要异步运行的每个方法,都需要创建新的 AsyncTask,而这会大大增加代码大小。
I thought about some generic AsincTask which gets method as a parameter and than executes it, but as far as i know it is impossible in Java to pass methods as parameters.
我想到了一些通用的 AsincTask,它获取方法作为参数然后执行它,但据我所知,在 Java 中不可能将方法作为参数传递。
In other words I'm looking for most compact(but correct) way to execute methods asynchronously.
换句话说,我正在寻找异步执行方法的最紧凑(但正确)的方法。
采纳答案by Jatin
Handler
and Looper
.
Handler
和Looper
。
Most of the times, keep the Handler to the Looper
of UI thread and then use it to post Runnable
. For example:
大多数情况下,将 Handler 保留在Looper
UI 线程中,然后使用它来发布Runnable
. 例如:
Handler h = new Handler();
//later to update UI
h.post(new Runnable(//whatever);
PS: Handler
and Looper
are awesome. So much that I remadethem for Java.
PS:Handler
而且Looper
很棒。以至于我为 Java重新制作了它们。
回答by CodeChimp
If you used the Commanddesign pattern, and made a generic AsyncTask that could run your "command" objects, you would need only one class for each task and the one generic AsyncTask to execute them all. You could even go so far as to make a generic "command" that executed a method via reflections or some pre-defined interface method.
如果您使用命令设计模式,并制作了一个可以运行您的“命令”对象的通用 AsyncTask,您将只需要一个类用于每个任务和一个通用 AsyncTask 来执行它们。您甚至可以创建一个通用的“命令”,通过反射或一些预定义的接口方法来执行一个方法。