Android wifi探究四:Wifi P2P framework层源码分析

上一篇博客对应用程序下使用Wi-Fi P2P Api连接附近的设备的过程做了一个简单的梳理,我们只是学会了怎么使用api,但对api背后的机制一无所知。那么这篇博客就开始尝试分析api背后的实现机制,也就是android framework中Wi-Fi P2P的工作机制。
Wifi P2P在framework层也是一个Service,它的启动过程和WifiService一样:

                mSystemServiceManager.startService(WIFI_P2P_SERVICE_CLASS);
                mSystemServiceManager.startService(WIFI_SERVICE_CLASS);

所以就在不啰嗦了,感兴趣可惜浏览下 Android wifi探究二:java层的wifi框架 这篇文章,我们感兴趣的是WifiP2pServiceImpl是怎么工作的,怎么和应用程序交互的。比如当应用程序调用discoverPeers方法发起查找时,WifiP2pServiceImpl做了什么工作。
回顾上一篇博客的内容,我们使用Wifi P2P服务时,首先要获取到WifiP2pManager 的实例:

mManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);

之后的操作都是调用WifiP2pManager 中的方法实现的。我们知道我们向系统注册的Wi-Fi P2P服务是WifiP2pServiceImpl,他们之间会使用一定的机制进行通信,当然主要就是Binder了,不过,还有一个很重要的知识点,那就是Messenger。

一.Messenger

浏览下WifiP2pServiceImpl的实现,因为之前已经分析过WifiServiceImpl的实现,对比我们就知道WifiP2pServiceImpl内部也有个状态机,状态机是消息驱动的,我们需要给状态机发消息才能促使状态机切换状态,那么我们能不能在WifiP2pManager 中直接给WifiP2pServiceImpl发消息呢?答案是能。怎么发呢?就是这里要介绍的Messenger。
我们看一下Api文档中对它的介绍:
Reference to a Handler, which others can use to send messages to it. This allows for the implementation of message-based communication across processes, by creating a Messenger pointing to a Handler in one process, and handing that Messenger to another process.

Note: the implementation underneath is just a simple wrapper around a Binder that is used to perform the communication. This means semantically you should treat it as such: this class does not impact process lifecycle management (you must be using some higher-level component to tell the system that your process needs to continue running), the connection will break if your process goes away for any reason,

翻译(英语太菜,翻译有误请包涵):
我们可以使用Handler引用来发消息,我们可以创建一个Messenger实例,这个实例指向一个进程中的Handler,这样我们可以在另一个进程中处理Messenger 发过来的消息。这样就实现了基于消息的进程间的通信。
注意:实现的原理就是对Binder做一个封装。这意味着:这个类不影响进程的生命周期(你必须使用高级别的组件告诉系统的进程需要继续运行),如果另一进程消失了的话,连接就会断开。
那么,Messanger是怎么获取的呢?
WifiP2pManager 中:

    public Messenger getMessenger() {
        try {
            return mService.getMessenger();
        } catch (RemoteException e) {
            return null;
        }
    }

mService就是WifiP2pServiceImpl的客户端,我们看下WifiP2pServiceImpl中的getMessenger方法:

    public Messenger getMessenger() {
        enforceAccessPermission();
        enforceChangePermission();
        return new Messenger(mClientHandler);
    }

mClientHandler就是WifiP2pServiceImpl用来发送和处理消息的Handler实例&

  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值