summaryrefslogtreecommitdiffstats
path: root/docs/html/guide/topics/wireless
diff options
context:
space:
mode:
Diffstat (limited to 'docs/html/guide/topics/wireless')
-rw-r--r--docs/html/guide/topics/wireless/bluetooth.jd156
-rw-r--r--docs/html/guide/topics/wireless/wifip2p.jd611
2 files changed, 749 insertions, 18 deletions
diff --git a/docs/html/guide/topics/wireless/bluetooth.jd b/docs/html/guide/topics/wireless/bluetooth.jd
index 0af1d2c..0567799 100644
--- a/docs/html/guide/topics/wireless/bluetooth.jd
+++ b/docs/html/guide/topics/wireless/bluetooth.jd
@@ -29,6 +29,7 @@ other devices</li>
<li><a href="#Profiles">Working with Profiles</a>
<ol>
<li><a href="#AT-Commands">Vendor-specific AT commands</a>
+ <li><a href="#HDP">Health Device Profile</a>
</ol></li>
</ol>
@@ -43,6 +44,7 @@ other devices</li>
<h2>Related samples</h2>
<ol>
<li><a href="{@docRoot}resources/samples/BluetoothChat/index.html">Bluetooth Chat</a></li>
+ <li><a href="{@docRoot}resources/samples/BluetoothHDP/index.html">Bluetooth HDP (Health Device Profile)</a></li>
</ol>
</div>
@@ -132,11 +134,27 @@ Headset and Hands-Free (v1.5) profiles.</dd>
audio can be streamed from one device to another over a Bluetooth connection.
"A2DP" stands for Advanced Audio Distribution Profile.</dd>
-<dt>{@link android.bluetooth.BluetoothProfile.ServiceListener}</dt>
+<dt>{@link android.bluetooth.BluetoothHealth}</dt>
+<dd> Represents a Health Device Profile proxy that controls the Bluetooth service.</dd>
+
+<dt>{@link android.bluetooth.BluetoothHealthCallback}</dt>
+
+<dd>An abstract class that you use to implement {@link
+android.bluetooth.BluetoothHealth} callbacks. You must extend this class and
+implement the callback methods to receive updates about changes in the
+application’s registration state and Bluetooth channel state.</dd>
+
+<dt>{@link android.bluetooth.BluetoothHealthAppConfiguration}</dt>
+
+<dd>Represents an application configuration that the Bluetooth Health third-party
+application registers to communicate with a remote Bluetooth health
+device.</dd>
+
+<dt>{@link android.bluetooth.BluetoothProfile.ServiceListener}</dt>
<dd>An interface that notifies {@link android.bluetooth.BluetoothProfile} IPC
clients when they have been connected to or disconnected from the service (that
-is, the internal service that runs a particular profile). </dd>
+is, the internal service that runs a particular profile). </dd>
</dl>
@@ -231,12 +249,20 @@ if (!mBluetoothAdapter.isEnabled()) {
<p>A dialog will appear requesting user permission to enable Bluetooth, as shown
in Figure 1. If the user responds "Yes," the system will begin to enable Bluetooth
and focus will return to your application once the process completes (or fails).</p>
-<p>If enabling Bluetooth succeeds, your Activity will receive the {@link
+
+<p>The {@code REQUEST_ENABLE_BT} constant passed to {@link
+android.app.Activity#startActivityForResult(Intent,int) startActivityForResult()} is a locally
+defined integer (which must be greater than 0), that the system passes back to you in your
+{@link
+android.app.Activity#onActivityResult(int,int,Intent) onActivityResult()} implementation as the
+<code>requestCode</code> parameter.</p>
+
+<p>If enabling Bluetooth succeeds, your activity receives the {@link
android.app.Activity#RESULT_OK} result code in the {@link
android.app.Activity#onActivityResult(int,int,Intent) onActivityResult()}
callback. If Bluetooth was not enabled
-due to an error (or the user responded "No") then the result code will be {@link
-android.app.Activity#RESULT_CANCELED}.</p>
+due to an error (or the user responded "No") then the result code is {@link
+android.app.Activity#RESULT_CANCELED}.</p>
</li>
</ol>
@@ -413,11 +439,11 @@ startActivity(discoverableIntent);
<p>A dialog will be displayed, requesting user permission to make the device
discoverable, as shown in Figure 2. If the user responds "Yes," then the device
-will become discoverable for the specified amount of time. Your Activity will
+will become discoverable for the specified amount of time. Your activity will
then receive a call to the {@link android.app.Activity#onActivityResult(int,int,Intent)
onActivityResult())} callback, with the result code equal to the duration that the device
is discoverable. If the user responded "No" or if an error occurred, the result code will
-be Activity.RESULT_CANCELLED.</p>
+be {@link android.app.Activity#RESULT_CANCELED}.</p>
<p class="note"><strong>Note:</strong> If Bluetooth has not been enabled on the device,
then enabling device discoverability will automatically enable Bluetooth.</p>
@@ -550,7 +576,7 @@ socket.</p>
</ol>
<p>The {@link android.bluetooth.BluetoothServerSocket#accept()} call should not
-be executed in the main Activity UI thread because it is a blocking call and
+be executed in the main activity UI thread because it is a blocking call and
will prevent any other interaction with the application. It usually makes
sense to do all work with a {@link android.bluetooth.BluetoothServerSocket} or {@link
android.bluetooth.BluetoothSocket} in a new
@@ -678,7 +704,7 @@ android.bluetooth.BluetoothSocket#connect()} method times out (after about
12 seconds), then it will throw an exception.</p>
<p>Because {@link
android.bluetooth.BluetoothSocket#connect()} is a blocking call, this connection
-procedure should always be performed in a thread separate from the main Activity
+procedure should always be performed in a thread separate from the main activity
thread.</p>
<p class="note">Note: You should always ensure that the device is not performing
device discovery when you call {@link
@@ -820,7 +846,7 @@ private class ConnectedThread extends Thread {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
- // Send the obtained bytes to the UI Activity
+ // Send the obtained bytes to the UI activity
mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
.sendToTarget();
} catch (IOException e) {
@@ -829,14 +855,14 @@ private class ConnectedThread extends Thread {
}
}
- /* Call this from the main Activity to send data to the remote device */
+ /* Call this from the main activity to send data to the remote device */
public void write(byte[] bytes) {
try {
mmOutStream.write(bytes);
} catch (IOException e) { }
}
- /* Call this from the main Activity to shutdown the connection */
+ /* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
mmSocket.close();
@@ -848,12 +874,12 @@ private class ConnectedThread extends Thread {
<p>The constructor acquires the necessary streams and once executed, the thread
will wait for data to come through the InputStream. When {@link
java.io.InputStream#read(byte[])} returns with
-bytes from the stream, the data is sent to the main Activity using a member
+bytes from the stream, the data is sent to the main activity using a member
Handler from the parent class. Then it goes back and waits for more bytes from
the stream.</p>
<p>Sending outgoing data is as simple as calling the thread's
-<code>write()</code> method from the main Activity and passing in the bytes to
+<code>write()</code> method from the main activity and passing in the bytes to
be sent. This method then simply calls {@link
java.io.OutputStream#write(byte[])} to send the data to the remote device.</p>
@@ -889,7 +915,7 @@ Bluetooth Headset Service via interprocess communication (<a
href="{@docRoot}guide/topics/fundamentals/processes-and-threads.html#IPC">IPC</a
>). This includes both Bluetooth Headset and Hands-Free (v1.5) profiles. The
{@link android.bluetooth.BluetoothHeadset} class includes support for AT commands.
-For more discussion of this topic, see <a href="#AT-Commands">Vendor-specific AT commands</a></li>
+For more discussion of this topic, see <a href="#AT-Commands">Vendor-specific AT commands</a></li>
<li><strong>A2DP</strong>. The Advanced Audio Distribution Profile (A2DP)
profile defines how high quality audio can be streamed from one device to
@@ -897,13 +923,25 @@ another over a Bluetooth connection. Android provides the {@link
android.bluetooth.BluetoothA2dp} class, which is a proxy for controlling
the Bluetooth A2DP Service via IPC.</li>
+ <li><strong>Health Device</strong>. Android 4.0 (API level 14) introduces
+support for the Bluetooth Health Device Profile (HDP). This lets you create
+applications that use Bluetooth to communicate with health devices that support
+Bluetooth, such as heart-rate monitors, blood meters, thermometers, scales, and
+so on. For a list of supported devices and their corresponding device data
+specialization codes, refer to <strong>Bluetooth Assigned Numbers</strong> at <a
+href="http://www.bluetooth.org">www.bluetooth.org</a>. Note that these values
+are also referenced in the ISO/IEEE 11073-20601 [7] specification as
+MDC_DEV_SPEC_PROFILE_* in the Nomenclature Codes Annex. For more discussion of
+HDP, see <a href="#HDP">Health Device Profile</a>.</li>
+
</ul>
<p>Here are the basic steps for working with a profile:</p>
<ol>
- <li>Get the default adapter, as described in <a href="{@docRoot}guide/topics/wireless/bluetooth.
-html#SettingUp">Setting Up Bluetooth</a>.</li>
+ <li>Get the default adapter, as described in
+ <a href="{@docRoot}guide/topics/wireless/bluetooth.html#SettingUp">Setting Up
+ Bluetooth</a>.</li>
<li>Use {@link
android.bluetooth.BluetoothAdapter#getProfileProxy(android.content.Context,
@@ -925,7 +963,9 @@ to the profile proxy object.</li>
state of the connection and perform other operations that are relevant to that
profile.</li>
</ol>
-<p> For example, this code snippet shows how to connect to a {@link android.bluetooth.BluetoothHeadset} proxy object so that you can control the
+
+<p> For example, this code snippet shows how to connect to a {@link
+android.bluetooth.BluetoothHeadset} proxy object so that you can control the
Headset profile:</p>
<pre>BluetoothHeadset mBluetoothHeadset;
@@ -955,6 +995,8 @@ private BluetoothProfile.ServiceListener mProfileListener = new BluetoothProfile
mBluetoothAdapter.closeProfileProxy(mBluetoothHeadset);
</pre>
+
+
<h3 id="AT-Commands">Vendor-specific AT commands</h3>
<p>Starting in Android 3.0, applications can register to receive system
@@ -964,3 +1006,81 @@ broadcasts that indicate a connected device's battery level and could notify the
user or take other action as needed. Create a broadcast receiver for the {@link
android.bluetooth.BluetoothHeadset#ACTION_VENDOR_SPECIFIC_HEADSET_EVENT} intent
to handle vendor-specific AT commands for the headset.</p>
+
+<h3 id="HDP">Health Device Profile</h3>
+
+<p>Android 4.0 (API level 14) introduces support for the Bluetooth Health Device
+Profile (HDP). This lets you create applications that use Bluetooth to
+communicate with health devices that support Bluetooth, such as heart-rate
+monitors, blood meters, thermometers, and scales. The Bluetooth Health API
+includes the classes {@link android.bluetooth.BluetoothHealth}, {@link
+android.bluetooth.BluetoothHealthCallback}, and {@link
+android.bluetooth.BluetoothHealthAppConfiguration}, which are described in <a
+href="#TheBasics">The Basics</a>. </p>
+
+<p>In using the Bluetooth Health API, it's helpful to understand these key HDP concepts:</p>
+<table>
+ <tr>
+ <th>Concept</th>
+ <th>Description</th>
+ </tr>
+ <tr>
+ <td><strong>Source</strong></td>
+
+ <td>A role defined in HDP. A <em>source</em> is a health device that
+transmits medical data (weight scale, glucose meter, thermometer, etc.) to a
+smart device such as an Android phone or tablet. </td>
+ </tr>
+ <tr>
+ <td><strong>Sink</strong></td>
+
+ <td>A role defined in HDP. In HDP, a <em>sink</em> is the smart device that
+receives the medical data. In an Android HDP application, the sink is
+represented by a {@link android.bluetooth.BluetoothHealthAppConfiguration}
+object.</td>
+ </tr>
+ <tr>
+ <td><strong>Registration</strong></td>
+ <td>Refers to registering a sink for a particular health device.</td>
+ </tr>
+ <tr>
+ <td><strong>Connection</strong></td>
+
+ <td>Refers to opening a channel between a health device and a smart device
+such as an Android phone or tablet.</td>
+ </tr>
+</table>
+
+<h4>Creating an HDP Application</h4>
+
+<p>Here are the basic steps involved in creating an Android HDP application:</p>
+<ol>
+
+ <li>Get a reference to the {@link android.bluetooth.BluetoothHealth} proxy
+object. <p>Similar to regular headset and A2DP profile devices, you must call
+{@link android.bluetooth.BluetoothAdapter#getProfileProxy getProfileProxy()}
+with a {@link android.bluetooth.BluetoothProfile.ServiceListener} and the {@link
+android.bluetooth.BluetoothProfile.ServiceListener#HEALTH} profile type to
+establish a connection with the profile proxy object.</p> </li>
+
+ <li>Create a {@link android.bluetooth.BluetoothHealthCallback} and register an
+application configuration
+({@link android.bluetooth.BluetoothHealthAppConfiguration})
+that acts as a health
+sink.</li>
+
+ <li>Establish a connection to a health device. Some devices will initiate the
+connection. It is unnecessary to carry out this step for those devices.</li>
+
+ <li>When connected successfully to a health device, read/write to the health
+device using the file descriptor. <p>The received data needs to be interpreted
+using a health manager which implements the IEEE 11073-xxxxx
+specifications.</p></li>
+
+ <li>When done, close the health channel and unregister the application. The
+channel also closes when there is extended inactivity.</li>
+</ol>
+
+<p>For a complete code sample that illustrates these steps, see <a
+href="{@docRoot}resources/samples/BluetoothHDP/index.html">Bluetooth HDP (Health
+Device Profile)</a>. </p>
diff --git a/docs/html/guide/topics/wireless/wifip2p.jd b/docs/html/guide/topics/wireless/wifip2p.jd
new file mode 100644
index 0000000..82c9abd
--- /dev/null
+++ b/docs/html/guide/topics/wireless/wifip2p.jd
@@ -0,0 +1,611 @@
+page.title=Wi-Fi Direct
+
+@jd:body
+
+ <div id="qv-wrapper">
+ <div id="qv">
+ <h2>In this document</h2>
+
+ <ol>
+ <li><a href="#api">API Overview</a></li>
+ <li><a href="#creating-br">Creating a Broadcast Receiver for Wi-Fi Direct Intents</a></li>
+
+ <li>
+ <a href="#creating-app">Creating a Wi-Fi Direct Application</a>
+
+ <ol>
+ <li><a href="#setup">Initial setup</a></li>
+
+ <li><a href="#discovering">Discovering peers</a></li>
+
+ <li><a href="#connecting">Connecting to peers</a></li>
+
+ <li><a href="#transferring">Transferring data</a></li>
+ </ol>
+ </li>
+ </ol>
+ <h2>Related Samples</h2>
+ <ol>
+ <li><a href="{@docRoot}resources/samples/WiFiDirectDemo/index.html">Wi-Fi Direct Demo</a></li>
+ </ol>
+ </div>
+ </div>
+
+ <p>Wi-Fi Direct 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.
+ 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.
+ This is useful for applications that share data among users, such as a multiplayer game or
+ a photo sharing application.</p>
+
+ <p>The Wi-Fi Direct APIs consist of the following main parts:</p>
+
+ <ul>
+ <li>Methods that allow you to discover, request, and connect to peers are defined
+ in the {@link android.net.wifi.p2p.WifiP2pManager} class.</li>
+
+ <li>Listeners that allow you to be notified of the success or failure of {@link
+ android.net.wifi.p2p.WifiP2pManager} method calls. When calling {@link
+ android.net.wifi.p2p.WifiP2pManager} methods, each method can receive a specific listener
+ passed in as a parameter.</li>
+
+ <li>Intents that notify you of specific events detected by the Wi-Fi Direct framework,
+ such as a dropped connection or a newly discovered peer.</li>
+ </ul>
+
+ <p>You often use these three main components of the APIs together. For example, you can
+ provide a {@link android.net.wifi.p2p.WifiP2pManager.ActionListener} to a call to {@link
+ android.net.wifi.p2p.WifiP2pManager#discoverPeers discoverPeers()}, so that you can be
+ notified with the {@link android.net.wifi.p2p.WifiP2pManager.ActionListener#onSuccess
+ ActionListener.onSuccess()} and {@link android.net.wifi.p2p.WifiP2pManager.ActionListener#onFailure
+ ActionListener.onFailure()}
+ methods. A {@link android.net.wifi.p2p.WifiP2pManager#WIFI_P2P_PEERS_CHANGED_ACTION} intent is
+ also broadcast if the {@link android.net.wifi.p2p.WifiP2pManager#discoverPeers discoverPeers()}
+ method discovers that the peers list has changed.</p>
+
+ <h2 id="api">API Overview</h2>
+
+<p>The {@link android.net.wifi.p2p.WifiP2pManager} class provides methods to allow you to interact with
+ the Wi-Fi hardware on your device to do things like discover and connect to peers. The following actions
+ are available:</p>
+
+<p class="table-caption"><strong>Table 1.</strong>Wi-Fi Direct Methods</p>
+
+ <table>
+ <tr>
+ <th>Method</th>
+ <th>Description</th>
+ </tr>
+
+ <tr>
+ <td>{@link android.net.wifi.p2p.WifiP2pManager#initialize initialize()}</td>
+ <td>Registers the application with the Wi-Fi framework. This must be called before calling any other Wi-Fi Direct method.</td>
+ </tr>
+
+ <tr>
+ <td>{@link android.net.wifi.p2p.WifiP2pManager#connect connect()}</td>
+ <td>Starts a peer-to-peer connection with a device with the specified configuration.</td>
+ </tr>
+
+ <tr>
+ <td>{@link android.net.wifi.p2p.WifiP2pManager#cancelConnect cancelConnect()}</td>
+ <td>Cancels any ongoing peer-to-peer group negotiation.</td>
+ </tr>
+
+ <tr>
+ <td>{@link android.net.wifi.p2p.WifiP2pManager#requestConnectionInfo requestConnectInfo()}</td>
+ <td>Requests a device's connection information.</td>
+ </tr>
+
+ <tr>
+ <td>{@link android.net.wifi.p2p.WifiP2pManager#createGroup createGroup()}</td>
+ <td>Creates a peer-to-peer group with the current device as the group owner.</td>
+ </tr>
+
+ <tr>
+ <td>{@link android.net.wifi.p2p.WifiP2pManager#removeGroup removeGroup()}</td>
+ <td>Removes the current peer-to-peer group.</td>
+ </tr>
+
+ <tr>
+ <td>{@link android.net.wifi.p2p.WifiP2pManager#requestGroupInfo requestGroupInfo()}</td>
+ <td>Requests peer-to-peer group information.</td>
+ </tr>
+
+ <tr>
+ <td>{@link android.net.wifi.p2p.WifiP2pManager.PeerListListener#discoverPeers discoverPeers()}</td>
+ <td>Initiates peer discovery </td>
+ </tr>
+
+ <tr>
+ <td>{@link android.net.wifi.p2p.WifiP2pManager#requestPeers requestPeers()}</td>
+ <td>Requests the current list of discovered peers.</td>
+ </tr>
+ </table>
+
+
+ <p>{@link android.net.wifi.p2p.WifiP2pManager} methods let you pass in a listener,
+ so that the Wi-Fi Direct framework can notify your
+ activity of the status of a call. The available listener interfaces and the
+ corresponding {@link android.net.wifi.p2p.WifiP2pManager} method calls that use the listeners
+ are described in the following table:</p>
+
+ <p class="table-caption"><strong>Table 2.</strong> Wi-Fi Direct Listeners</p>
+
+ <table>
+ <tr>
+ <th>Listener interface</th>
+ <th>Associated actions</th>
+ </tr>
+ <tr>
+ <td>{@link android.net.wifi.p2p.WifiP2pManager.ActionListener}</td>
+ <td>{@link android.net.wifi.p2p.WifiP2pManager#connect connect()}, {@link
+ android.net.wifi.p2p.WifiP2pManager#cancelConnect cancelConnect()}, {@link
+ android.net.wifi.p2p.WifiP2pManager#createGroup createGroup()}, {@link
+ android.net.wifi.p2p.WifiP2pManager#removeGroup removeGroup()}, and {@link
+ android.net.wifi.p2p.WifiP2pManager.PeerListListener#discoverPeers discoverPeers()}</td>
+ </tr>
+
+ <tr>
+ <td>{@link android.net.wifi.p2p.WifiP2pManager.ChannelListener}</td>
+ <td>{@link android.net.wifi.p2p.WifiP2pManager#initialize initialize()}</td>
+ </tr>
+
+ <tr>
+ <td>{@link android.net.wifi.p2p.WifiP2pManager.ConnectionInfoListener}</td>
+ <td>{@link android.net.wifi.p2p.WifiP2pManager#requestConnectionInfo requestConnectInfo()}</td>
+ </tr>
+
+ <tr>
+ <td>{@link android.net.wifi.p2p.WifiP2pManager.GroupInfoListener}</td>
+ <td>{@link android.net.wifi.p2p.WifiP2pManager#requestGroupInfo requestGroupInfo()}</td>
+ </tr>
+
+ <tr>
+ <td>{@link android.net.wifi.p2p.WifiP2pManager.PeerListListener}</td>
+ <td>{@link android.net.wifi.p2p.WifiP2pManager#requestPeers requestPeers()}</td>
+ </tr>
+ </table>
+
+<p>The Wi-Fi Direct APIs define intents that are broadcast when certain Wi-Fi Direct events happen,
+ such as when a new peer is discovered or when a device's Wi-Fi state changes. You can register
+ to receive these intents in your application by <a href="#creating-br">creating a broadcast
+ receiver</a> that handles these intents:</p>
+
+<p class="table-caption"><strong>Table 3.</strong> Wi-Fi Direct Intents</p>
+
+ <table>
+ <tr>
+ <th>Intent</th>
+ <th>Description</th>
+ </tr>
+ <tr>
+ <td>{@link android.net.wifi.p2p.WifiP2pManager#WIFI_P2P_CONNECTION_CHANGED_ACTION}</td>
+ <td>Broadcast when the state of the device's Wi-Fi connection changes.</td>
+ </tr>
+ <tr>
+ <td>{@link android.net.wifi.p2p.WifiP2pManager#WIFI_P2P_PEERS_CHANGED_ACTION}</td>
+ <td>Broadcast when you call {@link
+ android.net.wifi.p2p.WifiP2pManager.PeerListListener#discoverPeers discoverPeers()}. You
+ usually want to call {@link android.net.wifi.p2p.WifiP2pManager.PeerListListener#requestPeers
+ requestPeers()} to get an updated list of peers if you handle this intent in your
+ application.</td>
+ </tr>
+ <tr>
+ <td>{@link android.net.wifi.p2p.WifiP2pManager#WIFI_P2P_STATE_CHANGED_ACTION}</td>
+ <td>Broadcast when Wi-Fi Direct is enabled or disabled on the device.</td>
+ </tr>
+ <tr>
+ <td>{@link android.net.wifi.p2p.WifiP2pManager#WIFI_P2P_THIS_DEVICE_CHANGED_ACTION}</td>
+ <td>Broadcast when a device's details have changed, such as the device's name.</td>
+ </tr>
+ </table>
+
+
+
+ <h2 id="creating-br">Creating a Broadcast Receiver for Wi-Fi Direct Intents</h2>
+
+ <p>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 Direct intents are as follows:</p>
+
+ <ol>
+ <li>Create a class that extends the {@link android.content.BroadcastReceiver} class. For the
+ class' constructor, you most likely want to have parameters for the {@link
+ android.net.wifi.p2p.WifiP2pManager}, {@link android.net.wifi.p2p.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.</li>
+
+ <li>In the broadcast receiver, check for the intents that you are interested in
+ <code>{@link android.content.BroadcastReceiver#onReceive onReceive()}</code>.
+ Carry out any necessary actions depending on the intent that is
+ received. For example, if the broadcast receiver receives a {@link
+ android.net.wifi.p2p.WifiP2pManager#WIFI_P2P_PEERS_CHANGED_ACTION} intent, you can call the
+ {@link android.net.wifi.p2p.WifiP2pManager#requestPeers requestPeers()} method to get a list of
+ the currently discovered peers.</li>
+ </ol>
+
+ <p>The following code shows you how to create a typical broadcast receiver. The broadcast
+ receiver takes a {@link android.net.wifi.p2p.WifiP2pManager} object and an activity as
+ arguments and uses these two classes to appropriately carry out the needed actions when the
+ broadcast receiver receives an intent:</p>
+
+<pre>
+/**
+ * A BroadcastReceiver that notifies of important Wi-Fi p2p events.
+ */
+public class WiFiDirectBroadcastReceiver extends BroadcastReceiver {
+
+ private WifiP2pManager manager;
+ private Channel channel;
+ private MyWiFiActivity activity;
+
+ public WiFiDirectBroadcastReceiver(WifiP2pManager manager, Channel channel,
+ MyWifiActivity activity) {
+ super();
+ this.manager = manager;
+ this.channel = channel;
+ this.activity = activity;
+ }
+
+ &#064;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
+ }
+ }
+}
+</pre>
+
+ <h2 id="creating-app">Creating a Wi-Fi Direct Application</h2>
+
+ <p>Creating a Wi-Fi Direct 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.</p>
+
+ <h3 id="setup">Initial setup</h3>
+ <p>Before using the Wi-Fi Direct APIs, you must ensure that your application can access
+ the hardware and that the device supports the Wi-Fi Direct protocol. If Wi-Fi Direct is supported,
+ you can obtain an instance of {@link android.net.wifi.p2p.WifiP2pManager}, create and register
+ your broadcast receiver, and begin using the Wi-Fi Direct APIs.</p>
+ <ol>
+ <li>
+ <p>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:</p>
+ <pre>
+&lt;uses-sdk android:minSdkVersion="14" /&gt;
+&lt;uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /&gt;
+&lt;uses-permission android:name="android.permission.CHANGE_WIFI_STATE" /&gt;
+&lt;uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" /&gt;
+&lt;uses-permission android:name="android.permission.INTERNET" /&gt;
+&lt;uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /&gt;
+</pre>
+ </li>
+
+ <li>Check to see if Wi-Fi Direct is on and supported. A good place to check this is in your
+ broadcast receiver when it receives the {@link
+ android.net.wifi.p2p.WifiP2pManager#WIFI_P2P_STATE_CHANGED_ACTION} intent. Notify your
+ activity of the Wi-Fi Direct state and react accordingly:
+<pre>
+&#064;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 Direct is enabled
+ } else {
+ // Wi-Fi Direct is not enabled
+ }
+ }
+ ...
+}
+</pre>
+ </li>
+
+ <li>In your activity's {@link android.app.Activity#onCreate onCreate()} method, obtain an instance of {@link
+ android.net.wifi.p2p.WifiP2pManager} and register your application with the Wi-Fi Direct
+ framework by calling {@link android.net.wifi.p2p.WifiP2pManager#initialize initialize()}. This
+ method returns a {@link android.net.wifi.p2p.WifiP2pManager.Channel}, which is used to connect
+ your application to the Wi-Fi Direct framework. You should also create an instance of your
+ broadcast receiver with the {@link
+ android.net.wifi.p2p.WifiP2pManager} and {@link android.net.wifi.p2p.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:
+<pre>
+WifiP2pManager mManager;
+Channel mChannel;
+BroadcastReceiver mReceiver;
+...
+&#064;Override
+protected void onCreate(Bundle savedInstanceState){
+ ...
+ mManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
+ mChannel = mManager.initialize(this, getMainLooper(), null);
+ mReceiver = new WiFiDirectBroadcastReceiver(manager, channel, this);
+ ...
+}
+</pre>
+ </li>
+
+ <li>Create an intent filter and add the same intents that your
+ broadcast receiver checks for:
+ <pre>
+IntentFilter mIntentFilter;
+...
+&#064;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);
+ ...
+}
+</pre>
+ </li>
+
+ <li>Register the broadcast receiver in the {@link android.app.Activity#onResume()} method
+ of your activity and unregister it in the {@link android.app.Activity#onPause()} method of your activity:
+ <pre>
+/* register the broadcast receiver with the intent values to be matched */
+&#064;Override
+protected void onResume() {
+ super.onResume();
+ registerReceiver(mReceiver, mIntentFilter);
+}
+/* unregister the broadcast receiver */
+&#064;Override
+protected void onPause() {
+ super.onPause();
+ unregisterReceiver(mReceiver);
+}
+</pre>
+
+ <p>When you have obtained a {@link android.net.wifi.p2p.WifiP2pManager.Channel} and
+ set up a broadcast receiver, your application can make Wi-Fi Direct method calls and receive
+ Wi-Fi Direct intents.</p>
+ </li>
+
+ <p>You can now implement your application and use the Wi-Fi Direct features by calling the
+ methods in {@link android.net.wifi.p2p.WifiP2pManager}. The next sections describe how to do common actions
+ such as discovering and connecting to peers.</p>
+ </ol>
+
+ <h3 id="discovering">Discovering peers</h3>
+
+ <p>To discover peers that are available to connect to, call {@link
+ android.net.wifi.p2p.WifiP2pManager#discoverPeers 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 {@link
+ android.net.wifi.p2p.WifiP2pManager.ActionListener#onSuccess onSuccess()} and {@link
+ android.net.wifi.p2p.WifiP2pManager.ActionListener#onFailure onFailure()} if you created a
+ {@link android.net.wifi.p2p.WifiP2pManager.ActionListener}. The
+ {@link android.net.wifi.p2p.WifiP2pManager.ActionListener#onSuccess 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:</p>
+ <pre>
+manager.discoverPeers(channel, new WifiP2pManager.ActionListener() {
+ &#064;Override
+ public void onSuccess() {
+ ...
+ }
+
+ &#064;Override
+ public void onFailure(int reasonCode) {
+ ...
+ }
+});
+
+</pre>
+
+<p>If the discovery process succeeds and detects peers, the system broadcasts the {@link
+ android.net.wifi.p2p.WifiP2pManager#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 {@link
+ android.net.wifi.p2p.WifiP2pManager#WIFI_P2P_PEERS_CHANGED_ACTION} intent, you can request a
+ list of the discovered peers with {@link
+ android.net.wifi.p2p.WifiP2pManager#requestPeers requestPeers()}. The following code shows how to set this up:</p>
+ <pre>
+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 (manager != null) {
+ manager.requestPeers(channel, myPeerListListener);
+ }
+}
+</pre>
+
+ <p>The {@link android.net.wifi.p2p.WifiP2pManager#requestPeers requestPeers()} method is also
+ asynchronous and can notify your activity when a list of peers is available with {@link
+ android.net.wifi.p2p.WifiP2pManager.PeerListListener#onPeersAvailable onPeersAvailable()}, which is defined in the
+ the {@link android.net.wifi.p2p.WifiP2pManager.PeerListListener} interface. The {@link
+ android.net.wifi.p2p.WifiP2pManager.PeerListListener#onPeersAvailable onPeersAvailable()} method
+ provides you with an {@link android.net.wifi.p2p.WifiP2pDeviceList}, which you can iterate
+ through to find the peer that you want to connect to.</p>
+
+ <h3 id="connecting">Connecting to peers</h3>
+
+ <p>When you have figured out the device that you want to connect to after obtaining a list of
+ possible peers, call the {@link android.net.wifi.p2p.WifiP2pManager#connect connect()} method to
+ connect to the device. This method call requires a {@link android.net.wifi.p2p.WifiP2pConfig}
+ object that contains the information of the device to connect to.
+ You can be notified of a connection success or failure through the {@link
+ android.net.wifi.p2p.WifiP2pManager.ActionListener}. The following code
+ shows you how to create a connection to a desired device:</p>
+ <pre>
+//obtain a peer from the WifiP2pDeviceList
+WifiP2pDevice device;
+WifiP2pConfig config = new WifiP2pConfig();
+config.deviceAddress = device.deviceAddress;
+manager.connect(channel, config, new ActionListener() {
+
+ &#064;Override
+ public void onSuccess() {
+ //success logic
+ }
+
+ &#064;Override
+ public void onFailure(int reason) {
+ //failure logic
+ }
+});
+
+</pre>
+
+
+ <h3 id="transferring">Transferring data</h3>
+ <p>Once a connection is established, you can transfer data between the devices with
+ sockets. The basic steps of transferring data are as follows:</p>
+
+ <ol>
+ <li>Create a {@link java.net.ServerSocket}. This socket waits for a connection from a client on a specified
+ port and blocks until it happens, so do this in a background thread.</li>
+
+ <li>Create a client {@link java.net.Socket}. The client uses the IP address and port of
+ the server socket to connect to the server device.</li>
+
+ <li>Send data from the client to the server. When the client
+ socket successfully connects to the server socket, you can send data from the client to the server
+ with byte streams. </li>
+
+ <li>The server socket waits for a client connection (with the {@link java.net.ServerSocket#accept()} method). This
+ call blocks until a client connects, so call this is another thread. When a connection happens, the server device can receive
+ the data from the client. Carry out any actions with this data, such as saving it to a file
+ or presenting it to the user.</li>
+ </ol>
+
+ <p>The following example, modified from the <a href=
+ "{@docRoot}resources/samples/WiFiDirectDemo/index.html">Wi-Fi Direct Demo</a> sample, shows you how
+ to create this client-server socket communication and transfer JPEG images from a client
+ to a server with a service. For a complete working example, compile and run the <a href=
+ "{@docRoot}resources/samples/WiFiDirectDemo/index.html">Wi-Fi Direct Demo</a> sample.</p>
+<pre>
+public static class FileServerAsyncTask extends AsyncTask<Void, Void, String> {
+
+ private Context context;
+ private TextView statusText;
+
+ public FileServerAsyncTask(Context context, View statusText) {
+ this.context = context;
+ this.statusText = (TextView) statusText;
+ }
+
+ &#064;Override
+ protected String doInBackground(Void... params) {
+ try {
+
+ /**
+ * Create a server socket and wait for client connections. This
+ * call blocks until a connection is accepted from a client
+ */
+ ServerSocket serverSocket = new ServerSocket(8888);
+ Socket client = serverSocket.accept();
+
+ /**
+ * If this code is reached, a client has connected and transferred data
+ * Save the input stream from the client as a JPEG file
+ */
+ final File f = new File(Environment.getExternalStorageDirectory() + "/"
+ + context.getPackageName() + "/wifip2pshared-" + System.currentTimeMillis()
+ + ".jpg");
+
+ File dirs = new File(f.getParent());
+ if (!dirs.exists())
+ dirs.mkdirs();
+ f.createNewFile();
+ InputStream inputstream = client.getInputStream();
+ copyFile(inputstream, new FileOutputStream(f));
+ serverSocket.close();
+ return f.getAbsolutePath();
+ } catch (IOException e) {
+ Log.e(WiFiDirectActivity.TAG, e.getMessage());
+ return null;
+ }
+ }
+
+ /**
+ * Start activity that can handle the JPEG image
+ */
+ &#064;Override
+ protected void onPostExecute(String result) {
+ if (result != null) {
+ statusText.setText("File copied - " + result);
+ Intent intent = new Intent();
+ intent.setAction(android.content.Intent.ACTION_VIEW);
+ intent.setDataAndType(Uri.parse("file://" + result), "image/*");
+ context.startActivity(intent);
+ }
+ }
+}
+</pre>
+
+ <p>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.</p>
+
+<pre>
+Context context = this.getApplicationContext();
+String host;
+int port;
+int len;
+Socket socket = new Socket();
+byte buf[] = new byte[1024];
+...
+try {
+ /**
+ * Create a client socket with the host,
+ * port, and timeout information.
+ */
+ socket.bind(null);
+ socket.connect((new InetSocketAddress(host, port)), 500);
+
+ /**
+ * Create a byte stream from a JPEG file and pipe it to the output stream
+ * of the socket. This data will be retrieved by the server device.
+ */
+ OutputStream outputStream = socket.getOutputStream();
+ ContentResolver cr = context.getContentResolver();
+ InputStream inputStream = null;
+ inputStream = cr.openInputStream(Uri.parse("path/to/picture.jpg"));
+ while ((len = inputStream.read(buf)) != -1) {
+ outputStream.write(buf, 0, len);
+ }
+ outputStream.close();
+ inputStream.close();
+} catch (FileNotFoundException e) {
+ //catch logic
+} catch (IOException e) {
+ //catch logic
+}
+
+/**
+ * Clean up any open sockets when done
+ * transferring or if an exception occurred.
+ */
+finally {
+ if (socket != null) {
+ if (socket.isConnected()) {
+ try {
+ socket.close();
+ } catch (IOException e) {
+ //catch logic
+ }
+ }
+ }
+}
+</pre>