asyncTask
不会阻止用户界面。它在单独的线程上运行以发送/接收来自Web的数据,然后返回结果。当您收到结果时,您可以根据您的选择更新UI。
当asyncTask
执行其后台工作时,您的用户界面将不会停止。你可以通过在你的活动中建立一个,并在doInBackground
方法中简单地睡一段时间(比如5秒)来尝试。你会看到你的用户界面在5秒内仍然有效。
编辑:你可以对你回来的结果做任何事情,它也不会中断你的用户界面。如果情况并非如此,那么您可能需要考虑如何优化内存对象的操作。任何未存储在内存中的内容都可能被检索或写入到磁盘,数据库或因特网终端,其编号为AsyncTask
。正如评论者指出的那样,这不是使用其他线程的唯一方式,但如果您提出合理的Web请求并期望用户拥有良好的连接,则这很容易,并且可能会起作用。你只是想确保你有超时和异常的覆盖,以便你的应用程序不会崩溃,如果任务需要比预期更长的时间。
public class LoadCommentList extends AsyncTask<Integer, Integer, List<Comment>> {
private String commentSubject;
public LoadCommentList(commentSubject){
this.commentSubject = commentSubject;
}
// Do the long-running work in here
protected List<Comment> doInBackground(Integer... params) {
// the data producer is a class I have to handle web calls
DataProducer dp = DataProducer.getInstance();
// here, the getComments method makes the http call to get comments
List<Comment> comments = dp.getComments(commentSubject);
return comments;
}
// This is called each time you call publishProgress()
protected void onProgressUpdate(Integer... progress) {
// setProgressPercent(progress[0]);
}
// This is called when doInBackground() is finished
protected void onPostExecute(List<Comment> comments) {
// calls a method in the activity to update the ui
updateUI(comments);
}
}
实际上使用Integer ... params的例子有更清晰的例子,但这只是一个我很方便的例子。
的AsyncTask是不是唯一的方式。还有Handler和Loopers,你可以在[与UI线程交流](https://developer.android.com/training/multiple-threads/communicate-ui.html)中阅读有关信息,然后保持您的应用程序响应。 –