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

目录
相关文章
|
存储 编解码 Windows
AVI 格式的历史和演变
AVI 格式的主要功能使其成为存储和播放多媒体内容的多功能且实用的选择。 它对多种编解码器、各种分辨率和广泛兼容性的支持使 AVI 格式成为视频爱好者和专业人士的可靠选择。
391 0
|
Linux Docker 容器
.net Core WebApi发布到Docker并推送到阿里云容器服务
.net Core WebApi发布到Docker并推送到阿里云容器服务
984 0
.net Core WebApi发布到Docker并推送到阿里云容器服务
|
9月前
|
存储 Linux API
【Linux进程概念】—— 操作系统中的“生命体”,计算机里的“多线程”
在计算机系统的底层架构中,操作系统肩负着资源管理与任务调度的重任。当我们启动各类应用程序时,其背后复杂的运作机制便悄然展开。程序,作为静态的指令集合,如何在系统中实现动态执行?本文带你一探究竟!
【Linux进程概念】—— 操作系统中的“生命体”,计算机里的“多线程”
|
设计模式 中间件 程序员
【实战指南】深入了解23种设计模式
《深入了解23种设计模式:程序员必读指南》旨在帮助程序员理解和应用设计模式,以解决常见编程问题。书中介绍了设计模式的起源、目的及其在提高代码复用性、质量和团队沟通中的作用。涵盖创建型、结构型和行为型三大类共23种设计模式,每种模式均附有详细解析与C++实现示例,适合初学者和有经验的开发者学习参考。
281 97
|
12月前
|
机器学习/深度学习 自然语言处理 语音技术
Python在深度学习领域的应用,重点讲解了神经网络的基础概念、基本结构、训练过程及优化技巧
本文介绍了Python在深度学习领域的应用,重点讲解了神经网络的基础概念、基本结构、训练过程及优化技巧,并通过TensorFlow和PyTorch等库展示了实现神经网络的具体示例,涵盖图像识别、语音识别等多个应用场景。
389 8
|
存储 人工智能 Serverless
妙用AI助理帮您定方案、找细节
当您希望在繁琐的文档中迷失方向时,AI助理能为您提供清晰指引,助您轻松实现加速配置与获取核心代码参数,显著简化开发流程。无论是方案获取还是寻找细节,只需向AI助理提问,即可获得详细步骤与示例代码,大幅提升工作效率。点击右下角的AI助理,即刻体验便捷服务。
425 1
|
Python
经验大分享:Python函数返回值
经验大分享:Python函数返回值
268 0
|
Java Go Python
golang调用python实战
# 简介 ## go-python Python提供了丰富的[C-API](https://docs.python.org/2/c-api/)。而C和Go又可以通过cgo无缝集成。所以,直接通过Golang调用libpython,就可以实现Go调Python的功能了。但是过程比较复杂,而[go-python](https://github.com/sbinet/go-python)提供
3920 0
golang调用python实战
|
Web App开发 移动开发 HTML5
HTML中input标签的23种type类型
HTML中input标签的23种type类型
|
前端开发 Java 微服务
SpringBoot中的配置文件加载顺序
SpringBoot中的配置文件加载顺序
249 0