在后台处理工作并且可以通过一些机制来操作UI线程的情况下,何时使用AsyncTask
和何时使用Thread
。
在后台处理工作并且可以通过一些机制来操作UI线程的情况下,何时使用AsyncTask
和何时使用Thread
。
希望这能帮到你:
对于长时间运行的任务,我们使用Java线程和Android本地的AsyncTask。
基本上,使用AsyncTask来处理:
并且使用Java线程来处理:
有关更多信息,请参见Mohit的回答点击此处
服务类似于Activity,但没有界面。如果您想要获取天气,例如,您不会为其创建一个空白活动,而是将使用服务。服务可以访问Context对象,该对象具有独立的生命周期。这允许许多活动重用公共代码,并且在公共或公开服务的情况下,在许多应用程序中使用。
默认情况下,服务在调用组件进程的主线程上运行(因此可能会降低响应性并导致ANR),因此您应该创建一个新线程来执行长时间运行的操作。
线程是一条线程,可能您已经从其他部分了解过它。您需要知道的是,您无法从线程中更新UI。您需要使用Handler进行此操作,并且有时停止线程也会变得棘手。线程是一种在不阻塞其他工作的情况下完成工作的机制...
服务不意味着线程,线程也不意味着服务。两者是不同的。
AsyncTask是建议使用的智能线程。智能,因为它可以帮助处理方法,而且有两个在UI线程上运行的方法,这对于更新UI组件很有用。
executeOnExecutor
代替execute
在专用线程池中执行AsyncTask。请参见http://developer.android.com/reference/android/os/AsyncTask.html#executeOnExecutor%28java.util.concurrent.Executor,%20Params...%29
因为示例通常更具表现力,请看下面的示例。static Object doHeavyTask(String string) throws Exception;
TextView progressInfo;
new AsyncTask<String, Integer, Exception>() {
@Override
protected Exception doInBackground(String... params) {
for (int i = 0; i < params.length; i++) {
try {
doHeavyTask(params[i]);
} catch (Exception e) {
return e;
}
publishProgress(i, params.length);
}
return null;
}
@Override
protected void onProgressUpdate(Integer... values) {
progressInfo.setText("Executed " + values[0] +
" of " + values[1] + " tasks.");
}
@Override
protected void onPostExecute(Exception result) {
if (result == null) {
progressInfo.setText("Heavy background job done successfully!");
}
else {
progressInfo.setText("Heavy background job failed!" +
"Exception message: " + result.getMessage());
}
}
}.execute("input1", "input2", "input3");
使用Thread也可以完全实现相同的功能:
final Handler handler = new Handler(Looper.getMainLooper());
final String[] params = { "input1", "input2", "input3" };
new Thread() {
@Override
public void run() {
for (int i = 0; i < params.length; i++) {
try {
doHeavyTask(params[i]);
} catch (final Exception e) {
handler.post(new Runnable() {
@Override
public void run() {
progressInfo.setText("Heavy background job failed!" +
"Exception message: " + e.getMessage());
}
});
return;
}
final int currentIndex = i;
handler.post(new Runnable() {
@Override
public void run() {
progressInfo.setText("Executed " + currentIndex +
" of " + params.length + " tasks.");
}
});
}
handler.post(new Runnable() {
@Override
public void run() {
progressInfo.setText(
"Heavy background job done successfully!");
}
});
}
}.start();
您可以同时运行多个线程。但是asynctask是排队的,这意味着它一次只能运行一个任务。