Android 话题 类
Android Thread Classes
我正在尝试使用 Android Studio 实现一个简单的客户端服务器应用程序。我了解 Android 关于主线程 UI 无法处理网络代码和线程无法引用主线程的限制。
但是,我不确定使用哪种方法来 运行 网络相关命令(即发送 OutputStream or/and InputStream)。我有两个一般性问题。
我应该使用工作线程(Runnable 或其他)还是使用 AsyncTask?
在什么情况下哪个更好?
谢谢
来自AsyncTask
documentation:
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.
目前 AsyncTask
是否重新使用相同的后台线程(即,如果它使用大小为 1 的固定线程池)有点模糊。这个问题可以通过查看 AsyncTask
来源来回答。但即使现在 没有,将来也可能。如果您使用 AsyncTask
,您的代码将自动受益于未来的更改和改进。仅此一项就足以使用 AsyncTask
,即使您不需要它带来的其他便利。
AsyncTask enables proper and easy use of the UI thread. This class
allows performing background operations and publishing results on the
UI thread without having to manipulate threads and/or handlers. An
asynchronous task is defined by a computation that runs on a
background thread and whose result is published on the UI thread.
AsyncTask will go through the following 4 stages:
onPreExecute()
Invoked on the UI thread before the task is executed
doInbackground(Params..)
Invoked on the background thread immediately after onPreExecute() finishes executing.
onProgressUpdate(Progress..)
Invoked on the UI thread after a call to publishProgress(Progress...).
onPostExecute(Result)
我正在尝试使用 Android Studio 实现一个简单的客户端服务器应用程序。我了解 Android 关于主线程 UI 无法处理网络代码和线程无法引用主线程的限制。
但是,我不确定使用哪种方法来 运行 网络相关命令(即发送 OutputStream or/and InputStream)。我有两个一般性问题。
我应该使用工作线程(Runnable 或其他)还是使用 AsyncTask?
在什么情况下哪个更好?
谢谢
来自AsyncTask
documentation:
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.
目前 AsyncTask
是否重新使用相同的后台线程(即,如果它使用大小为 1 的固定线程池)有点模糊。这个问题可以通过查看 AsyncTask
来源来回答。但即使现在 没有,将来也可能。如果您使用 AsyncTask
,您的代码将自动受益于未来的更改和改进。仅此一项就足以使用 AsyncTask
,即使您不需要它带来的其他便利。
AsyncTask enables proper and easy use of the UI thread. This class allows performing background operations and publishing results on the UI thread without having to manipulate threads and/or handlers. An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread.
AsyncTask will go through the following 4 stages:
onPreExecute() Invoked on the UI thread before the task is executed doInbackground(Params..) Invoked on the background thread immediately after onPreExecute() finishes executing. onProgressUpdate(Progress..) Invoked on the UI thread after a call to publishProgress(Progress...). onPostExecute(Result)