事件或处理程序?从线程调用方法
考虑一个简单的 Android 应用程序:有两个 TabActivities 和一个在后台从服务器获取整数值的线程。如果数字是偶数,则必须显示在第一个选项卡中,否则显示在第二个选项卡中。显然我会做一些更复杂的事情,但这是基本模式。我该怎么做呢?我已经绞尽脑汁大约一天了,以下是我遇到的事情:
EventHandlers 的使用。两个 TabActivities 注册监听 my_events,当线程接收到值时,它会“抛出 my_event”,然后调用这两个活动中的特定方法并传递值。
处理程序的使用。
我以前没有使用过这两个概念,我想知道哪一个可能是更好/正确的路线。此外,如果您能提供沿所选路线的更多提示,我们将不胜感激。另外,这个线程应该从服务类运行吗?
Consider a simple Android application: there are two TabActivities and a thread in the background getting integer values from a server. If the number is even, it must be displayed in the first tab otherwise in the second. Obviously I will be doing something more complicated, but this is the basic pattern. How do I go about doing this? I have been scratching my head for about a day now and here are things I have come across:
Use of EventHandlers. The two TabActivities register for listening for my_events and when a value is received by the thread, it 'throws my_event' and then specific methods in both these activites are called and the value is passed.
The use of Handlers.
I have not used both of these concepts before and I would like to know which might be the better/correct route to take. Further, any more tips along the chosen route will be appreciated. Also, should this thread be run from a service class?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您创建线程时,只需将选项卡的对象传递到其中,然后在执行中您可以轻松地将所需的文本放入选项卡中。
When you create your thread just pass the objects of your tabs into it, then in your execution you can easily put the text you want into tabs.
您可能想了解如何使用 AysncTask。如果执行此操作,您希望将值插入到 onProgressUpdate() 方法中的相应选项卡中。由于传递给此方法的参数实际上可能无法充分表示传入的数据,因此您只需将新数据放在可以从 onProgressUpdate() 方法访问的位置(可能在成员变量中)。请记住,对此成员变量的访问可能需要同步,因为 onProgressUpdate 中的代码在应用程序的主线程上运行,而 doInBackground 中的代码在后台线程上运行,因此这些方法中的代码将同时运行。
AsyncTask 为您透明地使用处理程序,但如果您愿意,也可以使用原始处理程序。您需要记住的基本事项是
该线程应由服务,但如果线程只需要在有 UI 更新时才需要存在,那么这样做可能没有什么意义。
Possibly you want to look at using an AysncTask. If you do this you want to insert the values into the appropriate tab in the onProgressUpdate() method. Since the arguments passed to this method may not actually be able to represent the incoming data sufficiently you'll just want to put the new data somewhere that it can be accessed from the onProgressUpdate() method, probably in a member variable. Keep in mind that access to this member variable probably needs to be synchronized because code in onProgressUpdate is running on the application's main thread, while code in doInBackground is running on a background thread so code in these methods will be running concurrently.
AsyncTask uses Handlers transparently for you, but you could use raw Handlers if you wanted. The basic things you need to keep in mind are
Possibly the Thread should be invoked by a Service, but if the Thread only needs to exist when there is a UI for it to update there may be little point to this.