Android的UI更新主线程问题 [英] Android update UI main thread issue

查看:192
本文介绍了Android的UI更新主线程问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法弄清楚它是如何做的机器人。这是一个非常简单的应用程序,一个TextView占用大部分屏幕和底部切换按钮。当按钮被切换在电话通过套接字通信,每5秒请求新的数据,这个​​新的数据必须随后是prepended到的TextView的顶部。

由于你不想做5秒的定时器或网络活动中我一直在使用的AsyncTask,但线程主线程外无法更新的TextView的主线。

下面是一些伪code,因为我在做什么。我怎样才能使它这样的UpdateView在每接收新数据时调用,但是从主线程?

 通讯(IO)变量

有关的TextView字符串的LinkedList

 公共类MyActivity {
//的setContentView
//设置网络连接
// getTextView
// getToggleButton
    //当开始的AsyncTask的GetData点击
    //当点击关闭停止的GetData(设置全局布尔为false)
}公共无效的UpdateView(){//拿链表,并为TextView的适当大小的一个字符串
// setTextView}私有类的GetData扩展的AsyncTask {//而我们想要得到的数据(全局布尔变量)
    //发送请求
    //等待回应
    该视图// *更新全局文本变量*
    //睡眠5秒}


解决方案

您可以在 onPostExecute()的AsyncTask C $ C>或 onProgressUpdate()方法。从那里,你可以触发UI上的更新。我认为在 doInBackground()您读取数据。

I am having trouble figuring out how this is done in android. It is a very simple application, a TextView taking up the majority of the screen and a ToggleButton on the bottom. When the button is toggled on the phone communicates over a socket every 5 seconds requesting new data, this new data must then be prepended to the top of the TextView.

Because you don't want to do the 5 second timers or the network activity in the main thread I've been using asynctask but threads outside the main thread can't update the TextView.

Here is some pseudocode for what I am doing. How can I make it so updateView is called each time new data is received, but from the main thread?

Communication(IO) Variables

LinkedList of strings for 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

}

解决方案

You can do this inside your AsyncTask in onPostExecute() or in onProgressUpdate()method. From there you can trigger updates on the UI. I assume that in doInBackground() you fetch the data.

这篇关于Android的UI更新主线程问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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