Android Wi-Fi Direct 开发指南

Android Wi-Fi Direct 开发指南

(本文为Android官方开发文档译文) 

使用Wi-Fi Direct技术可以让具备硬件支持的设备在没有中间接入点的情况下进行直接互联。Android 4.0API版本14)及以后的系统都提供了对Wi-Fi DirectAPI支持。通过对这些API的使用,开发者可以实现支持Wi-Fi Direct的设备间进行相互探测和连接,从而获得较之蓝牙更远距离的高速数据通信效果。对于诸如多人游戏、图片共享等需要在用户之间传输数据的应用而言,这一技术无疑是十分有价值的。

关于Wi-Fi DirectAPI函数的使用需要注意一下几个要点:

·用于探测(discover)对等设备(peers)、向对等设备发起请求(request)以及建立连接(connect)的方法定义在类WifiP2pManager中。

·通过设置监听器(Listener)可以获知WifiP2pManager中方法调用的成功与否。监听器以参数的形式传递给被调用的方法。

·当发现新对等设备或链接丢失的时候,Wi-Fi Direct系统(framework)以意向(Intent)的方式根据检测到的不同事件做出相应的通知。

开发中,以上三点的配合使用相当普遍。简单举个例子,定义一个监听器WifiP2pManager.ActionListener并调用函数discoverPeers(),当相应事件发生的时候就会在ActionListener.onSuccess()ActionListener.onFailure()两个方法中得到通知。当discoverPeers()方法检测到了对等设备列表变化的时候,可以收到由系统广播(broadcast)发出一个WIFI_P2P_PEERS_CHANGED_ACTION意向。

API概述API Overview


WifiP2pManager类所提供的方法可用于操作当前设备中的Wi-Fi硬件,实现诸如探测对、连接对等设备等功能。目前所支持的功能如下:

 1.Wi-Fi Direct Methods

Method

Description

initialize()

Registers the application with the Wi-Fi framework. This must be called before calling any other Wi-Fi Direct 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.

WifiP2pManager中所提供的方法允许特定的监听器作为参数传入,以便Wi-Fi Direct机制能够汇报函数调用的结果。下表中列出了目前支持的监听器接口以及WifiP2pManager中用到相应监听器的方法。

 2. Wi-Fi Direct Listeners

Listener interface

Associated actions

WifiP2pManager.ActionListener

connect(),cancelConnect(),createGroup(),removeGroup(), anddiscoverPeers()

WifiP2pManager.ChannelListener

initialize()

WifiP2pManager.ConnectionInfoListener

requestConnectInfo()

WifiP2pManager.GroupInfoListener

requestGroupInfo()

WifiP2pManager.PeerListListener

requestPeers()

每当有Wi-Fi Direct事件发生的时候(例如,发现新的对等设备、设备的Wi-Fi状态改变等),Wi-Fi Direct API会以广播的形式发出一个意向。而在应用程序中需要做的事情就是创建广播接收器(creating a broadcast receiver)来处理这些意向:

 3. Wi-Fi Direct 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 calldiscoverPeers(). 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 Direct is enabled or disabled on the device.

WIFI_P2P_THIS_DEVICE_CHANGED_ACTION

Broadcast when a device's details have changed, such as the device's name.

创建广播接收器以处理Wi-Fi Direct意向Creating a Broadcast Receiver for Wi-Fi Direct Intents


广播接收器可以让应用程序接收到Android系统所发出的广播意向。这样,应用程序就能对感兴趣的事件做出响应。创建广播接收器的基本步骤如下:

  1. 创建一个继承BroadcastReceiver类的新类。构造函数的参数分别传递WifiP2pManager,WifiP2pManager.Channel,以及在这个广播接收器中需要注册的活动(activity)。这是一种最常见的参数设置模式,它让广播接收器能够引起活动作出更新,同时又能在必要时使用Wi-Fi硬件和通信信道。
  2. 在广播接收器的onReceive()函数中,针对感兴趣的特定意向可以执行相应的动作(actions)。例如,当广播接收器收到了意向WIFI_P2P_PEERS_CHANGED_ACTION,就可以调用requestPeers()方法来列举出当前探测到的对等设备。

下面的代码将展示了如何创建一个特定的广播接收器。例子中的广播接收器以WifiP2pManager对象和一个活动(activity)作为参数,并使用它们针对收到的意向(intent)做出相应的动作(action:

[java]  view plain copy
  1. /** 
  2.  * A BroadcastReceiver that notifies of important Wi-Fi p2p events. 
  3.  */  
  4. public class WiFiDirectBroadcastReceiver extends BroadcastReceiver {  
  5.   
  6.     private WifiP2pManager manager;  
  7.     private Channel channel;  
  8.     private MyWiFiActivity activity;  
  9.   
  10.     public WiFiDirectBroadcastReceiver(WifiP2pManager manager, Channel channel,  
  11.             MyWifiActivity activity) {  
  12.         super();  
  13.         this.manager = manager;  
  14.         this.channel = channel;  
  15.         this.activity = activity;  
  16.     }  
  17.   
  18.     @Override  
  19.     public void onReceive(Context context, Intent intent) {  
  20.         String action = intent.getAction();  
  21.   
  22.         if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) {  
  23.             // Check to see if Wi-Fi is enabled and notify appropriate activity  
  24.         } else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {  
  25.             // Call WifiP2pManager.requestPeers() to get a list of current peers  
  26.         } else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) {  
  27.             // Respond to new connection or disconnections  
  28.         } else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) {  
  29.             // Respond to this device's wifi state changing  
  30.         }  
  31.     }  
  32. }  


 

创建Wi-Fi Direct应用Creating a Wi-Fi Direct Application


完整的Wi-Fi Direct应用包含创建并注册广播接收器、检测对等设备、连接对等设备以及在对等设备间传输数据几个方面的功能。下面将详细介绍如何实现。

准备工作(Initial setup

在使用Wi-Fi Direct API之前,首先要确保应用程序能够访问硬件,并且设备支持Wi-Fi Direct协议。如果这些条件都满足,就可以获取一个WifiP2pManager实例,创建并注册广播接收器,最后就是使用Wi-Fi Direct API了。

  1. 在Android manifest文件中加入以下内容,允许使用Wi-Fi设备上的硬件并声明应用程序正确支持了调用API所需的最低SDK版本
[html]  view plain copy
  1. <uses-sdk android:minSdkVersion="14" />  
  2.   
  3. <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />  
  4.   
  5. <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />  
  6.   
  7. <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />  
  8.   
  9. <uses-permission android:name="android.permission.INTERNET" />  
  10.   
  11. <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />  


检查Wi-Fi Direct支持并已开启。推荐在广播接收器收到WIFI_P2P_STATE_CHANGED_ACTION意向的时候进行检测。检测结果需要通告相应的活动并做出处理:

[java]  view plain copy
  1. @Override  
  2.   
  3. public void onReceive(Context context, Intent intent) {  
  4.   
  5.     ...  
  6.   
  7.     String action = intent.getAction();  
  8.   
  9.     if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) {  
  10.   
  11.         int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1);  
  12.   
  13.         if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) {  
  14.   
  15.             // Wifi Direct is enabled  
  16.   
  17.         } else {  
  18.   
  19.             // Wi-Fi Direct is not enabled  
  20.   
  21.         }  
  22.   
  23.     }  
  24.   
  25.     ...  
  26.   
  27. }  


在活动的onCreate()方法中获取WifiP2pManager对象的一个实例,通过该对象的initialize()方法向Wi-Fi Direct系统注册当前的应用程序。注册成功后,会返回一个WifiP2pManager.Channel,通过它,应用程序就能和Wi-Fi Direct系统交互。WifiP2pManagerWifiP2pManager.Channel对象以及一个活动的引用最后都被作为参数传递给自定义的广播接收器。这样,该活动就能够响应广播接收器的通知并作出相应的更新。当然,这样做也使程序具备了操纵设备Wi-Fi状态的能力:

[java]  view plain copy
  1. WifiP2pManager mManager;  
  2.   
  3. Channel mChannel;  
  4.   
  5. BroadcastReceiver mReceiver;  
  6.   
  7. ...  
  8.   
  9. @Override  
  10.   
  11. protected void onCreate(Bundle savedInstanceState){  
  12.   
  13.     ...  
  14.   
  15.     mManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);  
  16.   
  17.     mChannel = mManager.initialize(this, getMainLooper(), null);  
  18.   
  19.     mReceiver = new WiFiDirectBroadcastReceiver(manager, channel, this);  
  20.   
  21.     ...  
  22.   
  23. }  


创建一个意向过滤器(intent filter),其中添加的意向种类和广播接收器中的保持一致:

[java]  view plain copy
  1. IntentFilter mIntentFilter;  
  2.   
  3. ...  
  4.   
  5. @Override  
  6.   
  7. protected void onCreate(Bundle savedInstanceState){  
  8.   
  9.     ...  
  10.   
  11.     mIntentFilter = new IntentFilter();  
  12.   
  13.     mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);  
  14.   
  15.     mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);  
  16.   
  17.     mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);  
  18.   
  19.     mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);  
  20.   
  21.     ...  
  22.   
  23. }  


在活动的onResume()方法中注册广播接收器,并在活动的onPause()方法中注销它:

[java]  view plain copy
  1. /* register the broadcast receiver with the intent values to be matched */  
  2. @Override  
  3. protected void onResume() {  
  4.     super.onResume();  
  5.     registerReceiver(mReceiver, mIntentFilter);  
  6. }  
  7. /* unregister the broadcast receiver */  
  8. @Override  
  9. protected void onPause() {  
  10.     super.onPause();  
  11.     unregisterReceiver(mReceiver);  
  12. }  


一旦成功获取WifiP2pManager.Channel并创建了广播接收器,应用程序就已经具备了使用Wi-Fi Direct相关函数和接收Wi-Fi Direct意向的能力。尽管放手使用WifiP2pManager为你提供的方法,让程序也拥有Wi-Fi Direct的特殊能力吧!

下一节将讲述如何实现一些常见的动作,例如探测并连接到对等设备。

 

探测对等设备(Discovering peers

调用discoverPeers()函数可以探测到有效距离内的对等设备。它是一个异步函数,调用成功与否会在程序所创建WifiP2pManager.ActionListener监听器的onSuccess()onFailure()中给出通知。值得注意的是,onSuccess()方法只会对成功探测到对等设备这一事件做出通知,而并不会提供任何关于已发现的对等设备的具体信息:

[java]  view plain copy
  1. manager.discoverPeers(channel, new WifiP2pManager.ActionListener() {  
  2.     @Override  
  3.     public void onSuccess() {  
  4.         ...  
  5.     }  
  6.   
  7.     @Override  
  8.     public void onFailure(int reasonCode) {  
  9.         ...  
  10.     }  
  11. });  


当成功检测到对等设备存在的时候,系统会广播WIFI_P2P_PEERS_CHANGED_ACTION意向。程序接收到该意向后,通过调用requestPeers()方法,就能获得已经探测到对等设备的清单。下面代码将展示如何实现这一过程:

[java]  view plain copy
  1. PeerListListener myPeerListListener;  
  2. ...  
  3. if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {  
  4.   
  5.     // request available peers from the wifi p2p manager. This is an  
  6.     // asynchronous call and the calling activity is notified with a  
  7.     // callback on PeerListListener.onPeersAvailable()  
  8.     if (manager != null) {  
  9.         manager.requestPeers(channel, myPeerListListener);  
  10.     }  
  11. }  


requestPeers()方法同样是一个异步函数,当它准备好一份对等设备列表的时候,就会通知监听器WifiP2pManager.PeerListListener中定义的onPeersAvailable()方法。而onPeersAvailable()方法中所能获取到的对等设备列表以WifiP2pDeviceList形式存储,通过遍历这个列表可以选择出希望连接的设备。

连接对等设备(Connecting to peers

确定了要连接的设备,还需调用connect()方法建立连接。该方法的其中一个参数是WifiP2pConfig对象,它提供了要连接设备的相关信息。连接的成功与否需要通过监听器WifiP2pManager.ActionListener获取通知。下面的代码将示范如何建立设备连接:

[java]  view plain copy
  1. //obtain a peer from the WifiP2pDeviceList  
  2. WifiP2pDevice device;  
  3. WifiP2pConfig config = new WifiP2pConfig();  
  4. config.deviceAddress = device.deviceAddress;  
  5. manager.connect(channel, config, new ActionListener() {  
  6.   
  7.     @Override  
  8.     public void onSuccess() {  
  9.         //success logic  
  10.     }  
  11.   
  12.     @Override  
  13.     public void onFailure(int reason) {  
  14.         //failure logic  
  15.     }  
  16. });  



传输数据(Transferring data

连接一旦建立成功,数据传输也就是顺理成章的事情。以下是通过socket发送数据的基本步骤:

  1. 创建ServerSocket。它将被用于监听特定端口,等待客户端发起的连接请求。该操作需要在后台线程中实现。
  2. 创建客户端Socket。客户端通过ServerSocket对应的IP和端口连接到服务设备。
  3. 客户端向服务器发生数据。客户socket成功连接到服务socket后,就能以字节流的形式向服务器发生数据了。
  4. 服务器socket通过accept()方法等待客户端数据连接的到来。该方法在收到客户端数据之前一直处于阻塞状态。因此,需要在单独的线程中调用它。数据连接一旦建立,服务设备就能接收到客户端的数据。这时要做的就是施以相应的动作,例如将数据保存到文件,或者是直接显示到用户界面上,等等。

以下代码修改自SDK自带的示例Wi-Fi Direct Demo。它演示了如何建立一对客户端-服务器连接,并由客户端向服务器发送JPEG图片。若需完整的演示工程,只需编译并运行SDK示例Wi-Fi Direct Demo即可。

[java]  view plain copy
  1. public static class FileServerAsyncTask extends AsyncTask {  
  2.   
  3.    
  4.   
  5.     private Context context;  
  6.   
  7.     private TextView statusText;  
  8.   
  9.    
  10.   
  11.     public FileServerAsyncTask(Context context, View statusText) {  
  12.   
  13.         this.context = context;  
  14.   
  15.         this.statusText = (TextView) statusText;  
  16.   
  17.     }  
  18.   
  19.    
  20.   
  21.     @Override  
  22.   
  23.     protected String doInBackground(Void... params) {  
  24.   
  25.         try {  
  26.   
  27.    
  28.   
  29.             /** 
  30.  
  31.              * Create a server socket and wait for client connections. This 
  32.  
  33.              * call blocks until a connection is accepted from a client 
  34.  
  35.              */  
  36.   
  37.             ServerSocket serverSocket = new ServerSocket(8888);  
  38.   
  39.             Socket client = serverSocket.accept();  
  40.   
  41.    
  42.   
  43.             /** 
  44.  
  45.              * If this code is reached, a client has connected and transferred data 
  46.  
  47.              * Save the input stream from the client as a JPEG file 
  48.  
  49.              */  
  50.   
  51.             final File f = new File(Environment.getExternalStorageDirectory() + "/"  
  52.   
  53.                     + context.getPackageName() + "/wifip2pshared-" + System.currentTimeMillis()  
  54.   
  55.                     + ".jpg");  
  56.   
  57.    
  58.   
  59.             File dirs = new File(f.getParent());  
  60.   
  61.             if (!dirs.exists())  
  62.   
  63.                 dirs.mkdirs();  
  64.   
  65.             f.createNewFile();  
  66.   
  67.             InputStream inputstream = client.getInputStream();  
  68.   
  69.             copyFile(inputstream, new FileOutputStream(f));  
  70.   
  71.             serverSocket.close();  
  72.   
  73.             return f.getAbsolutePath();  
  74.   
  75.         } catch (IOException e) {  
  76.   
  77.             Log.e(WiFiDirectActivity.TAG, e.getMessage());  
  78.   
  79.             return null;  
  80.   
  81.         }  
  82.   
  83.     }  
  84.   
  85.    
  86.   
  87.     /** 
  88.  
  89.      * Start activity that can handle the JPEG image 
  90.  
  91.      */  
  92.   
  93.     @Override  
  94.   
  95.     protected void onPostExecute(String result) {  
  96.   
  97.         if (result != null) {  
  98.   
  99.             statusText.setText("File copied - " + result);  
  100.   
  101.             Intent intent = new Intent();  
  102.   
  103.             intent.setAction(android.content.Intent.ACTION_VIEW);  
  104.   
  105.             intent.setDataAndType(Uri.parse("file://" + result), "image/*");  
  106.   
  107.             context.startActivity(intent);  
  108.   
  109.         }  
  110.   
  111.     }  
  112.   
  113. }  


On the client, connect to the server socket with a client socket and transfer data. This example transfers a JPEG file on the client device's file system.

[java]  view plain copy
  1. Context context = this.getApplicationContext();  
  2.   
  3. String host;  
  4.   
  5. int port;  
  6.   
  7. int len;  
  8.   
  9. Socket socket = new Socket();  
  10.   
  11. byte buf[]  = new byte[1024];  
  12.   
  13. ...  
  14.   
  15. try {  
  16.   
  17.     /** 
  18.  
  19.      * Create a client socket with the host, 
  20.  
  21.      * port, and timeout information. 
  22.  
  23.      */  
  24.   
  25.     socket.bind(null);  
  26.   
  27.     socket.connect((new InetSocketAddress(host, port)), 500);  
  28.   
  29.    
  30.   
  31.     /** 
  32.  
  33.      * Create a byte stream from a JPEG file and pipe it to the output stream 
  34.  
  35.      * of the socket. This data will be retrieved by the server device. 
  36.  
  37.      */  
  38.   
  39.     OutputStream outputStream = socket.getOutputStream();  
  40.   
  41.     ContentResolver cr = context.getContentResolver();  
  42.   
  43.     InputStream inputStream = null;  
  44.   
  45.     inputStream = cr.openInputStream(Uri.parse("path/to/picture.jpg"));  
  46.   
  47.     while ((len = inputStream.read(buf)) != -1) {  
  48.   
  49.         outputStream.write(buf, 0, len);  
  50.   
  51.     }  
  52.   
  53.     outputStream.close();  
  54.   
  55.     inputStream.close();  
  56.   
  57. catch (FileNotFoundException e) {  
  58.   
  59.     //catch logic  
  60.   
  61. catch (IOException e) {  
  62.   
  63.     //catch logic  
  64.   
  65. }  
  66.   
  67.    
  68.   
  69. /** 
  70.  
  71.  * Clean up any open sockets when done 
  72.  
  73.  * transferring or if an exception occurred. 
  74.  
  75.  */  
  76.   
  77. finally {  
  78.   
  79.     if (socket != null) {  
  80.   
  81.         if (socket.isConnected()) {  
  82.   
  83.             try {  
  84.   
  85.                 socket.close();  
  86.   
  87.             } catch (IOException e) {  
  88.   
  89.                 //catch logic  
  90.   
  91.             }  
  92.   
  93.         }  
  94.   
  95.     }  
  96.   
  97. }  

 

示例代码下载:

http://download.csdn.net/detail/yichigo/5516627

以上示例代码来源于android sdk中自带的例子程序

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值