Reputation: 1513
I've been looking for quite some time for some good documentation or a good example of this. I need to make changes to my main activity UI from the worker thread in my service which is running in the background. As far as I understand I know that I am suppose to work with some sort of Handler but I am not sure exactly how to approach this.
Does anyone have any ideas or good examples that they could direct me to? The UI element I am changing is a TextView that is simply informing the user of the status of the thread.
Thanks for your help.
Upvotes: 4
Views: 4576
Reputation: 173
Create a handler in onCreate() method in your main activity. This will create a handler in the UI thread. Then using this handler from the worker thread, call whatever you need to to get the TextView updated.
Upvotes: 1
Reputation: 2229
You have to send an intent from your service with sendBroadcast(intent) and set a BroadcastReceiver in your activity
Upvotes: 1
Reputation: 16622
All you have to do is to create a Handler
on the UI thread:
private Handler serviceHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
someFunctionInTheUIThread();
}
};
And then pass this through to your service. You could have a function in the Service like this:
public void registerHandler(Handler serviceHandler) {
handler = serviceHandler;
}
and then pass the handler through like this:
theService = ((LocalBinder) service).getService();
theService.registerHandler(serviceHandler);
then to send a message back:
Message msg = handler.obtainMessage(IDENTIFIER, "Message or data");
handler.sendMessage(msg);
Upvotes: 7
Reputation:
Look into Service Binding. Or you could use BroadcastReceiver in your main activity to receive broadcasts from Service.
Upvotes: 2