Reputation: 1491
I am using Eclipse and programming for android. Can an AsyncThread interact with the UI, I have this code in my background thread and it is causing an exception to be thrown:
if (pressTime == 0){
displayTime.setText("You missed your ring");
}
Upvotes: 0
Views: 176
Reputation: 36289
You can use a Handler
. Just create it in the UI Thread, then post a call to it from your async thread.
For example, if you are using an AsyncTask
, just add the following global variable:
Handler mHandler;
Next, in your task's constructor, or onPreExecute
method, add the following line:
mHandler = new Handler();
Finally, as long as the above line was called on the UI Thread, you can execute code on said Thread in your doInBackground
method using the following:
mHandler.post(new Runnable() {
@Override
public void run() {
if (pressTime == 0)
displayTime.setText("You missed your ring");
}
});
Upvotes: 1
Reputation: 157447
Only the thread that actually has created the view (tipically the UI Thread) can modify the view. You have to post on the UI Thread queue the modify you want to brought to the the UI. Tipically, in your context is the activity, this is achieved with runOnUiThread
. Otherwise you can use and Handler
.
Here the doc for runOnUiThread. Here for Handler.
Upvotes: 3