一 ) Provides classes to create peer-to-peer (P2P) connections with Wi-Fi Direct.
提供用于使用Wi-Fi Direct创建对等(P2P)连接的类。
二 ) Using these APIs, you can discover and connect to other devices when each device supports Wi-Fi Direct, then communicate over a speedy connection across distances much longer than a Bluetooth connection. The primary class you need to work with is WifiP2pManager, which you can acquire by calling getSystemService(WIFI_P2P_SERVICE). The WifiP2pManager includes APIs that allow you to:
使用以下API可以”发现”支持直连的设备也可以连接支持WIFI直连的设备,然后使用比蓝牙连接速度更快,连接距离更长的通信方式连接,需要使用主要WifiP2pManager类,可以通过调用getSystemService(WIFI_P2P_SERVICE)来获取对象.WifiP2pManager包含API如下:
And more
通过调用initialize()初始化P2P连接应用程序
三 ) Several other interfaces and classes are necessary as well, such as:
一些其他的接口和类同样也会用到,比如:
四 ) 使用这些API必须申请以下用户权限
- ACCESS_WIFI_STATE
- CHANGE_WIFI_STATE
- INTERNET (although your app doesn’t technically connect to the Internet, communicating to Wi-Fi Direct peers with standard java sockets requires Internet permission).
其中的第三个:虽然app可能不需要联网,但第三方通过java sockets获取网络与WIFI对等设备直连同样需要这个权限
Note: Not all Android-powered devices support Wi-Fi Direct. If your application uses Wi-Fi Direct, declare so with a element in the manifest file:
并不是Android设备都支持wifi直连,使用需要在清单元素中注册
<manifest ...>
<uses-feature android:name="android.hardware.wifi.direct" />
...
</manifest>
五:Wi-Fi peer-to-peer (P2P) allows Android 4.0 (API level 14) or later devices with the appropriate hardware to connect directly to each other via Wi-Fi without an intermediate access point (Android’s Wi-Fi P2P framework complies with the Wi-Fi Alliance’s Wi-Fi Direct™ certification program). Using these APIs, you can discover and connect to other devices when each device supports Wi-Fi P2P, then communicate over a speedy connection across distances much longer than a Bluetooth connection. This is useful for applications that share data among users, such as a multiplayer game or a photo sharing application.
Wifi P2P支持Android API level14以上合适的设备硬件通过wifi直连通信而不通过ap,当每个设备支持Wifi-P2P,就可以通过API发现和连接其他设备,然后使用比蓝牙连接速度更快,连接距离更长的通信方式连接,这对于用户共享数据很有用,比如多个游戏玩家玩游戏或者分享照片.
The Wi-Fi P2P APIs consist of the following main parts:
wifi P2P API包含一下及部分:
You often use these three main components of the APIs together. For example, you can provide a WifiP2pManager.ActionListener to a call to discoverPeers(), so that you can be notified with the ActionListener.onSuccess() and ActionListener.onFailure() methods. A WIFI_P2P_PEERS_CHANGED_ACTION intent is also broadcast if the discoverPeers() method discovers that the peers list has changed.
会用到以下三个API的组合,比如通过WifiP2pManager.ActionListener来调用discoverPeers()方法,这样当成功或者失败的时候会收到通知.调用discoverPeers()可以发现对等列表被更改,发送WIFI_P2P_PEERS_CHANGED_ACTION 广播
六:Create a broadcast receiver for Wi-Fi P2P intents
创建Wifi P2P intent 广播接收器
A broadcast receiver allows you to receive intents broadcast by the Android system, so that your application can respond to events that you are interested in. The basic steps for creating a broadcast receiver to handle Wi-Fi P2P intents are as follows:
允许通过接受广播气接受Android系统广播,这样你的应用可以响应你想要的事件.基本步骤去创建接收wifi p2p意图事件如下:
Create a class that extends the BroadcastReceiver class. For the class’ constructor, you most likely want to have parameters for the WifiP2pManager, WifiP2pManager.Channel, and the activity that this broadcast receiver will be registered in. This allows the broadcast receiver to send updates to the activity as well as have access to the Wi-Fi hardware and a communication channel if needed.
1:创建一个类继承BroadcastReceiver类.参数有"WifiP2pManager"/WifiP2pManager.Channel/activity.允许广播接收器更新activity,如果需要也可以通过Wi-Fi 硬件通道通信
In the broadcast receiver, check for the intents that you are interested in onReceive(). Carry out any necessary actions depending on the intent that is received. For example, if the broadcast receiver receives a WIFI_P2P_PEERS_CHANGED_ACTION intent, you can call the requestPeers() method to get a list of the currently discovered peers.
2 :在广播接受函数中检查任何你感兴趣的intent,根据收到的intent完成任何必要的处理操作,比如收到WIFI_P2P_PEERS_CHANGED_ACTION intent ,你可以调用requestPeers()方法获取当前对等设备发现列表
public class WiFiDirectBroadcastReceiver extends BroadcastReceiver {
private WifiP2pManager mManager;
private Channel mChannel;
private MyWiFiActivity mActivity;
public WiFiDirectBroadcastReceiver(WifiP2pManager manager, Channel channel,
MyWifiActivity activity) {
super();
this.mManager = manager;
this.mChannel = channel;
this.mActivity = activity;
}
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) {
// Check to see if Wi-Fi is enabled and notify appropriate activity
} else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {
// Call WifiP2pManager.requestPeers() to get a list of current peers
} else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) {
// Respond to new connection or disconnections
} else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) {
// Respond to this device's wifi state changing
}
}
}
七:Create a Wi-Fi P2P application
创建一个wifi P2P应用
Creating a Wi-Fi P2P application involves creating and registering a broadcast receiver for your application, discovering peers, connecting to a peer, and transferring data to a peer. The following sections describe how to do this.
创建一个wifi p2p 应用涉及为你的应用创建和注册广播监听,发现对等设备,连接对等设备,给对等设备传输数据.
Initial setup
Before using the Wi-Fi P2P APIs, you must ensure that your application can access the hardware and that the device supports the Wi-Fi P2P protocol. If Wi-Fi P2P is supported, you can obtain an instance of WifiP2pManager, create and register your broadcast receiver, and begin using the Wi-Fi P2P APIs
初始设置
在使用wifi p2p API之前,确保你的应用支持wifi p2p协议,如果支持,你可以获得一个WifiP2pManager对象,调用api来创建广播接收器.
1:Request permission to use the Wi-Fi hardware on the device and also declare your application to have the correct minimum SDK version in the Android manifest:
请求允许使用wifi硬件权限的声明在你的应用中,并且在Android manifest中指定正确的sdk版本号
<uses-sdk android:minSdkVersion="14" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
2:Check to see if Wi-Fi P2P is on and supported. A good place to check this is in your broadcast receiver when it receives the WIFI_P2P_STATE_CHANGED_ACTION intent. Notify your activity of the Wi-Fi P2P state and react accordingly:
检查是否启用并支持wifi P2P.在广播接收器接受到WIFI_P2P_STATE_CHANGED_ACTION intent时候是一个好地方.通知你的activity wifi P2P状态作出相应反映
@Override
public void onReceive(Context context, Intent intent) {
...
String action = intent.getAction();
if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) {
int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1);
if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) {
// Wifi P2P is enabled
} else {
// Wi-Fi P2P is not enabled
}
}
...
}
3:In your activity’s onCreate() method, obtain an instance of WifiP2pManager and register your application with the Wi-Fi P2P framework by calling initialize(). This method returns a WifiP2pManager.Channel, which is used to connect your application to the Wi-Fi P2P framework. You should also create an instance of your broadcast receiver with the WifiP2pManager and WifiP2pManager.Channel objects along with a reference to your activity. This allows your broadcast receiver to notify your activity of interesting events and update it accordingly. It also lets you manipulate the device’s Wi-Fi state if necessary:
在应用activity的onCreate()方法中获取WifiP2pManager对象并通过调用initialize()方法向Wi-Fi P2P framework注册这个应用,这个方法返回一个用来将应用与Wi-Fi P2P framework连接起来的WifiP2pManager.Channel对象.还可以用WifiP2pManager和WifiP2pManager.Channel 对象以及activity创建一个广播接收的实例.允许广播接收器通知activity根据注册事件相应更新,同时如果需要操纵设备的wifi状态
WifiP2pManager mManager;
Channel mChannel;
BroadcastReceiver mReceiver;
...
@Override
protected void onCreate(Bundle savedInstanceState){
...
mManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
mChannel = mManager.initialize(this, getMainLooper(), null);
mReceiver = new WiFiDirectBroadcastReceiver(mManager, mChannel, this);
...
}
4:Create an intent filter and add the same intents that your broadcast receiver checks for:
创建意图过滤同时添加一些广播接收器需要关注的意图
IntentFilter mIntentFilter;
...
@Override
protected void onCreate(Bundle savedInstanceState){
...
mIntentFilter = new IntentFilter();
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
...
}
5:Register the broadcast receiver in the onResume() method of your activity and unregister it in the onPause() method of your activity:
在onResume()中注册广播监听,在onPause()中取消广播监听
/* register the broadcast receiver with the intent values to be matched */
@Override
protected void onResume() {
super.onResume();
registerReceiver(mReceiver, mIntentFilter);
}
/* unregister the broadcast receiver */
@Override
protected void onPause() {
super.onPause();
unregisterReceiver(mReceiver);
}
When you have obtained a WifiP2pManager.Channel and set up a broadcast receiver, your application can make Wi-Fi P2P method calls and receive Wi-Fi P2P intents.
当获得WifiP2pManager.Channel 和配置广播接收器,应用就可以调用Wi-Fi P2P方法和接收Wi-Fi P2P意图
Discover peers
To discover peers that are available to connect to, call discoverPeers() to detect available peers that are in range. The call to this function is asynchronous and a success or failure is communicated to your application with onSuccess() and onFailure() if you created a WifiP2pManager.ActionListener. The onSuccess() method only notifies you that the discovery process succeeded and does not provide any information about the actual peers that it discovered, if any:
在范围内发现并连接可用的对等设备.这个函数是异步的,如果创建WifiP2pManager.ActionListener,则应用可以获取到onSuccess()和onFailure()来通知发现成功与否,但不提供任何关于被发现对等设备信息(如果有):
mManager.discoverPeers(channel, new WifiP2pManager.ActionListener() {
@Override
public void onSuccess() {
...
}
@Override
public void onFailure(int reasonCode) {
...
}
});
If the discovery process succeeds and detects peers, the system broadcasts the WIFI_P2P_PEERS_CHANGED_ACTION intent, which you can listen for in a broadcast receiver to obtain a list of peers. When your application receives the WIFI_P2P_PEERS_CHANGED_ACTION intent, you can request a list of the discovered peers with requestPeers(). The following code shows how to set this up:
如果发现对等设备的结果是”成功”,系统广播WIFI_P2P_PEERS_CHANGED_ACTION intent,同时监听获取对等列表.当应用收到WIFI_P2P_PEERS_CHANGED_ACTION intent,可以通过requestPeers()请求被发现的对等设备:
PeerListListener myPeerListListener;
...
if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {
// request available peers from the wifi p2p manager. This is an
// asynchronous call and the calling activity is notified with a
// callback on PeerListListener.onPeersAvailable()
if (mManager != null) {
mManager.requestPeers(mChannel, myPeerListListener);
}
}
The requestPeers() method is also asynchronous and can notify your activity when a list of peers is available with onPeersAvailable(), which is defined in the WifiP2pManager.PeerListListener interface. The onPeersAvailable() method provides you with an WifiP2pDeviceList, which you can iterate through to find the peer that you want to connect to.
requestPeers()方法也是异步的并且当可以通过onPeersAvailable()方法给activity提供一个对等设备列表,需要监听WifiP2pManager.PeerListListener接口.onPeersAvailable()方法提供WifiP2pDeviceList 列表,可以通过迭代找到你想要连接的对等设备.
Fetch the list of peers
获取对等设备列表
else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {
// 调用 WifiP2pManager.requestPeers() 获得当前peer设备列表
if (mManager != null) {
mManager.requestPeers(mChannel, new WifiP2pManager.PeerListListener() {
@Override
public void onPeersAvailable(WifiP2pDeviceList peerList) {
Collection<WifiP2pDevice> refreshedPeers = peerList.getDeviceList();
if (!refreshedPeers.equals(peers)) {
peers.clear();
peers.addAll(refreshedPeers);
}
if (peers.size() == 0) {
Log.d(TAG, "No devices found");
return;
}
for(int i = 0; i< peers.size(); i++){
Log.d(TAG,"peers.size() = " + peers.size() + "\n");
Log.d(TAG,"peers.get(0).deviceName: " + peers.get(0).deviceName + "\n");
Log.d(TAG,"peers.get(0).deviceAddress: " + peers.get(0).deviceAddress + "\n");
Log.d(TAG,"peers.get(0).status: " + peers.get(0).status + "\n");
Log.d(TAG,"peers.get(0).toString(): " + peers.get(0).toString() + "\n");
Log.d(TAG,"peers.get(0).isGroupOwner(): " + peers.get(0).isGroupOwner() + "\n");
Log.d(TAG,"peers.get(0).primaryDeviceType: " + peers.get(0).primaryDeviceType + "\n");
}
}
});
}
}
Connect to a peer
When you have figured out the device that you want to connect to after obtaining a list of possible peers, call the connect() method to connect to the device. This method call requires a WifiP2pConfig object that contains the information of the device to connect to. You can be notified of a connection success or failure through the WifiP2pManager.ActionListener. The following code shows you how to create a connection to a desired device:
当在范围内发现一个列表的对等设备可以选择进行连接,调用connect()方法与设备连接.调用这个方法需要WifiP2pConfig对象,该对象包含要连接的设备的信息.可以通过WifiP2pManager.ActionListener来获取连接成功与否.如下: