BluetoothAdapter.java revision e21a4ac09d2473becaea43a73d19e9e836e7732a
1/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.bluetooth;
18
19import android.annotation.SdkConstant;
20import android.annotation.SdkConstant.SdkConstantType;
21import android.content.Context;
22import android.os.Binder;
23import android.os.Handler;
24import android.os.IBinder;
25import android.os.Looper;
26import android.os.Message;
27import android.os.ParcelUuid;
28import android.os.RemoteException;
29import android.os.ServiceManager;
30import android.util.Log;
31import android.util.Pair;
32
33import java.io.IOException;
34import java.util.Arrays;
35import java.util.Collections;
36import java.util.HashSet;
37import java.util.LinkedList;
38import java.util.Random;
39import java.util.Set;
40import java.util.UUID;
41
42/**
43 * Represents the local device Bluetooth adapter. The {@link BluetoothAdapter}
44 * lets you perform fundamental Bluetooth tasks, such as initiate
45 * device discovery, query a list of bonded (paired) devices,
46 * instantiate a {@link BluetoothDevice} using a known MAC address, and create
47 * a {@link BluetoothServerSocket} to listen for connection requests from other
48 * devices.
49 *
50 * <p>To get a {@link BluetoothAdapter} representing the local Bluetooth
51 * adapter, call the static {@link #getDefaultAdapter} method.
52 * Fundamentally, this is your starting point for all
53 * Bluetooth actions. Once you have the local adapter, you can get a set of
54 * {@link BluetoothDevice} objects representing all paired devices with
55 * {@link #getBondedDevices()}; start device discovery with
56 * {@link #startDiscovery()}; or create a {@link BluetoothServerSocket} to
57 * listen for incoming connection requests with
58 * {@link #listenUsingRfcommWithServiceRecord(String,UUID)}.
59 *
60 * <p class="note"><strong>Note:</strong>
61 * Most methods require the {@link android.Manifest.permission#BLUETOOTH}
62 * permission and some also require the
63 * {@link android.Manifest.permission#BLUETOOTH_ADMIN} permission.
64 *
65 * <div class="special reference">
66 * <h3>Developer Guides</h3>
67 * <p>For more information about using Bluetooth, read the
68 * <a href="{@docRoot}guide/topics/wireless/bluetooth.html">Bluetooth</a> developer guide.</p>
69 * </div>
70 *
71 * {@see BluetoothDevice}
72 * {@see BluetoothServerSocket}
73 */
74public final class BluetoothAdapter {
75    private static final String TAG = "BluetoothAdapter";
76    private static final boolean DBG = false;
77
78    /**
79     * Sentinel error value for this class. Guaranteed to not equal any other
80     * integer constant in this class. Provided as a convenience for functions
81     * that require a sentinel error value, for example:
82     * <p><code>Intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
83     * BluetoothAdapter.ERROR)</code>
84     */
85    public static final int ERROR = Integer.MIN_VALUE;
86
87    /**
88     * Broadcast Action: The state of the local Bluetooth adapter has been
89     * changed.
90     * <p>For example, Bluetooth has been turned on or off.
91     * <p>Always contains the extra fields {@link #EXTRA_STATE} and {@link
92     * #EXTRA_PREVIOUS_STATE} containing the new and old states
93     * respectively.
94     * <p>Requires {@link android.Manifest.permission#BLUETOOTH} to receive.
95     */
96    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
97    public static final String ACTION_STATE_CHANGED =
98            "android.bluetooth.adapter.action.STATE_CHANGED";
99
100    /**
101     * Used as an int extra field in {@link #ACTION_STATE_CHANGED}
102     * intents to request the current power state. Possible values are:
103     * {@link #STATE_OFF},
104     * {@link #STATE_TURNING_ON},
105     * {@link #STATE_ON},
106     * {@link #STATE_TURNING_OFF},
107     */
108    public static final String EXTRA_STATE =
109            "android.bluetooth.adapter.extra.STATE";
110    /**
111     * Used as an int extra field in {@link #ACTION_STATE_CHANGED}
112     * intents to request the previous power state. Possible values are:
113     * {@link #STATE_OFF},
114     * {@link #STATE_TURNING_ON},
115     * {@link #STATE_ON},
116     * {@link #STATE_TURNING_OFF},
117     */
118    public static final String EXTRA_PREVIOUS_STATE =
119            "android.bluetooth.adapter.extra.PREVIOUS_STATE";
120
121    /**
122     * Indicates the local Bluetooth adapter is off.
123     */
124    public static final int STATE_OFF = 10;
125    /**
126     * Indicates the local Bluetooth adapter is turning on. However local
127     * clients should wait for {@link #STATE_ON} before attempting to
128     * use the adapter.
129     */
130    public static final int STATE_TURNING_ON = 11;
131    /**
132     * Indicates the local Bluetooth adapter is on, and ready for use.
133     */
134    public static final int STATE_ON = 12;
135    /**
136     * Indicates the local Bluetooth adapter is turning off. Local clients
137     * should immediately attempt graceful disconnection of any remote links.
138     */
139    public static final int STATE_TURNING_OFF = 13;
140
141    /**
142     * Activity Action: Show a system activity that requests discoverable mode.
143     * This activity will also request the user to turn on Bluetooth if it
144     * is not currently enabled.
145     * <p>Discoverable mode is equivalent to {@link
146     * #SCAN_MODE_CONNECTABLE_DISCOVERABLE}. It allows remote devices to see
147     * this Bluetooth adapter when they perform a discovery.
148     * <p>For privacy, Android is not discoverable by default.
149     * <p>The sender of this Intent can optionally use extra field {@link
150     * #EXTRA_DISCOVERABLE_DURATION} to request the duration of
151     * discoverability. Currently the default duration is 120 seconds, and
152     * maximum duration is capped at 300 seconds for each request.
153     * <p>Notification of the result of this activity is posted using the
154     * {@link android.app.Activity#onActivityResult} callback. The
155     * <code>resultCode</code>
156     * will be the duration (in seconds) of discoverability or
157     * {@link android.app.Activity#RESULT_CANCELED} if the user rejected
158     * discoverability or an error has occurred.
159     * <p>Applications can also listen for {@link #ACTION_SCAN_MODE_CHANGED}
160     * for global notification whenever the scan mode changes. For example, an
161     * application can be notified when the device has ended discoverability.
162     * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
163     */
164    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
165    public static final String ACTION_REQUEST_DISCOVERABLE =
166            "android.bluetooth.adapter.action.REQUEST_DISCOVERABLE";
167
168    /**
169     * Used as an optional int extra field in {@link
170     * #ACTION_REQUEST_DISCOVERABLE} intents to request a specific duration
171     * for discoverability in seconds. The current default is 120 seconds, and
172     * requests over 300 seconds will be capped. These values could change.
173     */
174    public static final String EXTRA_DISCOVERABLE_DURATION =
175            "android.bluetooth.adapter.extra.DISCOVERABLE_DURATION";
176
177    /**
178     * Activity Action: Show a system activity that allows the user to turn on
179     * Bluetooth.
180     * <p>This system activity will return once Bluetooth has completed turning
181     * on, or the user has decided not to turn Bluetooth on.
182     * <p>Notification of the result of this activity is posted using the
183     * {@link android.app.Activity#onActivityResult} callback. The
184     * <code>resultCode</code>
185     * will be {@link android.app.Activity#RESULT_OK} if Bluetooth has been
186     * turned on or {@link android.app.Activity#RESULT_CANCELED} if the user
187     * has rejected the request or an error has occurred.
188     * <p>Applications can also listen for {@link #ACTION_STATE_CHANGED}
189     * for global notification whenever Bluetooth is turned on or off.
190     * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
191     */
192    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
193    public static final String ACTION_REQUEST_ENABLE =
194            "android.bluetooth.adapter.action.REQUEST_ENABLE";
195
196    /**
197     * Broadcast Action: Indicates the Bluetooth scan mode of the local Adapter
198     * has changed.
199     * <p>Always contains the extra fields {@link #EXTRA_SCAN_MODE} and {@link
200     * #EXTRA_PREVIOUS_SCAN_MODE} containing the new and old scan modes
201     * respectively.
202     * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
203     */
204    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
205    public static final String ACTION_SCAN_MODE_CHANGED =
206            "android.bluetooth.adapter.action.SCAN_MODE_CHANGED";
207
208    /**
209     * Used as an int extra field in {@link #ACTION_SCAN_MODE_CHANGED}
210     * intents to request the current scan mode. Possible values are:
211     * {@link #SCAN_MODE_NONE},
212     * {@link #SCAN_MODE_CONNECTABLE},
213     * {@link #SCAN_MODE_CONNECTABLE_DISCOVERABLE},
214     */
215    public static final String EXTRA_SCAN_MODE = "android.bluetooth.adapter.extra.SCAN_MODE";
216    /**
217     * Used as an int extra field in {@link #ACTION_SCAN_MODE_CHANGED}
218     * intents to request the previous scan mode. Possible values are:
219     * {@link #SCAN_MODE_NONE},
220     * {@link #SCAN_MODE_CONNECTABLE},
221     * {@link #SCAN_MODE_CONNECTABLE_DISCOVERABLE},
222     */
223    public static final String EXTRA_PREVIOUS_SCAN_MODE =
224            "android.bluetooth.adapter.extra.PREVIOUS_SCAN_MODE";
225
226    /**
227     * Indicates that both inquiry scan and page scan are disabled on the local
228     * Bluetooth adapter. Therefore this device is neither discoverable
229     * nor connectable from remote Bluetooth devices.
230     */
231    public static final int SCAN_MODE_NONE = 20;
232    /**
233     * Indicates that inquiry scan is disabled, but page scan is enabled on the
234     * local Bluetooth adapter. Therefore this device is not discoverable from
235     * remote Bluetooth devices, but is connectable from remote devices that
236     * have previously discovered this device.
237     */
238    public static final int SCAN_MODE_CONNECTABLE = 21;
239    /**
240     * Indicates that both inquiry scan and page scan are enabled on the local
241     * Bluetooth adapter. Therefore this device is both discoverable and
242     * connectable from remote Bluetooth devices.
243     */
244    public static final int SCAN_MODE_CONNECTABLE_DISCOVERABLE = 23;
245
246
247    /**
248     * Broadcast Action: The local Bluetooth adapter has started the remote
249     * device discovery process.
250     * <p>This usually involves an inquiry scan of about 12 seconds, followed
251     * by a page scan of each new device to retrieve its Bluetooth name.
252     * <p>Register for {@link BluetoothDevice#ACTION_FOUND} to be notified as
253     * remote Bluetooth devices are found.
254     * <p>Device discovery is a heavyweight procedure. New connections to
255     * remote Bluetooth devices should not be attempted while discovery is in
256     * progress, and existing connections will experience limited bandwidth
257     * and high latency. Use {@link #cancelDiscovery()} to cancel an ongoing
258     * discovery.
259     * <p>Requires {@link android.Manifest.permission#BLUETOOTH} to receive.
260     */
261    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
262    public static final String ACTION_DISCOVERY_STARTED =
263            "android.bluetooth.adapter.action.DISCOVERY_STARTED";
264    /**
265     * Broadcast Action: The local Bluetooth adapter has finished the device
266     * discovery process.
267     * <p>Requires {@link android.Manifest.permission#BLUETOOTH} to receive.
268     */
269    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
270    public static final String ACTION_DISCOVERY_FINISHED =
271            "android.bluetooth.adapter.action.DISCOVERY_FINISHED";
272
273    /**
274     * Broadcast Action: The local Bluetooth adapter has changed its friendly
275     * Bluetooth name.
276     * <p>This name is visible to remote Bluetooth devices.
277     * <p>Always contains the extra field {@link #EXTRA_LOCAL_NAME} containing
278     * the name.
279     * <p>Requires {@link android.Manifest.permission#BLUETOOTH} to receive.
280     */
281    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
282    public static final String ACTION_LOCAL_NAME_CHANGED =
283            "android.bluetooth.adapter.action.LOCAL_NAME_CHANGED";
284    /**
285     * Used as a String extra field in {@link #ACTION_LOCAL_NAME_CHANGED}
286     * intents to request the local Bluetooth name.
287     */
288    public static final String EXTRA_LOCAL_NAME = "android.bluetooth.adapter.extra.LOCAL_NAME";
289
290    /**
291     * Intent used to broadcast the change in connection state of the local
292     * Bluetooth adapter to a profile of the remote device. When the adapter is
293     * not connected to any profiles of any remote devices and it attempts a
294     * connection to a profile this intent will sent. Once connected, this intent
295     * will not be sent for any more connection attempts to any profiles of any
296     * remote device. When the adapter disconnects from the last profile its
297     * connected to of any remote device, this intent will be sent.
298     *
299     * <p> This intent is useful for applications that are only concerned about
300     * whether the local adapter is connected to any profile of any device and
301     * are not really concerned about which profile. For example, an application
302     * which displays an icon to display whether Bluetooth is connected or not
303     * can use this intent.
304     *
305     * <p>This intent will have 3 extras:
306     * {@link #EXTRA_CONNECTION_STATE} - The current connection state.
307     * {@link #EXTRA_PREVIOUS_CONNECTION_STATE}- The previous connection state.
308     * {@link BluetoothDevice#EXTRA_DEVICE} - The remote device.
309     *
310     * {@link #EXTRA_CONNECTION_STATE} or {@link #EXTRA_PREVIOUS_CONNECTION_STATE}
311     * can be any of {@link #STATE_DISCONNECTED}, {@link #STATE_CONNECTING},
312     * {@link #STATE_CONNECTED}, {@link #STATE_DISCONNECTING}.
313     *
314     * <p>Requires {@link android.Manifest.permission#BLUETOOTH} to receive.
315     */
316    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
317    public static final String ACTION_CONNECTION_STATE_CHANGED =
318        "android.bluetooth.adapter.action.CONNECTION_STATE_CHANGED";
319
320    /**
321     * Extra used by {@link #ACTION_CONNECTION_STATE_CHANGED}
322     *
323     * This extra represents the current connection state.
324     */
325    public static final String EXTRA_CONNECTION_STATE =
326        "android.bluetooth.adapter.extra.CONNECTION_STATE";
327
328    /**
329     * Extra used by {@link #ACTION_CONNECTION_STATE_CHANGED}
330     *
331     * This extra represents the previous connection state.
332     */
333    public static final String EXTRA_PREVIOUS_CONNECTION_STATE =
334          "android.bluetooth.adapter.extra.PREVIOUS_CONNECTION_STATE";
335
336    /** The profile is in disconnected state */
337    public static final int STATE_DISCONNECTED  = 0;
338    /** The profile is in connecting state */
339    public static final int STATE_CONNECTING    = 1;
340    /** The profile is in connected state */
341    public static final int STATE_CONNECTED     = 2;
342    /** The profile is in disconnecting state */
343    public static final int STATE_DISCONNECTING = 3;
344
345    /** @hide */
346    public static final String BLUETOOTH_SERVICE = "bluetooth";
347
348    private static final int ADDRESS_LENGTH = 17;
349
350    /**
351     * Lazily initialized singleton. Guaranteed final after first object
352     * constructed.
353     */
354    private static BluetoothAdapter sAdapter;
355
356    private final IBluetooth mService;
357
358    private Handler mServiceRecordHandler;
359
360    /**
361     * Get a handle to the default local Bluetooth adapter.
362     * <p>Currently Android only supports one Bluetooth adapter, but the API
363     * could be extended to support more. This will always return the default
364     * adapter.
365     * @return the default local adapter, or null if Bluetooth is not supported
366     *         on this hardware platform
367     */
368    public static synchronized BluetoothAdapter getDefaultAdapter() {
369        if (sAdapter == null) {
370            IBinder b = ServiceManager.getService("bluetooth");
371            if (b != null) {
372                IBluetooth service = IBluetooth.Stub.asInterface(b);
373                sAdapter = new BluetoothAdapter(service);
374            } else {
375                Log.e(TAG, "Bluetooth binder is null");
376            }
377        }
378        return sAdapter;
379    }
380
381    /**
382     * Use {@link #getDefaultAdapter} to get the BluetoothAdapter instance.
383     */
384    BluetoothAdapter(IBluetooth service) {
385        if (service == null) {
386            throw new IllegalArgumentException("service is null");
387        }
388        mService = service;
389        mServiceRecordHandler = null;
390    }
391
392    /**
393     * Get a {@link BluetoothDevice} object for the given Bluetooth hardware
394     * address.
395     * <p>Valid Bluetooth hardware addresses must be upper case, in a format
396     * such as "00:11:22:33:AA:BB". The helper {@link #checkBluetoothAddress} is
397     * available to validate a Bluetooth address.
398     * <p>A {@link BluetoothDevice} will always be returned for a valid
399     * hardware address, even if this adapter has never seen that device.
400     *
401     * @param address valid Bluetooth MAC address
402     * @throws IllegalArgumentException if address is invalid
403     */
404    public BluetoothDevice getRemoteDevice(String address) {
405        return new BluetoothDevice(address);
406    }
407
408    /**
409     * Get a {@link BluetoothDevice} object for the given Bluetooth hardware
410     * address.
411     * <p>Valid Bluetooth hardware addresses must be 6 bytes. This method
412     * expects the address in network byte order (MSB first).
413     * <p>A {@link BluetoothDevice} will always be returned for a valid
414     * hardware address, even if this adapter has never seen that device.
415     *
416     * @param address Bluetooth MAC address (6 bytes)
417     * @throws IllegalArgumentException if address is invalid
418     */
419    public BluetoothDevice getRemoteDevice(byte[] address) {
420        if (address == null || address.length != 6) {
421            throw new IllegalArgumentException("Bluetooth address must have 6 bytes");
422        }
423        return new BluetoothDevice(String.format("%02X:%02X:%02X:%02X:%02X:%02X",
424                address[0], address[1], address[2], address[3], address[4], address[5]));
425    }
426
427    /**
428     * Return true if Bluetooth is currently enabled and ready for use.
429     * <p>Equivalent to:
430     * <code>getBluetoothState() == STATE_ON</code>
431     * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
432     *
433     * @return true if the local adapter is turned on
434     */
435    public boolean isEnabled() {
436        try {
437            return mService.isEnabled();
438        } catch (RemoteException e) {Log.e(TAG, "", e);}
439        return false;
440    }
441
442    /**
443     * Get the current state of the local Bluetooth adapter.
444     * <p>Possible return values are
445     * {@link #STATE_OFF},
446     * {@link #STATE_TURNING_ON},
447     * {@link #STATE_ON},
448     * {@link #STATE_TURNING_OFF}.
449     * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
450     *
451     * @return current state of Bluetooth adapter
452     */
453    public int getState() {
454        if (mService == null) return STATE_OFF;
455        try {
456            return mService.getState();
457        } catch (RemoteException e) {Log.e(TAG, "", e);}
458        return STATE_OFF;
459    }
460
461    /**
462     * Turn on the local Bluetooth adapter&mdash;do not use without explicit
463     * user action to turn on Bluetooth.
464     * <p>This powers on the underlying Bluetooth hardware, and starts all
465     * Bluetooth system services.
466     * <p class="caution"><strong>Bluetooth should never be enabled without
467     * direct user consent</strong>. If you want to turn on Bluetooth in order
468     * to create a wireless connection, you should use the {@link
469     * #ACTION_REQUEST_ENABLE} Intent, which will raise a dialog that requests
470     * user permission to turn on Bluetooth. The {@link #enable()} method is
471     * provided only for applications that include a user interface for changing
472     * system settings, such as a "power manager" app.</p>
473     * <p>This is an asynchronous call: it will return immediately, and
474     * clients should listen for {@link #ACTION_STATE_CHANGED}
475     * to be notified of subsequent adapter state changes. If this call returns
476     * true, then the adapter state will immediately transition from {@link
477     * #STATE_OFF} to {@link #STATE_TURNING_ON}, and some time
478     * later transition to either {@link #STATE_OFF} or {@link
479     * #STATE_ON}. If this call returns false then there was an
480     * immediate problem that will prevent the adapter from being turned on -
481     * such as Airplane mode, or the adapter is already turned on.
482     * <p>Requires the {@link android.Manifest.permission#BLUETOOTH_ADMIN}
483     * permission
484     *
485     * @return true to indicate adapter startup has begun, or false on
486     *         immediate error
487     */
488    public boolean enable() {
489        try {
490            return mService.enable();
491        } catch (RemoteException e) {Log.e(TAG, "", e);}
492        return false;
493    }
494
495    /**
496     * Turn off the local Bluetooth adapter&mdash;do not use without explicit
497     * user action to turn off Bluetooth.
498     * <p>This gracefully shuts down all Bluetooth connections, stops Bluetooth
499     * system services, and powers down the underlying Bluetooth hardware.
500     * <p class="caution"><strong>Bluetooth should never be disabled without
501     * direct user consent</strong>. The {@link #disable()} method is
502     * provided only for applications that include a user interface for changing
503     * system settings, such as a "power manager" app.</p>
504     * <p>This is an asynchronous call: it will return immediately, and
505     * clients should listen for {@link #ACTION_STATE_CHANGED}
506     * to be notified of subsequent adapter state changes. If this call returns
507     * true, then the adapter state will immediately transition from {@link
508     * #STATE_ON} to {@link #STATE_TURNING_OFF}, and some time
509     * later transition to either {@link #STATE_OFF} or {@link
510     * #STATE_ON}. If this call returns false then there was an
511     * immediate problem that will prevent the adapter from being turned off -
512     * such as the adapter already being turned off.
513     * <p>Requires the {@link android.Manifest.permission#BLUETOOTH_ADMIN}
514     * permission
515     *
516     * @return true to indicate adapter shutdown has begun, or false on
517     *         immediate error
518     */
519    public boolean disable() {
520        try {
521            return mService.disable(true);
522        } catch (RemoteException e) {Log.e(TAG, "", e);}
523        return false;
524    }
525
526    /**
527     * Turn off the local Bluetooth adapter and don't persist the setting.
528     *
529     * <p>Requires the {@link android.Manifest.permission#BLUETOOTH_ADMIN}
530     * permission
531     *
532     * @return true to indicate adapter shutdown has begun, or false on
533     *         immediate error
534     * @hide
535     */
536    public boolean disable(boolean persist) {
537        try {
538            return mService.disable(persist);
539        } catch (RemoteException e) {Log.e(TAG, "", e);}
540        return false;
541    }
542
543    /**
544     * Returns the hardware address of the local Bluetooth adapter.
545     * <p>For example, "00:11:22:AA:BB:CC".
546     * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
547     *
548     * @return Bluetooth hardware address as string
549     */
550    public String getAddress() {
551        try {
552            return mService.getAddress();
553        } catch (RemoteException e) {Log.e(TAG, "", e);}
554        return null;
555    }
556
557    /**
558     * Get the friendly Bluetooth name of the local Bluetooth adapter.
559     * <p>This name is visible to remote Bluetooth devices.
560     * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
561     *
562     * @return the Bluetooth name, or null on error
563     */
564    public String getName() {
565        try {
566            return mService.getName();
567        } catch (RemoteException e) {Log.e(TAG, "", e);}
568        return null;
569    }
570
571    /**
572     * Get the UUIDs supported by the local Bluetooth adapter.
573     *
574     * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
575     *
576     * @return the UUIDs supported by the local Bluetooth Adapter.
577     * @hide
578     */
579    public ParcelUuid[] getUuids() {
580        if (getState() != STATE_ON) return null;
581        try {
582            return mService.getUuids();
583        } catch (RemoteException e) {Log.e(TAG, "", e);}
584        return null;
585    }
586
587    /**
588     * Set the friendly Bluetooth name of the local Bluetooth adapter.
589     * <p>This name is visible to remote Bluetooth devices.
590     * <p>Valid Bluetooth names are a maximum of 248 bytes using UTF-8
591     * encoding, although many remote devices can only display the first
592     * 40 characters, and some may be limited to just 20.
593     * <p>If Bluetooth state is not {@link #STATE_ON}, this API
594     * will return false. After turning on Bluetooth,
595     * wait for {@link #ACTION_STATE_CHANGED} with {@link #STATE_ON}
596     * to get the updated value.
597     * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN}
598     *
599     * @param name a valid Bluetooth name
600     * @return     true if the name was set, false otherwise
601     */
602    public boolean setName(String name) {
603        if (getState() != STATE_ON) return false;
604        try {
605            return mService.setName(name);
606        } catch (RemoteException e) {Log.e(TAG, "", e);}
607        return false;
608    }
609
610    /**
611     * Get the current Bluetooth scan mode of the local Bluetooth adapter.
612     * <p>The Bluetooth scan mode determines if the local adapter is
613     * connectable and/or discoverable from remote Bluetooth devices.
614     * <p>Possible values are:
615     * {@link #SCAN_MODE_NONE},
616     * {@link #SCAN_MODE_CONNECTABLE},
617     * {@link #SCAN_MODE_CONNECTABLE_DISCOVERABLE}.
618     * <p>If Bluetooth state is not {@link #STATE_ON}, this API
619     * will return {@link #SCAN_MODE_NONE}. After turning on Bluetooth,
620     * wait for {@link #ACTION_STATE_CHANGED} with {@link #STATE_ON}
621     * to get the updated value.
622     * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
623     *
624     * @return scan mode
625     */
626    public int getScanMode() {
627        if (getState() != STATE_ON) return SCAN_MODE_NONE;
628        try {
629            return mService.getScanMode();
630        } catch (RemoteException e) {Log.e(TAG, "", e);}
631        return SCAN_MODE_NONE;
632    }
633
634    /**
635     * Set the Bluetooth scan mode of the local Bluetooth adapter.
636     * <p>The Bluetooth scan mode determines if the local adapter is
637     * connectable and/or discoverable from remote Bluetooth devices.
638     * <p>For privacy reasons, discoverable mode is automatically turned off
639     * after <code>duration</code> seconds. For example, 120 seconds should be
640     * enough for a remote device to initiate and complete its discovery
641     * process.
642     * <p>Valid scan mode values are:
643     * {@link #SCAN_MODE_NONE},
644     * {@link #SCAN_MODE_CONNECTABLE},
645     * {@link #SCAN_MODE_CONNECTABLE_DISCOVERABLE}.
646     * <p>If Bluetooth state is not {@link #STATE_ON}, this API
647     * will return false. After turning on Bluetooth,
648     * wait for {@link #ACTION_STATE_CHANGED} with {@link #STATE_ON}
649     * to get the updated value.
650     * <p>Requires {@link android.Manifest.permission#WRITE_SECURE_SETTINGS}
651     * <p>Applications cannot set the scan mode. They should use
652     * <code>startActivityForResult(
653     * BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE})
654     * </code>instead.
655     *
656     * @param mode valid scan mode
657     * @param duration time in seconds to apply scan mode, only used for
658     *                 {@link #SCAN_MODE_CONNECTABLE_DISCOVERABLE}
659     * @return     true if the scan mode was set, false otherwise
660     * @hide
661     */
662    public boolean setScanMode(int mode, int duration) {
663        if (getState() != STATE_ON) return false;
664        try {
665            return mService.setScanMode(mode, duration);
666        } catch (RemoteException e) {Log.e(TAG, "", e);}
667        return false;
668    }
669
670    /** @hide */
671    public boolean setScanMode(int mode) {
672        if (getState() != STATE_ON) return false;
673        return setScanMode(mode, 120);
674    }
675
676    /** @hide */
677    public int getDiscoverableTimeout() {
678        if (getState() != STATE_ON) return -1;
679        try {
680            return mService.getDiscoverableTimeout();
681        } catch (RemoteException e) {Log.e(TAG, "", e);}
682        return -1;
683    }
684
685    /** @hide */
686    public void setDiscoverableTimeout(int timeout) {
687        if (getState() != STATE_ON) return;
688        try {
689            mService.setDiscoverableTimeout(timeout);
690        } catch (RemoteException e) {Log.e(TAG, "", e);}
691    }
692
693    /**
694     * Start the remote device discovery process.
695     * <p>The discovery process usually involves an inquiry scan of about 12
696     * seconds, followed by a page scan of each new device to retrieve its
697     * Bluetooth name.
698     * <p>This is an asynchronous call, it will return immediately. Register
699     * for {@link #ACTION_DISCOVERY_STARTED} and {@link
700     * #ACTION_DISCOVERY_FINISHED} intents to determine exactly when the
701     * discovery starts and completes. Register for {@link
702     * BluetoothDevice#ACTION_FOUND} to be notified as remote Bluetooth devices
703     * are found.
704     * <p>Device discovery is a heavyweight procedure. New connections to
705     * remote Bluetooth devices should not be attempted while discovery is in
706     * progress, and existing connections will experience limited bandwidth
707     * and high latency. Use {@link #cancelDiscovery()} to cancel an ongoing
708     * discovery. Discovery is not managed by the Activity,
709     * but is run as a system service, so an application should always call
710     * {@link BluetoothAdapter#cancelDiscovery()} even if it
711     * did not directly request a discovery, just to be sure.
712     * <p>Device discovery will only find remote devices that are currently
713     * <i>discoverable</i> (inquiry scan enabled). Many Bluetooth devices are
714     * not discoverable by default, and need to be entered into a special mode.
715     * <p>If Bluetooth state is not {@link #STATE_ON}, this API
716     * will return false. After turning on Bluetooth,
717     * wait for {@link #ACTION_STATE_CHANGED} with {@link #STATE_ON}
718     * to get the updated value.
719     * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN}.
720     *
721     * @return true on success, false on error
722     */
723    public boolean startDiscovery() {
724        if (getState() != STATE_ON) return false;
725        try {
726            return mService.startDiscovery();
727        } catch (RemoteException e) {Log.e(TAG, "", e);}
728        return false;
729    }
730
731    /**
732     * Cancel the current device discovery process.
733     * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN}.
734     * <p>Because discovery is a heavyweight procedure for the Bluetooth
735     * adapter, this method should always be called before attempting to connect
736     * to a remote device with {@link
737     * android.bluetooth.BluetoothSocket#connect()}. Discovery is not managed by
738     * the  Activity, but is run as a system service, so an application should
739     * always call cancel discovery even if it did not directly request a
740     * discovery, just to be sure.
741     * <p>If Bluetooth state is not {@link #STATE_ON}, this API
742     * will return false. After turning on Bluetooth,
743     * wait for {@link #ACTION_STATE_CHANGED} with {@link #STATE_ON}
744     * to get the updated value.
745     *
746     * @return true on success, false on error
747     */
748    public boolean cancelDiscovery() {
749        if (getState() != STATE_ON) return false;
750        try {
751            return mService.cancelDiscovery();
752        } catch (RemoteException e) {Log.e(TAG, "", e);}
753        return false;
754    }
755
756    /**
757     * Return true if the local Bluetooth adapter is currently in the device
758     * discovery process.
759     * <p>Device discovery is a heavyweight procedure. New connections to
760     * remote Bluetooth devices should not be attempted while discovery is in
761     * progress, and existing connections will experience limited bandwidth
762     * and high latency. Use {@link #cancelDiscovery()} to cancel an ongoing
763     * discovery.
764     * <p>Applications can also register for {@link #ACTION_DISCOVERY_STARTED}
765     * or {@link #ACTION_DISCOVERY_FINISHED} to be notified when discovery
766     * starts or completes.
767     * <p>If Bluetooth state is not {@link #STATE_ON}, this API
768     * will return false. After turning on Bluetooth,
769     * wait for {@link #ACTION_STATE_CHANGED} with {@link #STATE_ON}
770     * to get the updated value.
771     * <p>Requires {@link android.Manifest.permission#BLUETOOTH}.
772     *
773     * @return true if discovering
774     */
775    public boolean isDiscovering() {
776        if (getState() != STATE_ON) return false;
777        try {
778            return mService.isDiscovering();
779        } catch (RemoteException e) {Log.e(TAG, "", e);}
780        return false;
781    }
782
783    /**
784     * Return the set of {@link BluetoothDevice} objects that are bonded
785     * (paired) to the local adapter.
786     * <p>If Bluetooth state is not {@link #STATE_ON}, this API
787     * will return an empty set. After turning on Bluetooth,
788     * wait for {@link #ACTION_STATE_CHANGED} with {@link #STATE_ON}
789     * to get the updated value.
790     * <p>Requires {@link android.Manifest.permission#BLUETOOTH}.
791     *
792     * @return unmodifiable set of {@link BluetoothDevice}, or null on error
793     */
794    public Set<BluetoothDevice> getBondedDevices() {
795        if (getState() != STATE_ON) {
796            return toDeviceSet(new BluetoothDevice[0]);
797        }
798        try {
799            return toDeviceSet(mService.getBondedDevices());
800        } catch (RemoteException e) {Log.e(TAG, "", e);}
801        return null;
802    }
803
804    /**
805     * Get the current connection state of the local Bluetooth adapter.
806     * This can be used to check whether the local Bluetooth adapter is connected
807     * to any profile of any other remote Bluetooth Device.
808     *
809     * <p> Use this function along with {@link #ACTION_CONNECTION_STATE_CHANGED}
810     * intent to get the connection state of the adapter.
811     *
812     * @return One of {@link #STATE_CONNECTED}, {@link #STATE_DISCONNECTED},
813     * {@link #STATE_CONNECTING} or {@link #STATE_DISCONNECTED}
814     *
815     * @hide
816     */
817    public int getConnectionState() {
818        if (getState() != STATE_ON) return BluetoothAdapter.STATE_DISCONNECTED;
819        try {
820            return mService.getAdapterConnectionState();
821        } catch (RemoteException e) {Log.e(TAG, "getConnectionState:", e);}
822        return BluetoothAdapter.STATE_DISCONNECTED;
823    }
824
825    /**
826     * Get the current connection state of a profile.
827     * This function can be used to check whether the local Bluetooth adapter
828     * is connected to any remote device for a specific profile.
829     * Profile can be one of {@link BluetoothProfile#HEALTH}, {@link BluetoothProfile#HEADSET},
830     * {@link BluetoothProfile#A2DP}.
831     *
832     * <p>Requires {@link android.Manifest.permission#BLUETOOTH}.
833     *
834     * <p> Return value can be one of
835     * {@link BluetoothProfile#STATE_DISCONNECTED},
836     * {@link BluetoothProfile#STATE_CONNECTING},
837     * {@link BluetoothProfile#STATE_CONNECTED},
838     * {@link BluetoothProfile#STATE_DISCONNECTING}
839     */
840    public int getProfileConnectionState(int profile) {
841        if (getState() != STATE_ON) return BluetoothProfile.STATE_DISCONNECTED;
842        try {
843            return mService.getProfileConnectionState(profile);
844        } catch (RemoteException e) {
845            Log.e(TAG, "getProfileConnectionState:", e);
846        }
847        return BluetoothProfile.STATE_DISCONNECTED;
848    }
849
850    /**
851    /**
852     * Picks RFCOMM channels until none are left.
853     * Avoids reserved channels.
854     */
855    private static class RfcommChannelPicker {
856        private static final int[] RESERVED_RFCOMM_CHANNELS =  new int[] {
857            10,  // HFAG
858            11,  // HSAG
859            12,  // OPUSH
860            19,  // PBAP
861        };
862        private static LinkedList<Integer> sChannels;  // master list of non-reserved channels
863        private static Random sRandom;
864
865        private final LinkedList<Integer> mChannels;  // local list of channels left to try
866
867        private final UUID mUuid;
868
869        public RfcommChannelPicker(UUID uuid) {
870            synchronized (RfcommChannelPicker.class) {
871                if (sChannels == null) {
872                    // lazy initialization of non-reserved rfcomm channels
873                    sChannels = new LinkedList<Integer>();
874                    for (int i = 1; i <= BluetoothSocket.MAX_RFCOMM_CHANNEL; i++) {
875                        sChannels.addLast(new Integer(i));
876                    }
877                    for (int reserved : RESERVED_RFCOMM_CHANNELS) {
878                        sChannels.remove(new Integer(reserved));
879                    }
880                    sRandom = new Random();
881                }
882                mChannels = (LinkedList<Integer>)sChannels.clone();
883            }
884            mUuid = uuid;
885        }
886        /* Returns next random channel, or -1 if we're out */
887        public int nextChannel() {
888            if (mChannels.size() == 0) {
889                return -1;
890            }
891            return mChannels.remove(sRandom.nextInt(mChannels.size()));
892        }
893    }
894
895    /**
896     * Create a listening, secure RFCOMM Bluetooth socket.
897     * <p>A remote device connecting to this socket will be authenticated and
898     * communication on this socket will be encrypted.
899     * <p>Use {@link BluetoothServerSocket#accept} to retrieve incoming
900     * connections from a listening {@link BluetoothServerSocket}.
901     * <p>Valid RFCOMM channels are in range 1 to 30.
902     * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN}
903     * @param channel RFCOMM channel to listen on
904     * @return a listening RFCOMM BluetoothServerSocket
905     * @throws IOException on error, for example Bluetooth not available, or
906     *                     insufficient permissions, or channel in use.
907     * @hide
908     */
909    public BluetoothServerSocket listenUsingRfcommOn(int channel) throws IOException {
910        BluetoothServerSocket socket = new BluetoothServerSocket(
911                BluetoothSocket.TYPE_RFCOMM, true, true, channel);
912        int errno = socket.mSocket.bindListen();
913        if (errno != 0) {
914            try {
915                socket.close();
916            } catch (IOException e) {}
917            socket.mSocket.throwErrnoNative(errno);
918        }
919        return socket;
920    }
921
922    /**
923     * Create a listening, secure RFCOMM Bluetooth socket with Service Record.
924     * <p>A remote device connecting to this socket will be authenticated and
925     * communication on this socket will be encrypted.
926     * <p>Use {@link BluetoothServerSocket#accept} to retrieve incoming
927     * connections from a listening {@link BluetoothServerSocket}.
928     * <p>The system will assign an unused RFCOMM channel to listen on.
929     * <p>The system will also register a Service Discovery
930     * Protocol (SDP) record with the local SDP server containing the specified
931     * UUID, service name, and auto-assigned channel. Remote Bluetooth devices
932     * can use the same UUID to query our SDP server and discover which channel
933     * to connect to. This SDP record will be removed when this socket is
934     * closed, or if this application closes unexpectedly.
935     * <p>Use {@link BluetoothDevice#createRfcommSocketToServiceRecord} to
936     * connect to this socket from another device using the same {@link UUID}.
937     * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
938     * @param name service name for SDP record
939     * @param uuid uuid for SDP record
940     * @return a listening RFCOMM BluetoothServerSocket
941     * @throws IOException on error, for example Bluetooth not available, or
942     *                     insufficient permissions, or channel in use.
943     */
944    public BluetoothServerSocket listenUsingRfcommWithServiceRecord(String name, UUID uuid)
945            throws IOException {
946        return createNewRfcommSocketAndRecord(name, uuid, true, true);
947    }
948
949    /**
950     * Create a listening, insecure RFCOMM Bluetooth socket with Service Record.
951     * <p>The link key is not required to be authenticated, i.e the communication may be
952     * vulnerable to Man In the Middle attacks. For Bluetooth 2.1 devices,
953     * the link will be encrypted, as encryption is mandartory.
954     * For legacy devices (pre Bluetooth 2.1 devices) the link will not
955     * be encrypted. Use {@link #listenUsingRfcommWithServiceRecord}, if an
956     * encrypted and authenticated communication channel is desired.
957     * <p>Use {@link BluetoothServerSocket#accept} to retrieve incoming
958     * connections from a listening {@link BluetoothServerSocket}.
959     * <p>The system will assign an unused RFCOMM channel to listen on.
960     * <p>The system will also register a Service Discovery
961     * Protocol (SDP) record with the local SDP server containing the specified
962     * UUID, service name, and auto-assigned channel. Remote Bluetooth devices
963     * can use the same UUID to query our SDP server and discover which channel
964     * to connect to. This SDP record will be removed when this socket is
965     * closed, or if this application closes unexpectedly.
966     * <p>Use {@link BluetoothDevice#createRfcommSocketToServiceRecord} to
967     * connect to this socket from another device using the same {@link UUID}.
968     * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
969     * @param name service name for SDP record
970     * @param uuid uuid for SDP record
971     * @return a listening RFCOMM BluetoothServerSocket
972     * @throws IOException on error, for example Bluetooth not available, or
973     *                     insufficient permissions, or channel in use.
974     */
975    public BluetoothServerSocket listenUsingInsecureRfcommWithServiceRecord(String name, UUID uuid)
976            throws IOException {
977        return createNewRfcommSocketAndRecord(name, uuid, false, false);
978    }
979
980     /**
981     * Create a listening, encrypted,
982     * RFCOMM Bluetooth socket with Service Record.
983     * <p>The link will be encrypted, but the link key is not required to be authenticated
984     * i.e the communication is vulnerable to Man In the Middle attacks. Use
985     * {@link #listenUsingRfcommWithServiceRecord}, to ensure an authenticated link key.
986     * <p> Use this socket if authentication of link key is not possible.
987     * For example, for Bluetooth 2.1 devices, if any of the devices does not have
988     * an input and output capability or just has the ability to display a numeric key,
989     * a secure socket connection is not possible and this socket can be used.
990     * Use {@link #listenUsingInsecureRfcommWithServiceRecord}, if encryption is not required.
991     * For Bluetooth 2.1 devices, the link will be encrypted, as encryption is mandartory.
992     * For more details, refer to the Security Model section 5.2 (vol 3) of
993     * Bluetooth Core Specification version 2.1 + EDR.
994     * <p>Use {@link BluetoothServerSocket#accept} to retrieve incoming
995     * connections from a listening {@link BluetoothServerSocket}.
996     * <p>The system will assign an unused RFCOMM channel to listen on.
997     * <p>The system will also register a Service Discovery
998     * Protocol (SDP) record with the local SDP server containing the specified
999     * UUID, service name, and auto-assigned channel. Remote Bluetooth devices
1000     * can use the same UUID to query our SDP server and discover which channel
1001     * to connect to. This SDP record will be removed when this socket is
1002     * closed, or if this application closes unexpectedly.
1003     * <p>Use {@link BluetoothDevice#createRfcommSocketToServiceRecord} to
1004     * connect to this socket from another device using the same {@link UUID}.
1005     * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
1006     * @param name service name for SDP record
1007     * @param uuid uuid for SDP record
1008     * @return a listening RFCOMM BluetoothServerSocket
1009     * @throws IOException on error, for example Bluetooth not available, or
1010     *                     insufficient permissions, or channel in use.
1011     * @hide
1012     */
1013    public BluetoothServerSocket listenUsingEncryptedRfcommWithServiceRecord(
1014            String name, UUID uuid) throws IOException {
1015        return createNewRfcommSocketAndRecord(name, uuid, false, true);
1016    }
1017
1018    private BluetoothServerSocket createNewRfcommSocketAndRecord(String name, UUID uuid,
1019            boolean auth, boolean encrypt) throws IOException {
1020        RfcommChannelPicker picker = new RfcommChannelPicker(uuid);
1021        BluetoothServerSocket socket;
1022        int channel;
1023        int errno;
1024        while (true) {
1025            channel = picker.nextChannel();
1026
1027            if (channel == -1) {
1028                throw new IOException("No available channels");
1029            }
1030
1031            socket = new BluetoothServerSocket(
1032                    BluetoothSocket.TYPE_RFCOMM, auth, encrypt, channel);
1033            errno = socket.mSocket.bindListen();
1034            if (errno == 0) {
1035                if (DBG) Log.d(TAG, "listening on RFCOMM channel " + channel);
1036                break;  // success
1037            } else if (errno == BluetoothSocket.EADDRINUSE) {
1038                if (DBG) Log.d(TAG, "RFCOMM channel " + channel + " in use");
1039                try {
1040                    socket.close();
1041                } catch (IOException e) {}
1042                continue;  // try another channel
1043            } else {
1044                try {
1045                    socket.close();
1046                } catch (IOException e) {}
1047                socket.mSocket.throwErrnoNative(errno);  // Exception as a result of bindListen()
1048            }
1049        }
1050
1051        int handle = -1;
1052        //TODO(BT):
1053        /*try {
1054            handle = mService.addRfcommServiceRecord(name, new ParcelUuid(uuid), channel,
1055                    new Binder());
1056        } catch (RemoteException e) {Log.e(TAG, "", e);}*/
1057        if (handle == -1) {
1058            try {
1059                socket.close();
1060            } catch (IOException e) {}
1061            throw new IOException("Not able to register SDP record for " + name);
1062        }
1063
1064        if (mServiceRecordHandler == null) {
1065            mServiceRecordHandler = new Handler(Looper.getMainLooper()) {
1066                    public void handleMessage(Message msg) {
1067                        /* handle socket closing */
1068                        int handle = msg.what;
1069                        // TODO(BT):
1070                        /*
1071                        try {
1072                            if (DBG) Log.d(TAG, "Removing service record " +
1073                                           Integer.toHexString(handle));
1074                        } catch (RemoteException e) {Log.e(TAG, "", e);}
1075                        */
1076                    }
1077                };
1078        }
1079        socket.setCloseHandler(mServiceRecordHandler, handle);
1080        return socket;
1081    }
1082
1083
1084    /**
1085     * Construct an unencrypted, unauthenticated, RFCOMM server socket.
1086     * Call #accept to retrieve connections to this socket.
1087     * @return An RFCOMM BluetoothServerSocket
1088     * @throws IOException On error, for example Bluetooth not available, or
1089     *                     insufficient permissions.
1090     * @hide
1091     */
1092    public BluetoothServerSocket listenUsingInsecureRfcommOn(int port) throws IOException {
1093        BluetoothServerSocket socket = new BluetoothServerSocket(
1094                BluetoothSocket.TYPE_RFCOMM, false, false, port);
1095        int errno = socket.mSocket.bindListen();
1096        if (errno != 0) {
1097            try {
1098                socket.close();
1099            } catch (IOException e) {}
1100            socket.mSocket.throwErrnoNative(errno);
1101        }
1102        return socket;
1103    }
1104
1105     /**
1106     * Construct an encrypted, RFCOMM server socket.
1107     * Call #accept to retrieve connections to this socket.
1108     * @return An RFCOMM BluetoothServerSocket
1109     * @throws IOException On error, for example Bluetooth not available, or
1110     *                     insufficient permissions.
1111     * @hide
1112     */
1113    public BluetoothServerSocket listenUsingEncryptedRfcommOn(int port)
1114            throws IOException {
1115        BluetoothServerSocket socket = new BluetoothServerSocket(
1116                BluetoothSocket.TYPE_RFCOMM, false, true, port);
1117        int errno = socket.mSocket.bindListen();
1118        if (errno != 0) {
1119            try {
1120                socket.close();
1121            } catch (IOException e) {}
1122            socket.mSocket.throwErrnoNative(errno);
1123        }
1124        return socket;
1125    }
1126
1127    /**
1128     * Construct a SCO server socket.
1129     * Call #accept to retrieve connections to this socket.
1130     * @return A SCO BluetoothServerSocket
1131     * @throws IOException On error, for example Bluetooth not available, or
1132     *                     insufficient permissions.
1133     * @hide
1134     */
1135    public static BluetoothServerSocket listenUsingScoOn() throws IOException {
1136        BluetoothServerSocket socket = new BluetoothServerSocket(
1137                BluetoothSocket.TYPE_SCO, false, false, -1);
1138        int errno = socket.mSocket.bindListen();
1139        if (errno != 0) {
1140            try {
1141                socket.close();
1142            } catch (IOException e) {}
1143            socket.mSocket.throwErrnoNative(errno);
1144        }
1145        return socket;
1146    }
1147
1148    /**
1149     * Read the local Out of Band Pairing Data
1150     * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
1151     *
1152     * @return Pair<byte[], byte[]> of Hash and Randomizer
1153     *
1154     * @hide
1155     */
1156    public Pair<byte[], byte[]> readOutOfBandData() {
1157        if (getState() != STATE_ON) return null;
1158        //TODO(BT
1159        /*
1160        try {
1161            byte[] hash;
1162            byte[] randomizer;
1163
1164            byte[] ret = mService.readOutOfBandData();
1165
1166            if (ret  == null || ret.length != 32) return null;
1167
1168            hash = Arrays.copyOfRange(ret, 0, 16);
1169            randomizer = Arrays.copyOfRange(ret, 16, 32);
1170
1171            if (DBG) {
1172                Log.d(TAG, "readOutOfBandData:" + Arrays.toString(hash) +
1173                  ":" + Arrays.toString(randomizer));
1174            }
1175            return new Pair<byte[], byte[]>(hash, randomizer);
1176
1177        } catch (RemoteException e) {Log.e(TAG, "", e);}*/
1178        return null;
1179    }
1180
1181    /**
1182     * Get the profile proxy object associated with the profile.
1183     *
1184     * <p>Profile can be one of {@link BluetoothProfile#HEALTH}, {@link BluetoothProfile#HEADSET} or
1185     * {@link BluetoothProfile#A2DP}. Clients must implements
1186     * {@link BluetoothProfile.ServiceListener} to get notified of
1187     * the connection status and to get the proxy object.
1188     *
1189     * @param context Context of the application
1190     * @param listener The service Listener for connection callbacks.
1191     * @param profile The Bluetooth profile; either {@link BluetoothProfile#HEALTH},
1192     *                {@link BluetoothProfile#HEADSET} or {@link BluetoothProfile#A2DP}.
1193     * @return true on success, false on error
1194     */
1195    public boolean getProfileProxy(Context context, BluetoothProfile.ServiceListener listener,
1196                                   int profile) {
1197        if (context == null || listener == null) return false;
1198
1199        if (profile == BluetoothProfile.HEADSET) {
1200            BluetoothHeadset headset = new BluetoothHeadset(context, listener);
1201            return true;
1202        } else if (profile == BluetoothProfile.A2DP) {
1203            BluetoothA2dp a2dp = new BluetoothA2dp(context, listener);
1204            return true;
1205        } else if (profile == BluetoothProfile.INPUT_DEVICE) {
1206            BluetoothInputDevice iDev = new BluetoothInputDevice(context, listener);
1207            return true;
1208        } else if (profile == BluetoothProfile.PAN) {
1209            BluetoothPan pan = new BluetoothPan(context, listener);
1210            return true;
1211        } else if (profile == BluetoothProfile.HEALTH) {
1212            BluetoothHealth health = new BluetoothHealth(context, listener);
1213            return true;
1214        } else {
1215            return false;
1216        }
1217    }
1218
1219    /**
1220     * Close the connection of the profile proxy to the Service.
1221     *
1222     * <p> Clients should call this when they are no longer using
1223     * the proxy obtained from {@link #getProfileProxy}.
1224     * Profile can be one of  {@link BluetoothProfile#HEALTH}, {@link BluetoothProfile#HEADSET} or
1225     * {@link BluetoothProfile#A2DP}
1226     *
1227     * @param profile
1228     * @param proxy Profile proxy object
1229     */
1230    public void closeProfileProxy(int profile, BluetoothProfile proxy) {
1231        if (proxy == null) return;
1232
1233        switch (profile) {
1234            case BluetoothProfile.HEADSET:
1235                BluetoothHeadset headset = (BluetoothHeadset)proxy;
1236                headset.close();
1237                break;
1238            case BluetoothProfile.A2DP:
1239                BluetoothA2dp a2dp = (BluetoothA2dp)proxy;
1240                a2dp.close();
1241                break;
1242            case BluetoothProfile.INPUT_DEVICE:
1243                BluetoothInputDevice iDev = (BluetoothInputDevice)proxy;
1244                iDev.close();
1245                break;
1246            case BluetoothProfile.PAN:
1247                BluetoothPan pan = (BluetoothPan)proxy;
1248                pan.close();
1249                break;
1250            case BluetoothProfile.HEALTH:
1251                BluetoothHealth health = (BluetoothHealth)proxy;
1252                health.close();
1253                break;
1254        }
1255    }
1256
1257    /**
1258     * Enable the Bluetooth Adapter, but don't auto-connect devices
1259     * and don't persist state. Only for use by system applications.
1260     * @hide
1261     */
1262    public boolean enableNoAutoConnect() {
1263        try {
1264            return mService.enableNoAutoConnect();
1265        } catch (RemoteException e) {Log.e(TAG, "", e);}
1266        return false;
1267    }
1268
1269    /**
1270     * Enable control of the Bluetooth Adapter for a single application.
1271     *
1272     * <p>Some applications need to use Bluetooth for short periods of time to
1273     * transfer data but don't want all the associated implications like
1274     * automatic connection to headsets etc.
1275     *
1276     * <p> Multiple applications can call this. This is reference counted and
1277     * Bluetooth disabled only when no one else is using it. There will be no UI
1278     * shown to the user while bluetooth is being enabled. Any user action will
1279     * override this call. For example, if user wants Bluetooth on and the last
1280     * user of this API wanted to disable Bluetooth, Bluetooth will not be
1281     * turned off.
1282     *
1283     * <p> This API is only meant to be used by internal applications. Third
1284     * party applications but use {@link #enable} and {@link #disable} APIs.
1285     *
1286     * <p> If this API returns true, it means the callback will be called.
1287     * The callback will be called with the current state of Bluetooth.
1288     * If the state is not what was requested, an internal error would be the
1289     * reason. If Bluetooth is already on and if this function is called to turn
1290     * it on, the api will return true and a callback will be called.
1291     *
1292     * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
1293     *
1294     * @param on True for on, false for off.
1295     * @param callback The callback to notify changes to the state.
1296     * @hide
1297     */
1298    public boolean changeApplicationBluetoothState(boolean on,
1299                                                   BluetoothStateChangeCallback callback) {
1300        if (callback == null) return false;
1301
1302        //TODO(BT)
1303        /*
1304        try {
1305            return mService.changeApplicationBluetoothState(on, new
1306                    StateChangeCallbackWrapper(callback), new Binder());
1307        } catch (RemoteException e) {
1308            Log.e(TAG, "changeBluetoothState", e);
1309        }*/
1310        return false;
1311    }
1312
1313    /**
1314     * @hide
1315     */
1316    public interface BluetoothStateChangeCallback {
1317        public void onBluetoothStateChange(boolean on);
1318    }
1319
1320    /**
1321     * @hide
1322     */
1323    public class StateChangeCallbackWrapper extends IBluetoothStateChangeCallback.Stub {
1324        private BluetoothStateChangeCallback mCallback;
1325
1326        StateChangeCallbackWrapper(BluetoothStateChangeCallback
1327                callback) {
1328            mCallback = callback;
1329        }
1330
1331        @Override
1332        public void onBluetoothStateChange(boolean on) {
1333            mCallback.onBluetoothStateChange(on);
1334        }
1335    }
1336
1337    private Set<BluetoothDevice> toDeviceSet(BluetoothDevice[] devices) {
1338        Set<BluetoothDevice> deviceSet = new HashSet<BluetoothDevice>(Arrays.asList(devices));
1339        return Collections.unmodifiableSet(deviceSet);
1340    }
1341
1342    /**
1343     * Validate a String Bluetooth address, such as "00:43:A8:23:10:F0"
1344     * <p>Alphabetic characters must be uppercase to be valid.
1345     *
1346     * @param address Bluetooth address as string
1347     * @return true if the address is valid, false otherwise
1348     */
1349    public static boolean checkBluetoothAddress(String address) {
1350        if (address == null || address.length() != ADDRESS_LENGTH) {
1351            return false;
1352        }
1353        for (int i = 0; i < ADDRESS_LENGTH; i++) {
1354            char c = address.charAt(i);
1355            switch (i % 3) {
1356            case 0:
1357            case 1:
1358                if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F')) {
1359                    // hex character, OK
1360                    break;
1361                }
1362                return false;
1363            case 2:
1364                if (c == ':') {
1365                    break;  // OK
1366                }
1367                return false;
1368            }
1369        }
1370        return true;
1371    }
1372}
1373