如何优雅地从其他线程访问Android视图?
我在异步模式下使用 Twitter4j。当我在侦听器中得到响应时,我希望能够更改活动中的某些视图,但这会导致 CalledFromWrongThreadException
。
我知道我可以使用 runOnUiThread 方法,但是除了内联可运行类之外,最优雅的解决方案是什么?
我的活动的一部分:
TwitterListener listener = new TwitterAdapter() {
@Override
public void gotUserDetail(User user) {
super.gotUserDetail(user);
fillInUserProfileDetails(user);
I'm using Twitter4j in asynchronous mode. When I get response in Listener I want to be able to change some Views in my Activity but it results in CalledFromWrongThreadException
.
I know that I can use runOnUiThread
method, but what is the most elegant solution for this apart from inlining Runnable Classes?
Part of my Activity:
TwitterListener listener = new TwitterAdapter() {
@Override
public void gotUserDetail(User user) {
super.gotUserDetail(user);
fillInUserProfileDetails(user);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为没有比 Activity.runOnUiThread(Runnable) 或 View.post(Runnable) 更“优雅”的解决方案了。您可能已经在 Android 文档中看到了有关线程的讨论:
编辑:
http://android-developers.blogspot.com/2009/05/ painless-threading.html
如前所述,Android UI 工具包不是线程安全的,因此与其进行的所有交互都必须发生在同一个线程上,即应用程序的 UI 线程;如果要将工作从一个线程传递到另一个线程,则需要一个 Runnable 对象来封装要执行的工作。
我知道匿名内部类可能看起来相当混乱,但它们在 Java 中是很常见的习惯用法,因为它们是最接近 该语言中可用的闭包。因此,在我看来,你要做的最好的事情就是咬紧牙关并使用 Activity.runOnUiThread(Runnable),并提醒自己,程序员眼中的优雅。
I don't think there is any more "elegant" solution than
Activity.runOnUiThread(Runnable)
orView.post(Runnable)
. You've probably already seen the discussion of threading in the Android docs:EDIT:
http://android-developers.blogspot.com/2009/05/painless-threading.html
As stated there, the Android UI toolkit is not threadsafe, so all interaction with it must occur on the same thread, namely the application's UI thread; and if you're going to pass work from one thread to another, you will need a Runnable object to encapsulate the work to be performed.
I know that anonymous inner classes can look rather messy, but they are quite a common idiom in Java, since they are the closest thing to closures available in the language. So the best thing for you to do, IMO, is grit your teeth and use
Activity.runOnUiThread(Runnable)
, and remind yourself that elegance is in the eye of the programmer.