Android更新UI主线程问题

Android更新UI主线程问题,android,multithreading,textview,Android,Multithreading,Textview,我很难弄清楚android是如何做到这一点的。这是一个非常简单的应用程序,文本视图占据了屏幕的大部分,底部有一个切换按钮。当手机上的按钮被切换时,每5秒通过一个插座进行一次通信,请求新数据,然后必须将新数据预先添加到TextView的顶部 因为您不想在主线程中执行5秒计时器或网络活动,所以我一直在使用asynctask,但主线程之外的线程无法更新TextView 下面是我正在做的一些伪代码。如何使每次从主线程接收到新数据时都调用updateView Communication(IO) Varia

我很难弄清楚android是如何做到这一点的。这是一个非常简单的应用程序,文本视图占据了屏幕的大部分,底部有一个切换按钮。当手机上的按钮被切换时,每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

}

AsyncTask有一个名为OnProgressUpdate的函数。如果您跳过它,并在这里添加代码,它将在UI线程上执行

要调用OnProgressUpdate函数,可以调用PublishProgress。

需要重写

    protected void onProgressUpdate (Progress... values)
每次收到新数据时发布进度(值…

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


另一种方法是使用。

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

谢谢您这么做,如果我能选择多个正确答案,我会的。谢谢你的帮助。谢谢你,如果我能选择多个正确答案,我会的。谢谢你的帮助。