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