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