1page.title=Connecting with Wi-Fi Direct 2parent.title=Connecting Devices Wirelessly 3parent.link=index.html 4 5trainingnavtop=true 6previous.title=Using Network Service Discovery 7previous.link=nsd.html 8next.title=Service Discovery with Wi-Fi Direct 9next.link=nsd-wifi-direct.html 10 11@jd:body 12 13<div id="tb-wrapper"> 14 <div id="tb"> 15 <h2>This lesson teaches you how to</h2> 16 <ol> 17 <li><a href="#permissions">Set Up Application Permissions</a></li> 18 <li><a href="#receiver">Set Up the Broadcast Receiver and Peer-to-Peer 19 Manager</a></li> 20 <li><a href="#discover">Initiate Peer Discovery</a></li> 21 <li><a href="#fetch">Fetch the List of Peers</a></li> 22 <li><a href="#connect">Connect to a Peer</a></li> 23 </ol> 24 </div> 25</div> 26 27<p>The Wi-Fi Direct™ APIs allow applications to connect to nearby devices without 28needing to connect to a network or hotspot. This allows your application to quickly 29find and interact with nearby devices, at a range beyond the capabilities of Bluetooth. 30</p> 31<p> 32This lesson shows you how to find and connect to nearby devices using Wi-Fi Direct. 33</p> 34<h2 id="permissions">Set Up Application Permissions</h2> 35<p>In order to use Wi-Fi Direct, add the {@link 36android.Manifest.permission#CHANGE_WIFI_STATE}, {@link 37android.Manifest.permission#ACCESS_WIFI_STATE}, 38and {@link android.Manifest.permission#INTERNET} 39permissions to your manifest. Wi-Fi Direct doesn't require an internet connection, 40but it does use standard Java sockets, which require the {@link 41android.Manifest.permission#INTERNET} permission. 42So you need the following permissions to use Wi-Fi Direct.</p> 43 44<pre> 45<manifest xmlns:android="http://schemas.android.com/apk/res/android" 46 package="com.example.android.nsdchat" 47 ... 48 49 <uses-permission 50 android:required="true" 51 android:name="android.permission.ACCESS_WIFI_STATE"/> 52 <uses-permission 53 android:required="true" 54 android:name="android.permission.CHANGE_WIFI_STATE"/> 55 <uses-permission 56 android:required="true" 57 android:name="android.permission.INTERNET"/> 58 ... 59</pre> 60 61<h2 id="receiver">Set Up a Broadcast Receiver and Peer-to-Peer Manager</h2> 62<p>To use Wi-Fi Direct, you need to listen for broadcast intents that tell your 63application when certain events have occurred. In your application, instantiate 64an {@link 65android.content.IntentFilter} and set it to listen for the following:</p> 66<dl> 67 <dt>{@link android.net.wifi.p2p.WifiP2pManager#WIFI_P2P_STATE_CHANGED_ACTION}</dt> 68 <dd>Indicates whether Wi-Fi Peer-To-Peer (P2P) is enabled</dd> 69 <dt>{@link android.net.wifi.p2p.WifiP2pManager#WIFI_P2P_PEERS_CHANGED_ACTION}</dt> 70 <dd>Indicates that the available peer list has changed.</dd> 71 <dt>{@link android.net.wifi.p2p.WifiP2pManager#WIFI_P2P_CONNECTION_CHANGED_ACTION}</dt> 72 <dd>Indicates the state of Wi-Fi P2P connectivity has changed.</dd> 73 <dt>{@link android.net.wifi.p2p.WifiP2pManager#WIFI_P2P_THIS_DEVICE_CHANGED_ACTION}</dt> 74 <dd>Indicates this device's configuration details have changed.</dd> 75<pre> 76private final IntentFilter intentFilter = new IntentFilter(); 77... 78@Override 79public void onCreate(Bundle savedInstanceState) { 80 super.onCreate(savedInstanceState); 81 setContentView(R.layout.main); 82 83 // Indicates a change in the Wi-Fi Peer-to-Peer status. 84 intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION); 85 86 // Indicates a change in the list of available peers. 87 intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION); 88 89 // Indicates the state of Wi-Fi P2P connectivity has changed. 90 intentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION); 91 92 // Indicates this device's details have changed. 93 intentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION); 94 95 ... 96} 97</pre> 98 99 <p>At the end of the {@link android.app.Activity#onCreate onCreate()} method, get an instance of the {@link 100android.net.wifi.p2p.WifiP2pManager}, and call its {@link 101android.net.wifi.p2p.WifiP2pManager#initialize(Context, Looper, WifiP2pManager.ChannelListener) initialize()} 102method. This method returns a {@link 103android.net.wifi.p2p.WifiP2pManager.Channel} object, which you'll use later to 104connect your app to the Wi-Fi Direct Framework.</p> 105 106<pre> 107@Override 108 109Channel mChannel; 110 111public void onCreate(Bundle savedInstanceState) { 112 .... 113 mManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE); 114 mChannel = mManager.initialize(this, getMainLooper(), null); 115} 116</pre> 117<p>Now create a new {@link 118android.content.BroadcastReceiver} class that you'll use to listen for changes 119to the System's Wi-Fi P2P state. In the {@link 120android.content.BroadcastReceiver#onReceive(Context, Intent) onReceive()} 121method, add a condition to handle each P2P state change listed above.</p> 122 123<pre> 124 125 @Override 126 public void onReceive(Context context, Intent intent) { 127 String action = intent.getAction(); 128 if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) { 129 // Determine if Wifi Direct mode is enabled or not, alert 130 // the Activity. 131 int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1); 132 if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) { 133 activity.setIsWifiP2pEnabled(true); 134 } else { 135 activity.setIsWifiP2pEnabled(false); 136 } 137 } else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) { 138 139 // The peer list has changed! We should probably do something about 140 // that. 141 142 } else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) { 143 144 // Connection state changed! We should probably do something about 145 // that. 146 147 } else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) { 148 DeviceListFragment fragment = (DeviceListFragment) activity.getFragmentManager() 149 .findFragmentById(R.id.frag_list); 150 fragment.updateThisDevice((WifiP2pDevice) intent.getParcelableExtra( 151 WifiP2pManager.EXTRA_WIFI_P2P_DEVICE)); 152 153 } 154 } 155</pre> 156 157<p>Finally, add code to register the intent filter and broadcast receiver when 158your main activity is active, and unregister them when the activity is paused. 159The best place to do this is the {@link android.app.Activity#onResume()} and 160{@link android.app.Activity#onPause()} methods. 161 162<pre> 163 /** register the BroadcastReceiver with the intent values to be matched */ 164 @Override 165 public void onResume() { 166 super.onResume(); 167 receiver = new WiFiDirectBroadcastReceiver(mManager, mChannel, this); 168 registerReceiver(receiver, intentFilter); 169 } 170 171 @Override 172 public void onPause() { 173 super.onPause(); 174 unregisterReceiver(receiver); 175 } 176</pre> 177 178 179<h2 id="discover">Initiate Peer Discovery</h2> 180<p>To start searching for nearby devices with Wi-Fi Direct, call {@link 181android.net.wifi.p2p.WifiP2pManager#discoverPeers(WifiP2pManager.Channel, 182WifiP2pManager.ActionListener) discoverPeers()}. This method takes the 183following arguments:</p> 184<ul> 185 <li>The {@link android.net.wifi.p2p.WifiP2pManager.Channel} you 186 received back when you initialized the peer-to-peer mManager</li> 187 <li>An implementation of {@link android.net.wifi.p2p.WifiP2pManager.ActionListener} with methods 188 the system invokes for successful and unsuccessful discovery.</li> 189</ul> 190 191<pre> 192mManager.discoverPeers(mChannel, new WifiP2pManager.ActionListener() { 193 194 @Override 195 public void onSuccess() { 196 // Code for when the discovery initiation is successful goes here. 197 // No services have actually been discovered yet, so this method 198 // can often be left blank. Code for peer discovery goes in the 199 // onReceive method, detailed below. 200 } 201 202 @Override 203 public void onFailure(int reasonCode) { 204 // Code for when the discovery initiation fails goes here. 205 // Alert the user that something went wrong. 206 } 207}); 208</pre> 209 210<p>Keep in mind that this only <em>initiates</em> peer discovery. The 211{@link android.net.wifi.p2p.WifiP2pManager#discoverPeers(WifiP2pManager.Channel, 212WifiP2pManager.ActionListener) discoverPeers()} method starts the discovery process and then 213immediately returns. The system notifies you if the peer discovery process is 214successfully initiated by calling methods in the provided action listener. 215Also, discovery will remain active until a connection is initiated or a P2P group is 216formed.</p> 217 218<h2 id="fetch">Fetch the List of Peers</h2> 219<p>Now write the code that fetches and processes the list of peers. First 220implement the {@link android.net.wifi.p2p.WifiP2pManager.PeerListListener} 221interface, which provides information about the peers that Wi-Fi Direct has 222detected. The following code snippet illustrates this.</p> 223 224<pre> 225 private List<WifiP2pDevice> peers = new ArrayList<WifiP2pDevice>(); 226 ... 227 228 private PeerListListener peerListListener = new PeerListListener() { 229 @Override 230 public void onPeersAvailable(WifiP2pDeviceList peerList) { 231 232 // Out with the old, in with the new. 233 peers.clear(); 234 peers.addAll(peerList.getDeviceList()); 235 236 // If an AdapterView is backed by this data, notify it 237 // of the change. For instance, if you have a ListView of available 238 // peers, trigger an update. 239 ((WiFiPeerListAdapter) getListAdapter()).notifyDataSetChanged(); 240 if (peers.size() == 0) { 241 Log.d(WiFiDirectActivity.TAG, "No devices found"); 242 return; 243 } 244 } 245 } 246</pre> 247 248<p>Now modify your broadcast receiver's {@link 249android.content.BroadcastReceiver#onReceive(Context, Intent) onReceive()} 250method to call {@link android.net.wifi.p2p.WifiP2pManager#requestPeers 251requestPeers()} when an intent with the action {@link 252android.net.wifi.p2p.WifiP2pManager#WIFI_P2P_PEERS_CHANGED_ACTION} is received. You 253need to pass this listener into the receiver somehow. One way is to send it 254as an argument to the broadcast receiver's constructor. 255</p> 256 257<pre> 258public void onReceive(Context context, Intent intent) { 259 ... 260 else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) { 261 262 // Request available peers from the wifi p2p manager. This is an 263 // asynchronous call and the calling activity is notified with a 264 // callback on PeerListListener.onPeersAvailable() 265 if (mManager != null) { 266 mManager.requestPeers(mChannel, peerListListener); 267 } 268 Log.d(WiFiDirectActivity.TAG, "P2P peers changed"); 269 }... 270} 271</pre> 272 273<p>Now, an intent with the action {@link 274android.net.wifi.p2p.WifiP2pManager#WIFI_P2P_PEERS_CHANGED_ACTION} intent will 275trigger a request for an updated peer list. </p> 276 277<h2 id="connect">Connect to a Peer</h2> 278<p>In order to connect to a peer, create a new {@link 279android.net.wifi.p2p.WifiP2pConfig} object, and copy data into it from the 280{@link android.net.wifi.p2p.WifiP2pDevice} representing the device you want to 281connect to. Then call the {@link 282android.net.wifi.p2p.WifiP2pManager#connect(WifiP2pManager.Channel, 283WifiP2pConfig, WifiP2pManager.ActionListener) connect()} 284method.</p> 285 286<pre> 287 @Override 288 public void connect() { 289 // Picking the first device found on the network. 290 WifiP2pDevice device = peers.get(0); 291 292 WifiP2pConfig config = new WifiP2pConfig(); 293 config.deviceAddress = device.deviceAddress; 294 config.wps.setup = WpsInfo.PBC; 295 296 mManager.connect(mChannel, config, new ActionListener() { 297 298 @Override 299 public void onSuccess() { 300 // WiFiDirectBroadcastReceiver will notify us. Ignore for now. 301 } 302 303 @Override 304 public void onFailure(int reason) { 305 Toast.makeText(WiFiDirectActivity.this, "Connect failed. Retry.", 306 Toast.LENGTH_SHORT).show(); 307 } 308 }); 309 } 310</pre> 311 312<p>The {@link android.net.wifi.p2p.WifiP2pManager.ActionListener} implemented in 313this snippet only notifies you when the <em>initiation</em> succeeds or fails. 314To listen for <em>changes</em> in connection state, implement the {@link 315android.net.wifi.p2p.WifiP2pManager.ConnectionInfoListener} interface. Its {@link 316android.net.wifi.p2p.WifiP2pManager.ConnectionInfoListener#onConnectionInfoAvailable(WifiP2pInfo) 317onConnectionInfoAvailable()} 318callback will notify you when the state of the connection changes. In cases 319where multiple devices are going to be connected to a single device (like a game with 3203 or more players, or a chat app), one device will be designated the "group 321owner".</p> 322 323<pre> 324 @Override 325 public void onConnectionInfoAvailable(final WifiP2pInfo info) { 326 327 // InetAddress from WifiP2pInfo struct. 328 InetAddress groupOwnerAddress = info.groupOwnerAddress.getHostAddress()); 329 330 // After the group negotiation, we can determine the group owner. 331 if (info.groupFormed && info.isGroupOwner) { 332 // Do whatever tasks are specific to the group owner. 333 // One common case is creating a server thread and accepting 334 // incoming connections. 335 } else if (info.groupFormed) { 336 // The other device acts as the client. In this case, 337 // you'll want to create a client thread that connects to the group 338 // owner. 339 } 340 } 341</pre> 342 343<p>Now go back to the {@link 344android.content.BroadcastReceiver#onReceive(Context, Intent) onReceive()} method of the broadcast receiver, and modify the section 345that listens for a {@link 346android.net.wifi.p2p.WifiP2pManager#WIFI_P2P_CONNECTION_CHANGED_ACTION} intent. 347When this intent is received, call {@link 348android.net.wifi.p2p.WifiP2pManager#requestConnectionInfo(WifiP2pManager.Channel, 349WifiP2pManager.ConnectionInfoListener) requestConnectionInfo()}. This is an 350asynchronous call, so results will be received by the connection info listener 351you provide as a parameter. 352 353<pre> 354 ... 355 } else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) { 356 357 if (mManager == null) { 358 return; 359 } 360 361 NetworkInfo networkInfo = (NetworkInfo) intent 362 .getParcelableExtra(WifiP2pManager.EXTRA_NETWORK_INFO); 363 364 if (networkInfo.isConnected()) { 365 366 // We are connected with the other device, request connection 367 // info to find group owner IP 368 369 mManager.requestConnectionInfo(mChannel, connectionListener); 370 } 371 ... 372</pre> 373