Android update UI main thread issue
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 networ开发者_如何转开发k 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
}
AsyncTask has a function called OnProgressUpdate. If you ovverride it, and add code here, it will be executed on the UI thread
To call the OnProgressUpdate function, you call PublishProgress.
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.
You need to override
protected void onProgressUpdate (Progress... values)
and publishProgress(Value...)
each time new data is received.
The doInBackground()
method of the AsyncTask does not run on the UI Thread and that is why it can't update the UI.
Another method would be using a Handler.
精彩评论