0

所以从我读过的内容来看,Android的AsyncTask是异步加载Internet信息的好方法。但是,我不想阻止用户界面并阻止用户与其交互。如何顺利更新用户界面?

我的问题的基本描述。

目前,我使用websockets来发送/接收来自Web服务器的数据。在进入房间的用户,从播放列表中添加或删除的歌曲,上调或下调的歌曲,或一首歌曲结束,另一首歌曲开始的事件中,必须更新UI以便指示变化。但理想情况下,这些变化将非常频繁地发生,这意味着不断屏蔽用户界面以刷新它将会非常麻烦和烦人。

如何在不中断用户活动的情况下更新我的UI? AsyncTask足够吗?

+0

的AsyncTask是不是唯一的方式。还有Handler和Loopers,你可以在[与UI线程交流](https://developer.android.com/training/multiple-threads/communicate-ui.html)中阅读有关信息,然后保持您的应用程序响应。 –

回答

1

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的例子有更清晰的例子,但这只是一个我很方便的例子。

+0

因此,如果我使用的是socket.io,那么我会在Activity或AsyncTask中设置套接字连接的位置? – Quontas

+0

使用您的AsyncTask来完成长时间运行的工作。我已经更新了答案以示例。在AsyncTask中设置您的套接字连接,但您可以使用其他类或方法实际执行此操作,以保持代码清洁和可读。 –

+0

那么AsyncTask只运行一次?如果它只运行一次,有没有一种AsyncTask不断运行的方法? – Quontas