Bound Service 之 Messenger

简介:

上一片文章《Bound Service 之本地Binder》介绍了 Service 的bind方法的基本使用。现在再来解释下Bound Service的第二种用法。

  • 使用Messenger
如果你的service需要向远程进程(remote processes)提供服务,你可以使用Messenger提供接口。这个技术可以使你不用不使用 AIDL 也能实现跨进程IPC。如果阅读下文有疑问或困难可以先看看之前写过的关于 Messenger的 一篇文章:  《Messenger解析(和Handler、IBinder、Message的关系) 》
实现步骤:
1.service 要实现一个handler用来接收处理client传来的消息。
2.创建一个Messender关联到handler
3.使用messenger的IBinder作为unbind方法的返回值
4.client 得到IBinder之后创建一个messender(持有共同的IBinder,共同的handler达到通信),使用messenger向service发送请求。
  service收到client的消息在handler中处理。
这种方式没有直接在service中定义公用方法了。
例子:
server:
public class MessengerService extends Service {
    /** Command to the service to display a message */
    static final int MSG_SAY_HELLO = 1;

    /**
     * Handler of incoming messages from clients.
     */
    class IncomingHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_SAY_HELLO:
                    Toast.makeText(getApplicationContext(), "hello!", Toast.LENGTH_SHORT).show();
                    break;
                default:
                    super.handleMessage(msg);
            }
        }
    }

    /**
     * Target we publish for clients to send messages to IncomingHandler.
     */
    final Messenger mMessenger = new Messenger(new IncomingHandler());

    /**
     * When binding to the service, we return an interface to our messenger
     * for sending messages to the service.
     */
    @Override
    public IBinder onBind(Intent intent) {
        Toast.makeText(getApplicationContext(), "binding", Toast.LENGTH_SHORT).show();
        return mMessenger.getBinder();
    }
}
client:
public class ActivityMessenger extends Activity {
    /** Messenger for communicating with the service. */
    Messenger mService = null;

    /** Flag indicating whether we have called bind on the service. */
    boolean mBound;

    /**
     * Class for interacting with the main interface of the service.
     */
    private ServiceConnection mConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder service) {
            // This is called when the connection with the service has been
            // established, giving us the object we can use to
            // interact with the service.  We are communicating with the
            // service using a Messenger, so here we get a client-side
            // representation of that from the raw IBinder object.
            mService = new Messenger(service);
            mBound = true;
        }

        public void onServiceDisconnected(ComponentName className) {
            // This is called when the connection with the service has been
            // unexpectedly disconnected -- that is, its process crashed.
            mService = null;
            mBound = false;
        }
    };

    public void sayHello(View v) {
        if (!mBound) return;
        // Create and send a message to the service, using a supported 'what' value
        Message msg = Message.obtain(null, MessengerService.MSG_SAY_HELLO, 0, 0);
        try {
            mService.send(msg);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

    @Override
    protected void onStart() {
        super.onStart();
        // Bind to the service
        bindService(new Intent(this, MessengerService.class), mConnection,
            Context.BIND_AUTO_CREATE);
    }

    @Override
    protected void onStop() {
        super.onStop();
        // Unbind from the service
        if (mBound) {
            unbindService(mConnection);
            mBound = false;
        }
    }
}

Bound Service 之 Messenger 介绍道这里,下篇文章介绍,Bound Service 的第三种方式:AIDL。

文章参考:http://developer.android.com/guide/components/bound-services.html

目录
相关文章
|
3月前
|
存储 应用服务中间件 开发工具
Platform as a Service
PaaS(Platform as a Service,平台即服务)是一种云计算服务模型,它提供了一组开发工具和服务,使开发人员可以构建和部署应用程序,而无需关心底层基础设施的管理。PaaS 通常包括一个操作系统级别的基础设施、服务器、存储和网络服务,以及一系列开发工具和服务,如数据库、Web 服务器、应用服务器、消息传递、身份认证等。
54 2
Platform as a Service
|
6月前
|
监控
什么是 Service Ticket 的 Service Level Agreement
什么是 Service Ticket 的 Service Level Agreement
63 0
|
2月前
|
安全
[UDS] --- SecurityAccess 0x27 service
[UDS] --- SecurityAccess 0x27 service
35 0
|
2月前
[UDS] --- DiagnosticSessionControl 0x10 service
[UDS] --- DiagnosticSessionControl 0x10 service
55 0
|
API 调度
从Service到WorkManager
关于Service,想必大家都太熟悉了,今天我们就再回顾下它的使用、概念、区别、变更历史等等。
391 0
从Service到WorkManager
backend system available odata service detection
Created by Wang, Jerry, last modified on Jan 17, 2015
backend system available odata service detection
How to create and consume web service in CRM
The following steps demonstrates how to expose a function module as a web service in CRM.
115 0
How to create and consume web service in CRM
|
Kubernetes 负载均衡 网络协议
k8s service
Kubernetes Service 定义了这样一种抽象:一个 Pod 的逻辑分组,一种可以访问它们的策略——通常称为微服务。这一组 Pod 能够被 Service 访问到,通常是通过 Label Selector 实现的。
7045 0
|
网络架构