【问题标题】:Android update UI main thread issueAndroid更新UI主线程问题
【发布时间】:2011-07-25 15:49:10
【问题描述】:

我无法弄清楚这是如何在 android 中完成的。这是一个非常简单的应用程序,一个 TextView 占据了屏幕的大部分,一个 ToggleButton 在底部。当手机上的按钮被切换时,每 5 秒通过套接字进行一次请求新数据的通信,然后必须将此新数据添加到 TextView 的顶部。

因为您不想在主线程中执行 5 秒计时器或网络活动,所以我一直在使用 asynctask,但主线程之外的线程无法更新 TextView。

这是我正在做的一些伪代码。我怎样才能让它在每次收到新数据时调用 updateView,但从主线程调用?

Communication(IO) Variables

TextView 的字符串链接列表

public class MyActivity {
//setContentView
//setup network connection
//getTextView 
//getToggleButton
    //when clicked on start asynctask GetData
    //when clicked off stop GetData (set global boolean to false)
}

public void updateView(){

//take linked list and make one String of proper size for textview
//setTextView

}

private class GetData extends AsyncTask {

//while we want to get data (global boolean variable)
    //send request
    //wait for response
    //*update global text variable for the view* 
    //sleep for 5 seconds

}

【问题讨论】:

    标签: android multithreading textview


    【解决方案1】:

    AsyncTask 有一个名为 OnProgressUpdate 的函数。如果你覆盖它,并在此处添加代码,它将在 UI 线程上执行

    要调用 OnProgressUpdate 函数,请调用 PublishProgress。

    【讨论】:

    • 谢谢,如果我能选择多个正确答案,我会的。感谢您的帮助。
    【解决方案2】:

    您可以在 AsyncTaskonPostExecute()onProgressUpdate() 方法中执行此操作。从那里您可以触发 UI 上的更新。我假设您在doInBackground() 中获取数据。

    【讨论】:

      【解决方案3】:

      你需要重写

          protected void onProgressUpdate (Progress... values)
      

      publishProgress(Value...) 每次收到新数据时。

      AsyncTask 的doInBackground() 方法不在 UI 线程上运行,这就是它无法更新 UI 的原因。

      另一种方法是使用Handler

      【讨论】:

      • 谢谢,如果我能选择多个正确答案,我会的。感谢您的帮助。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-05
      • 1970-01-01
      • 1970-01-01
      • 2017-05-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多