[英]Android-Studio: How to update a chat (ListView) from a thread, which is startet in an other Activity
Hey guys:) I'm currently working on an android project, where I want to realize a chat function. 大家好:)我目前正在从事一个Android项目,我想在其中实现聊天功能。 I know there are several tutorials which describe a chat app but I want to do it myself with my own Server.
我知道有一些描述聊天应用程序的教程,但我想自己用自己的服务器来做。 In my MainActivity I start a self written updater in a new thread (bc. of network-operations can only be done outside the UI thread), which permanently checks, if the chat-protocol, which is stored on my server (RaspberryPi), has new messages from other users.
在我的MainActivity中,我在一个新线程(只能在UI线程之外完成网络操作)中启动一个自写更新程序,该程序将永久检查存储在我的服务器(RaspberryPi)中的聊天协议,有来自其他用户的新消息。 If there are new messages, the Updater downloads it and stores it in a string.
如果有新消息,更新程序将下载并存储在字符串中。 This works fine!
这样很好! Now, when the updater receives a new message, I want to update the ListView in my Chat-Activity with the new message.
现在,当更新程序收到新消息时,我想用新消息更新聊天活动中的ListView。 This process should work at any time and update my ListView permanently (not with a refresh button or sth. like that).
此过程应随时可用,并永久更新我的ListView(而不用这样的刷新按钮等)。 My question is: how do i realize this the smoothest way - a strategy, not necessarily code.
我的问题是:我如何实现这种最流畅的方式-一种策略,不一定是代码。 One idea, which works but feels a bit random, is to write the received messages in a shared preferences-file and load it in the chat-acivity via an infinite loop in the chat activity.
一个可行但有些随机的想法是,将接收到的消息写入共享的首选项文件中,并通过聊天活动中的无限循环将其加载到聊天活动中。 Is there a possibility to write the received messages directly in the ListView at any time from the thread with the updater which was startet in the MainActivity.
是否有可能随时使用MainActivity中的更新程序更新程序从线程直接在ListView中编写接收到的消息。 If needed i could upload the current code but i want to do it directly and not with an infinite loop.
如果需要,我可以上传当前代码,但我想直接执行而不是无限循环。 Thanks for reading and maybe even for the help :)
感谢您的阅读,甚至是帮助:)
You may want to save the received messages in SQLite database, and inside the activity, you can poll the database (suppose for every 5 seconds) and stop polling after the activity is destroyed. 您可能希望将收到的消息保存在SQLite数据库中,并且可以在活动内部轮询数据库(假设每5秒一次),并在活动被破坏后停止轮询。
Another way would be to use the static references of the views and update them from a different class. 另一种方法是使用视图的静态引用,并从其他类更新它们。 Even you are trying to update them from inside a background thread, you can update the UI using
view.post()
即使您尝试从后台线程内部更新它们,也可以使用
view.post()
更新UI。
SomeActivity.textView.post(new Runnable(){
@Override
public void run(){
SomeActivity.textView.setText("sth");
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.