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