情况:
- 活动绑定到已启动的前台服务。
- 服务将本地活页夹分发给活动。
- 活动通过 getService() 调用获取对服务的引用。
- 活动希望使用消息直接与服务中运行的线程进行通信。它从活动中调用 mService.getThreadHandler() 方法。
问题:
- 如何从当前正在运行的线程中获取 Handler 到活动活动中,以便我可以将消息直接发布到线程消息队列?
我不在服务中使用信使,我想从活动端直接与服务中的线程通信。
编辑:活动通过调用以下内容获取服务中线程本身的处理程序:
活动代码:
Handler mServiceThreadHandler;
ServiceConnection mServiceConnection;
public void onStart() {
if (!bindService(new Intent(this, MainService.class), mServiceConnection, Context.BIND_AUTO_CREATE))
{
Log.e(TAG, "Client did not bind to Service!");
}
super.onStart();
}
public class MyLocalServiceConnection implements ServiceConnection {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
LocalBinder binder = (LocalBinder) service;
mService = (MainService) binder.getService();
// the handler of the service is actually a handler of a thread
// within the service, and is set automatically within the binding
// activity when binding to the service. That way you have a direct
// "connection" with the message queue of the thread instead of
// a message queue in the service itself (main thread of service)
mServiceThreadHandler = mService.getServiceHandler();
if (mServiceThreadHandler == null) {
Log.e(TAG, "Service handler is NULL");
}
mBoundedToService = true;
}
@Override
public void onServiceDisconnected(ComponentName name) {
mServiceThreadHandler = null;
mBoundedToService = false;
}
}
服务代码:
private HandlerThread mServiceThread = new MyServiceThread();
public Handler getServiceHandler() {
return new Handler(mServiceThread.getLooper());
}
是否新的 Handler(mServiceThread.getLooper()); 在 mServiceThread 中返回一个新的 Handler 还是同一个 Handler?
编辑 2:使用接收消息的 serviceThread 更新服务代码。
public class MyService extends Service {
private MyHandlerThread serviceThread = new MyHandlerThread("serviceThread");
serviceThread.start();
public Handler getServiceHandler() {
// hand out the same handler of the service thread for using it in an activity!
// serviceThread.getLooper() is the current looper of the thread
// serviceThread is the 'this' which handles the messages (see MyHandlerThread)
return new Handler(serviceThread.getLooper(), serviceThread);
}
// do stuff in Service
}
public class MyHandlerThread extends HandlerThread implements android.os.Handler.Callback {
public MyHandlerThread(String name) {
super(name);
}
public MyHandlerThread(String name, int priority) {
super(name, priority);
}
@Override
public boolean handleMessage(Message msg) {
// TODO define your own message handling here.
return false;
}
}
正确的?