BluetoothAdapter.java revision cb1d354c1e9b458a0426cd08520d938012e32b34
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     * @hide
791     */
792    public int getProfileConnectionState(int profile) {
793        if (getState() != STATE_ON) return BluetoothProfile.STATE_DISCONNECTED;
794        try {
795            return mService.getProfileConnectionState(profile);
796        } catch (RemoteException e) {Log.e(TAG, "getProfileConnectionState:", e);}
797        return BluetoothProfile.STATE_DISCONNECTED;
798    }
799
800    /**
801    /**
802     * Picks RFCOMM channels until none are left.
803     * Avoids reserved channels.
804     */
805    private static class RfcommChannelPicker {
806        private static final int[] RESERVED_RFCOMM_CHANNELS =  new int[] {
807            10,  // HFAG
808            11,  // HSAG
809            12,  // OPUSH
810            19,  // PBAP
811        };
812        private static LinkedList<Integer> sChannels;  // master list of non-reserved channels
813        private static Random sRandom;
814
815        private final LinkedList<Integer> mChannels;  // local list of channels left to try
816
817        private final UUID mUuid;
818
819        public RfcommChannelPicker(UUID uuid) {
820            synchronized (RfcommChannelPicker.class) {
821                if (sChannels == null) {
822                    // lazy initialization of non-reserved rfcomm channels
823                    sChannels = new LinkedList<Integer>();
824                    for (int i = 1; i <= BluetoothSocket.MAX_RFCOMM_CHANNEL; i++) {
825                        sChannels.addLast(new Integer(i));
826                    }
827                    for (int reserved : RESERVED_RFCOMM_CHANNELS) {
828                        sChannels.remove(new Integer(reserved));
829                    }
830                    sRandom = new Random();
831                }
832                mChannels = (LinkedList<Integer>)sChannels.clone();
833            }
834            mUuid = uuid;
835        }
836        /* Returns next random channel, or -1 if we're out */
837        public int nextChannel() {
838            if (mChannels.size() == 0) {
839                return -1;
840            }
841            return mChannels.remove(sRandom.nextInt(mChannels.size()));
842        }
843    }
844
845    /**
846     * Create a listening, secure RFCOMM Bluetooth socket.
847     * <p>A remote device connecting to this socket will be authenticated and
848     * communication on this socket will be encrypted.
849     * <p>Use {@link BluetoothServerSocket#accept} to retrieve incoming
850     * connections from a listening {@link BluetoothServerSocket}.
851     * <p>Valid RFCOMM channels are in range 1 to 30.
852     * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN}
853     * @param channel RFCOMM channel to listen on
854     * @return a listening RFCOMM BluetoothServerSocket
855     * @throws IOException on error, for example Bluetooth not available, or
856     *                     insufficient permissions, or channel in use.
857     * @hide
858     */
859    public BluetoothServerSocket listenUsingRfcommOn(int channel) throws IOException {
860        BluetoothServerSocket socket = new BluetoothServerSocket(
861                BluetoothSocket.TYPE_RFCOMM, true, true, channel);
862        int errno = socket.mSocket.bindListen();
863        if (errno != 0) {
864            try {
865                socket.close();
866            } catch (IOException e) {}
867            socket.mSocket.throwErrnoNative(errno);
868        }
869        return socket;
870    }
871
872    /**
873     * Create a listening, secure RFCOMM Bluetooth socket with Service Record.
874     * <p>A remote device connecting to this socket will be authenticated and
875     * communication on this socket will be encrypted.
876     * <p>Use {@link BluetoothServerSocket#accept} to retrieve incoming
877     * connections from a listening {@link BluetoothServerSocket}.
878     * <p>The system will assign an unused RFCOMM channel to listen on.
879     * <p>The system will also register a Service Discovery
880     * Protocol (SDP) record with the local SDP server containing the specified
881     * UUID, service name, and auto-assigned channel. Remote Bluetooth devices
882     * can use the same UUID to query our SDP server and discover which channel
883     * to connect to. This SDP record will be removed when this socket is
884     * closed, or if this application closes unexpectedly.
885     * <p>Use {@link BluetoothDevice#createRfcommSocketToServiceRecord} to
886     * connect to this socket from another device using the same {@link UUID}.
887     * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
888     * @param name service name for SDP record
889     * @param uuid uuid for SDP record
890     * @return a listening RFCOMM BluetoothServerSocket
891     * @throws IOException on error, for example Bluetooth not available, or
892     *                     insufficient permissions, or channel in use.
893     */
894    public BluetoothServerSocket listenUsingRfcommWithServiceRecord(String name, UUID uuid)
895            throws IOException {
896        return createNewRfcommSocketAndRecord(name, uuid, true, true);
897    }
898
899    /**
900     * Create a listening, insecure RFCOMM Bluetooth socket with Service Record.
901     * <p>The link key is not required to be authenticated, i.e the communication may be
902     * vulnerable to Man In the Middle attacks. For Bluetooth 2.1 devices,
903     * the link will be encrypted, as encryption is mandartory.
904     * For legacy devices (pre Bluetooth 2.1 devices) the link will not
905     * be encrypted. Use {@link #listenUsingRfcommWithServiceRecord}, if an
906     * encrypted and authenticated communication channel is desired.
907     * <p>Use {@link BluetoothServerSocket#accept} to retrieve incoming
908     * connections from a listening {@link BluetoothServerSocket}.
909     * <p>The system will assign an unused RFCOMM channel to listen on.
910     * <p>The system will also register a Service Discovery
911     * Protocol (SDP) record with the local SDP server containing the specified
912     * UUID, service name, and auto-assigned channel. Remote Bluetooth devices
913     * can use the same UUID to query our SDP server and discover which channel
914     * to connect to. This SDP record will be removed when this socket is
915     * closed, or if this application closes unexpectedly.
916     * <p>Use {@link BluetoothDevice#createRfcommSocketToServiceRecord} to
917     * connect to this socket from another device using the same {@link UUID}.
918     * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
919     * @param name service name for SDP record
920     * @param uuid uuid for SDP record
921     * @return a listening RFCOMM BluetoothServerSocket
922     * @throws IOException on error, for example Bluetooth not available, or
923     *                     insufficient permissions, or channel in use.
924     */
925    public BluetoothServerSocket listenUsingInsecureRfcommWithServiceRecord(String name, UUID uuid)
926            throws IOException {
927        return createNewRfcommSocketAndRecord(name, uuid, false, false);
928    }
929
930     /**
931     * Create a listening, encrypted,
932     * RFCOMM Bluetooth socket with Service Record.
933     * <p>The link will be encrypted, but the link key is not required to be authenticated
934     * i.e the communication is vulnerable to Man In the Middle attacks. Use
935     * {@link #listenUsingRfcommWithServiceRecord}, to ensure an authenticated link key.
936     * <p> Use this socket if authentication of link key is not possible.
937     * For example, for Bluetooth 2.1 devices, if any of the devices does not have
938     * an input and output capability or just has the ability to display a numeric key,
939     * a secure socket connection is not possible and this socket can be used.
940     * Use {@link #listenUsingInsecureRfcommWithServiceRecord}, if encryption is not required.
941     * For Bluetooth 2.1 devices, the link will be encrypted, as encryption is mandartory.
942     * For more details, refer to the Security Model section 5.2 (vol 3) of
943     * Bluetooth Core Specification version 2.1 + EDR.
944     * <p>Use {@link BluetoothServerSocket#accept} to retrieve incoming
945     * connections from a listening {@link BluetoothServerSocket}.
946     * <p>The system will assign an unused RFCOMM channel to listen on.
947     * <p>The system will also register a Service Discovery
948     * Protocol (SDP) record with the local SDP server containing the specified
949     * UUID, service name, and auto-assigned channel. Remote Bluetooth devices
950     * can use the same UUID to query our SDP server and discover which channel
951     * to connect to. This SDP record will be removed when this socket is
952     * closed, or if this application closes unexpectedly.
953     * <p>Use {@link BluetoothDevice#createRfcommSocketToServiceRecord} to
954     * connect to this socket from another device using the same {@link UUID}.
955     * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
956     * @param name service name for SDP record
957     * @param uuid uuid for SDP record
958     * @return a listening RFCOMM BluetoothServerSocket
959     * @throws IOException on error, for example Bluetooth not available, or
960     *                     insufficient permissions, or channel in use.
961     * @hide
962     */
963    public BluetoothServerSocket listenUsingEncryptedRfcommWithServiceRecord(
964            String name, UUID uuid) throws IOException {
965        return createNewRfcommSocketAndRecord(name, uuid, false, true);
966    }
967
968    private BluetoothServerSocket createNewRfcommSocketAndRecord(String name, UUID uuid,
969            boolean auth, boolean encrypt) throws IOException {
970        RfcommChannelPicker picker = new RfcommChannelPicker(uuid);
971
972        BluetoothServerSocket socket;
973        int channel;
974        int errno;
975        while (true) {
976            channel = picker.nextChannel();
977
978            if (channel == -1) {
979                throw new IOException("No available channels");
980            }
981
982            socket = new BluetoothServerSocket(
983                    BluetoothSocket.TYPE_RFCOMM, auth, encrypt, channel);
984            errno = socket.mSocket.bindListen();
985            if (errno == 0) {
986                if (DBG) Log.d(TAG, "listening on RFCOMM channel " + channel);
987                break;  // success
988            } else if (errno == BluetoothSocket.EADDRINUSE) {
989                if (DBG) Log.d(TAG, "RFCOMM channel " + channel + " in use");
990                try {
991                    socket.close();
992                } catch (IOException e) {}
993                continue;  // try another channel
994            } else {
995                try {
996                    socket.close();
997                } catch (IOException e) {}
998                socket.mSocket.throwErrnoNative(errno);  // Exception as a result of bindListen()
999            }
1000        }
1001
1002        int handle = -1;
1003        try {
1004            handle = mService.addRfcommServiceRecord(name, new ParcelUuid(uuid), channel,
1005                    new Binder());
1006        } catch (RemoteException e) {Log.e(TAG, "", e);}
1007        if (handle == -1) {
1008            try {
1009                socket.close();
1010            } catch (IOException e) {}
1011            throw new IOException("Not able to register SDP record for " + name);
1012        }
1013        socket.setCloseHandler(mHandler, handle);
1014        return socket;
1015    }
1016
1017
1018    /**
1019     * Construct an unencrypted, unauthenticated, RFCOMM server socket.
1020     * Call #accept to retrieve connections to this socket.
1021     * @return An RFCOMM BluetoothServerSocket
1022     * @throws IOException On error, for example Bluetooth not available, or
1023     *                     insufficient permissions.
1024     * @hide
1025     */
1026    public BluetoothServerSocket listenUsingInsecureRfcommOn(int port) throws IOException {
1027        BluetoothServerSocket socket = new BluetoothServerSocket(
1028                BluetoothSocket.TYPE_RFCOMM, false, false, port);
1029        int errno = socket.mSocket.bindListen();
1030        if (errno != 0) {
1031            try {
1032                socket.close();
1033            } catch (IOException e) {}
1034            socket.mSocket.throwErrnoNative(errno);
1035        }
1036        return socket;
1037    }
1038
1039     /**
1040     * Construct an encrypted, RFCOMM server socket.
1041     * Call #accept to retrieve connections to this socket.
1042     * @return An RFCOMM BluetoothServerSocket
1043     * @throws IOException On error, for example Bluetooth not available, or
1044     *                     insufficient permissions.
1045     * @hide
1046     */
1047    public BluetoothServerSocket listenUsingEncryptedRfcommOn(int port)
1048            throws IOException {
1049        BluetoothServerSocket socket = new BluetoothServerSocket(
1050                BluetoothSocket.TYPE_RFCOMM, false, true, port);
1051        int errno = socket.mSocket.bindListen();
1052        if (errno != 0) {
1053            try {
1054                socket.close();
1055            } catch (IOException e) {}
1056            socket.mSocket.throwErrnoNative(errno);
1057        }
1058        return socket;
1059    }
1060
1061    /**
1062     * Construct a SCO server socket.
1063     * Call #accept to retrieve connections to this socket.
1064     * @return A SCO BluetoothServerSocket
1065     * @throws IOException On error, for example Bluetooth not available, or
1066     *                     insufficient permissions.
1067     * @hide
1068     */
1069    public static BluetoothServerSocket listenUsingScoOn() throws IOException {
1070        BluetoothServerSocket socket = new BluetoothServerSocket(
1071                BluetoothSocket.TYPE_SCO, false, false, -1);
1072        int errno = socket.mSocket.bindListen();
1073        if (errno != 0) {
1074            try {
1075                socket.close();
1076            } catch (IOException e) {}
1077            socket.mSocket.throwErrnoNative(errno);
1078        }
1079        return socket;
1080    }
1081
1082    /**
1083     * Read the local Out of Band Pairing Data
1084     * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
1085     *
1086     * @return Pair<byte[], byte[]> of Hash and Randomizer
1087     *
1088     * @hide
1089     */
1090    public Pair<byte[], byte[]> readOutOfBandData() {
1091        if (getState() != STATE_ON) return null;
1092        try {
1093            byte[] hash;
1094            byte[] randomizer;
1095
1096            byte[] ret = mService.readOutOfBandData();
1097
1098            if (ret  == null || ret.length != 32) return null;
1099
1100            hash = Arrays.copyOfRange(ret, 0, 16);
1101            randomizer = Arrays.copyOfRange(ret, 16, 32);
1102
1103            if (DBG) {
1104                Log.d(TAG, "readOutOfBandData:" + Arrays.toString(hash) +
1105                  ":" + Arrays.toString(randomizer));
1106            }
1107            return new Pair<byte[], byte[]>(hash, randomizer);
1108
1109        } catch (RemoteException e) {Log.e(TAG, "", e);}
1110        return null;
1111    }
1112
1113    /**
1114     * Get the profile proxy object associated with the profile.
1115     *
1116     * <p>Profile can be one of {@link BluetoothProfile#HEADSET} or
1117     * {@link BluetoothProfile#A2DP}. Clients must implements
1118     * {@link BluetoothProfile.ServiceListener} to get notified of
1119     * the connection status and to get the proxy object.
1120     *
1121     * @param context Context of the application
1122     * @param listener The service Listener for connection callbacks.
1123     * @param profile The Bluetooth profile; either {@link BluetoothProfile#HEADSET}
1124     *                or {@link BluetoothProfile#A2DP}.
1125     * @return true on success, false on error
1126     */
1127    public boolean getProfileProxy(Context context, BluetoothProfile.ServiceListener listener,
1128                                   int profile) {
1129        if (context == null || listener == null) return false;
1130
1131        if (profile == BluetoothProfile.HEADSET) {
1132            BluetoothHeadset headset = new BluetoothHeadset(context, listener);
1133            return true;
1134        } else if (profile == BluetoothProfile.A2DP) {
1135            BluetoothA2dp a2dp = new BluetoothA2dp(context, listener);
1136            return true;
1137        } else if (profile == BluetoothProfile.INPUT_DEVICE) {
1138            BluetoothInputDevice iDev = new BluetoothInputDevice(context, listener);
1139            return true;
1140        } else if (profile == BluetoothProfile.PAN) {
1141            BluetoothPan pan = new BluetoothPan(context, listener);
1142            return true;
1143        } else if (profile == BluetoothProfile.HEALTH) {
1144            BluetoothHealth health = new BluetoothHealth(context, listener);
1145            return true;
1146        } else {
1147            return false;
1148        }
1149    }
1150
1151    /**
1152     * Close the connection of the profile proxy to the Service.
1153     *
1154     * <p> Clients should call this when they are no longer using
1155     * the proxy obtained from {@link #getProfileProxy}.
1156     * Profile can be one of {@link BluetoothProfile#HEADSET} or
1157     * {@link BluetoothProfile#A2DP}
1158     *
1159     * @param profile
1160     * @param proxy Profile proxy object
1161     */
1162    public void closeProfileProxy(int profile, BluetoothProfile proxy) {
1163        if (profile == BluetoothProfile.HEADSET) {
1164            BluetoothHeadset headset = (BluetoothHeadset)proxy;
1165            if (headset != null) {
1166                headset.close();
1167            }
1168        }
1169    }
1170
1171    /**
1172     * Enable control of the Bluetooth Adapter for a single application.
1173     *
1174     * <p>Some applications need to use Bluetooth for short periods of time to
1175     * transfer data but don't want all the associated implications like
1176     * automatic connection to headsets etc.
1177     *
1178     * <p> Multiple applications can call this. This is reference counted and
1179     * Bluetooth disabled only when no one else is using it. There will be no UI
1180     * shown to the user while bluetooth is being enabled. Any user action will
1181     * override this call. For example, if user wants Bluetooth on and the last
1182     * user of this API wanted to disable Bluetooth, Bluetooth will not be
1183     * turned off.
1184     *
1185     * <p> This API is only meant to be used by internal applications. Third
1186     * party applications but use {@link #enable} and {@link #disable} APIs.
1187     *
1188     * <p> If this API returns true, it means the callback will be called.
1189     * The callback will be called with the current state of Bluetooth.
1190     * If the state is not what was requested, an internal error would be the
1191     * reason. If Bluetooth is already on and if this function is called to turn
1192     * it on, the api will return true and a callback will be called.
1193     *
1194     * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
1195     *
1196     * @param on True for on, false for off.
1197     * @param callback The callback to notify changes to the state.
1198     * @hide
1199     */
1200    public boolean changeApplicationBluetoothState(boolean on,
1201                                                   BluetoothStateChangeCallback callback) {
1202        if (callback == null) return false;
1203
1204        try {
1205            return mService.changeApplicationBluetoothState(on, new
1206                    StateChangeCallbackWrapper(callback), new Binder());
1207        } catch (RemoteException e) {
1208            Log.e(TAG, "changeBluetoothState", e);
1209        }
1210        return false;
1211    }
1212
1213    /**
1214     * @hide
1215     */
1216    public interface BluetoothStateChangeCallback {
1217        public void onBluetoothStateChange(boolean on);
1218    }
1219
1220    /**
1221     * @hide
1222     */
1223    public class StateChangeCallbackWrapper extends IBluetoothStateChangeCallback.Stub {
1224        private BluetoothStateChangeCallback mCallback;
1225
1226        StateChangeCallbackWrapper(BluetoothStateChangeCallback
1227                callback) {
1228            mCallback = callback;
1229        }
1230
1231        @Override
1232        public void onBluetoothStateChange(boolean on) {
1233            mCallback.onBluetoothStateChange(on);
1234        }
1235    }
1236
1237    private Set<BluetoothDevice> toDeviceSet(String[] addresses) {
1238        Set<BluetoothDevice> devices = new HashSet<BluetoothDevice>(addresses.length);
1239        for (int i = 0; i < addresses.length; i++) {
1240            devices.add(getRemoteDevice(addresses[i]));
1241        }
1242        return Collections.unmodifiableSet(devices);
1243    }
1244
1245    private Handler mHandler = new Handler() {
1246        public void handleMessage(Message msg) {
1247            /* handle socket closing */
1248            int handle = msg.what;
1249            try {
1250                if (DBG) Log.d(TAG, "Removing service record " + Integer.toHexString(handle));
1251                mService.removeServiceRecord(handle);
1252            } catch (RemoteException e) {Log.e(TAG, "", e);}
1253        }
1254    };
1255
1256    /**
1257     * Validate a Bluetooth address, such as "00:43:A8:23:10:F0"
1258     * <p>Alphabetic characters must be uppercase to be valid.
1259     *
1260     * @param address Bluetooth address as string
1261     * @return true if the address is valid, false otherwise
1262     */
1263    public static boolean checkBluetoothAddress(String address) {
1264        if (address == null || address.length() != ADDRESS_LENGTH) {
1265            return false;
1266        }
1267        for (int i = 0; i < ADDRESS_LENGTH; i++) {
1268            char c = address.charAt(i);
1269            switch (i % 3) {
1270            case 0:
1271            case 1:
1272                if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F')) {
1273                    // hex character, OK
1274                    break;
1275                }
1276                return false;
1277            case 2:
1278                if (c == ':') {
1279                    break;  // OK
1280                }
1281                return false;
1282            }
1283        }
1284        return true;
1285    }
1286}
1287