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