Making changes to Main Activity UI from thread in Service

随声附和 提交于 2019-12-04 09:03:00

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);

Look into Service Binding. Or you could use BroadcastReceiver in your main activity to receive broadcasts from Service.

You have to send an intent from your service with sendBroadcast(intent) and set a BroadcastReceiver in your activity

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!