从其他线程访问视图(Android版) [英] Accessing views from other thread (Android)

查看:113
本文介绍了从其他线程访问视图(Android版)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开发一个Android应用程序,我有一个按钮,开始/暂停一定的模拟过程。虽然这一进程在运行,我需要输出它的实时一些数据。但是,当我创建一个新的线程模拟,我无法访问视图(让它的TextView)从这个线程,因为他们只能从他们在那里创建线程访问。另一方面,因为在模拟运行(例如,preSS一些其它按钮),否则用户将无法做任何事新线程是必要的。创建一个新的服务还需要创建在这种情况下,一个新的线程。我应该怎么解决这个问题呢?

I'm developing an android application, and I have a button which starts/pauses certain simulation process. While this process is running, I need to output some data from it real-time. But when I create a new thread for the simulation, I can't access views (let it be TextView) from this thread, because they only can be accessed from the thread where they were created. On the other hand, new thread is necessary because otherwise user wouldn't be able to do anything while simulation is running (for example, press some other buttons). Creating a new service also requires creating a new thread in this case. How should I solve this problem?

推荐答案

您可以通过多种方式处理它,

You can handle it in many ways,


  1. 尝试使用的AsyncTask 在这一点,在doInBackGround()方式,你的UI做您的后台工作不会阻止你也可以访问该意见从那里您可以通过它的上下文通过的 publishProgress()和onProgressUpdate调用AsyncTask的活动()

  1. Try to use AsyncTask in this, your background work done in doInBackGround() method, and your UI will not block and you can also access the views of Activity from where you call AsyncTask by its context via publishProgress() and onProgressUpdate() .

如果您正在使用的简单的线程,然后用处理程序或信息或runOnUiThread 您可以更新主线程的看法。

If you are using a simple Thread then using Handler or message or runOnUiThread you can update the view of main thread.

但是,在你的方式,我认为AsyncTask的是最适合你。

这篇关于从其他线程访问视图(Android版)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆