Wi-Fi Peer-to-Peer(二)
Wi-Fi Peer-to-Peer API
在上一篇对 **Wi-Fi Peer-to-Peer **进行初步了解之后,这一篇我们来看看 Android Wi-Fi Peer-to-Peer Application 创建过程。
为此,我们先了解API
Wi-Fi P2P API 主要由以下3个重要部分组成
1.Methods
方法,有发现对等设备,请求对等设备,连接对等设备的方法
2.Listeners
监听器,Methods
中的方法都将接受一个监听器作为参数,允许你监听各个方法的调用成功或失败。这些方法都是异步调用的
3.Intents
意图,由Wi-Fi P2P framework通过指定的事件通知你,例如 断开连接或发现新的对等设备
整个过程都是这三个组建的配合使用。
举个例子:我们调用discoverPeers()
发现对等设备时,我们需要给他(discoverPeers()
)提供一个监听器 WifiP2pManager.ActionListener
,当discoverPeers()
调用成功时监听器的onSuccess()
方法会被回调,同理失败时onFailure()
方法会被回调。当discoverPeers()
发现对等设备列表发生变化时Wi-Fi P2P framework的WIFI_P2P_PEERS_CHANGED_ACTION意图会被广播
我们来看看API详细介绍,然后这些模糊概念会清楚很多
API Overview
Table 1 Wi-Fi P2P Methods
Method | Description |
---|---|
initialize() |
Registers the application with the Wi-Fi framework. This must be called before calling any other Wi-Fi P2P method. |
connect() |
Starts a peer-to-peer connection with a device with the specified configuration. |
cancelConnect() |
Cancels any ongoing peer-to-peer group negotiation. |
requestConnectInfo() |
Requests a device's connection information. |
createGroup() |
Creates a peer-to-peer group with the current device as the group owner |
removeGroup() |
Removes the current peer-to-peer group. |
requestGroupInfo() |
Requests peer-to-peer group information. |
discoverPeers() |
Initiates peer discovery |
requestPeers() |
Requests the current list of discovered peers. |
Table 2 Wi-Fi P2P Listeners
Listener Interface | Associated Action |
---|---|
WifiP2pManager.ActionListener |
connect() ,cancelConnect() ,createGroup() ,removeGroup() ,discoverPeers()
|
WifiP2pManager.ChannelListener |
initialize() |
WifiP2pManager.ConnectionInfoListener |
requestConnectInfo() |
WifiP2pManager.GroupInfoListener |
requestGroupInfo() |
WifiP2pManager.PeerListListener |
requestPeers() |
Table 3 Wi-Fi P2P Intents
Intent | Description |
---|---|
WIFI_P2P_CONNECTION_CHANGED_ACTION |
Broadcast when the state of the device's Wi-Fi connection changes. |
WIFI_P2P_PEERS_CHANGED_ACTION |
Broadcast when you call discoverPeers(),you usually want to call requestPeers() to get an updated list of peers if you handle this intent in your application |
WIFI_P2P_STATE_CHANGED_ACTION |
Broadcast when Wi-Fi P2P is enabled or disabled on the device |
WIFI_P2P_THIS_DEVICE_CHANGED_ACTION |
Broadcast when a device's detail have changed,such as the device's name |
使用的API不多,也很容易理解。
我测试连接2部手机,测试成功了。
但是由于今天有急事,代码部分留到第三部分,这一部分就算是对API进行了解,各位同学请见谅O(∩_∩)O。
我们第三部分见ヾ( ̄▽ ̄)ByeBye