BluetoothAdapter.java revision 6d95fc0a2ca910212a43c4547c0ef000659b72dc
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.os.Binder;
22import android.os.Handler;
23import android.os.IBinder;
24import android.os.Message;
25import android.os.ParcelUuid;
26import android.os.RemoteException;
27import android.os.ServiceManager;
28import android.util.Log;
29
30import java.io.IOException;
31import java.util.Collections;
32import java.util.HashSet;
33import java.util.LinkedList;
34import java.util.Random;
35import java.util.Set;
36import java.util.UUID;
37
38/**
39 * Represents the local device Bluetooth adapter. The {@link BluetoothAdapter}
40 * lets you perform fundamental Bluetooth tasks, such as initiate
41 * device discovery, query a list of bonded (paired) devices,
42 * instantiate a {@link BluetoothDevice} using a known MAC address, and create
43 * a {@link BluetoothServerSocket} to listen for connection requests from other
44 * devices.
45 *
46 * <p>To get a {@link BluetoothAdapter} representing the local Bluetooth
47 * adapter, call the static {@link #getDefaultAdapter} method.
48 * Fundamentally, this is your starting point for all
49 * Bluetooth actions. Once you have the local adapter, you can get a set of
50 * {@link BluetoothDevice} objects representing all paired devices with
51 * {@link #getBondedDevices()}; start device discovery with
52 * {@link #startDiscovery()}; or create a {@link BluetoothServerSocket} to
53 * listen for incoming connection requests with
54 * {@link #listenUsingRfcommWithServiceRecord(String,UUID)}.
55 *
56 * <p class="note"><strong>Note:</strong>
57 * Most methods require the {@link android.Manifest.permission#BLUETOOTH}
58 * permission and some also require the
59 * {@link android.Manifest.permission#BLUETOOTH_ADMIN} permission.
60 *
61 * {@see BluetoothDevice}
62 * {@see BluetoothServerSocket}
63 */
64public final class BluetoothAdapter {
65    private static final String TAG = "BluetoothAdapter";
66    private static final boolean DBG = false;
67
68    /**
69     * Sentinel error value for this class. Guaranteed to not equal any other
70     * integer constant in this class. Provided as a convenience for functions
71     * that require a sentinel error value, for example:
72     * <p><code>Intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
73     * BluetoothAdapter.ERROR)</code>
74     */
75    public static final int ERROR = Integer.MIN_VALUE;
76
77    /**
78     * Broadcast Action: The state of the local Bluetooth adapter has been
79     * changed.
80     * <p>For example, Bluetooth has been turned on or off.
81     * <p>Always contains the extra fields {@link #EXTRA_STATE} and {@link
82     * #EXTRA_PREVIOUS_STATE} containing the new and old states
83     * respectively.
84     * <p>Requires {@link android.Manifest.permission#BLUETOOTH} to receive.
85     */
86    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
87    public static final String ACTION_STATE_CHANGED =
88            "android.bluetooth.adapter.action.STATE_CHANGED";
89
90    /**
91     * Used as an int extra field in {@link #ACTION_STATE_CHANGED}
92     * intents to request the current power state. Possible values are:
93     * {@link #STATE_OFF},
94     * {@link #STATE_TURNING_ON},
95     * {@link #STATE_ON},
96     * {@link #STATE_TURNING_OFF},
97     */
98    public static final String EXTRA_STATE =
99            "android.bluetooth.adapter.extra.STATE";
100    /**
101     * Used as an int extra field in {@link #ACTION_STATE_CHANGED}
102     * intents to request the previous 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_PREVIOUS_STATE =
109            "android.bluetooth.adapter.extra.PREVIOUS_STATE";
110
111    /**
112     * Indicates the local Bluetooth adapter is off.
113     */
114    public static final int STATE_OFF = 10;
115    /**
116     * Indicates the local Bluetooth adapter is turning on. However local
117     * clients should wait for {@link #STATE_ON} before attempting to
118     * use the adapter.
119     */
120    public static final int STATE_TURNING_ON = 11;
121    /**
122     * Indicates the local Bluetooth adapter is on, and ready for use.
123     */
124    public static final int STATE_ON = 12;
125    /**
126     * Indicates the local Bluetooth adapter is turning off. Local clients
127     * should immediately attempt graceful disconnection of any remote links.
128     */
129    public static final int STATE_TURNING_OFF = 13;
130
131    /**
132     * Activity Action: Show a system activity that requests discoverable mode.
133     * This activity will also request the user to turn on Bluetooth if it
134     * is not currently enabled.
135     * <p>Discoverable mode is equivalent to {@link
136     * #SCAN_MODE_CONNECTABLE_DISCOVERABLE}. It allows remote devices to see
137     * this Bluetooth adapter when they perform a discovery.
138     * <p>For privacy, Android is not discoverable by default.
139     * <p>The sender of this Intent can optionally use extra field {@link
140     * #EXTRA_DISCOVERABLE_DURATION} to request the duration of
141     * discoverability. Currently the default duration is 120 seconds, and
142     * maximum duration is capped at 300 seconds for each request.
143     * <p>Notification of the result of this activity is posted using the
144     * {@link android.app.Activity#onActivityResult} callback. The
145     * <code>resultCode</code>
146     * will be the duration (in seconds) of discoverability, or a negative
147     * value if the user rejected discoverability.
148     * <p>Applications can also listen for {@link #ACTION_SCAN_MODE_CHANGED}
149     * for global notification whenever the scan mode changes. For example, an
150     * application can be notified when the device has ended discoverability.
151     * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
152     */
153    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
154    public static final String ACTION_REQUEST_DISCOVERABLE =
155            "android.bluetooth.adapter.action.REQUEST_DISCOVERABLE";
156
157    /**
158     * Used as an optional int extra field in {@link
159     * #ACTION_REQUEST_DISCOVERABLE} intents to request a specific duration
160     * for discoverability in seconds. The current default is 120 seconds, and
161     * requests over 300 seconds will be capped. These values could change.
162     */
163    public static final String EXTRA_DISCOVERABLE_DURATION =
164            "android.bluetooth.adapter.extra.DISCOVERABLE_DURATION";
165
166    /**
167     * Activity Action: Show a system activity that allows the user to turn on
168     * Bluetooth.
169     * <p>This system activity will return once Bluetooth has completed turning
170     * on, or the user has decided not to turn Bluetooth on.
171     * <p>Notification of the result of this activity is posted using the
172     * {@link android.app.Activity#onActivityResult} callback. The
173     * <code>resultCode</code>
174     * will be negative if the user did not turn on Bluetooth, and non-negative
175     * if Bluetooth has been turned on.
176     * <p>Applications can also listen for {@link #ACTION_STATE_CHANGED}
177     * for global notification whenever Bluetooth is turned on or off.
178     * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
179     */
180    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
181    public static final String ACTION_REQUEST_ENABLE =
182            "android.bluetooth.adapter.action.REQUEST_ENABLE";
183
184    /**
185     * Broadcast Action: Indicates the Bluetooth scan mode of the local Adapter
186     * has changed.
187     * <p>Always contains the extra fields {@link #EXTRA_SCAN_MODE} and {@link
188     * #EXTRA_PREVIOUS_SCAN_MODE} containing the new and old scan modes
189     * respectively.
190     * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
191     */
192    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
193    public static final String ACTION_SCAN_MODE_CHANGED =
194            "android.bluetooth.adapter.action.SCAN_MODE_CHANGED";
195
196    /**
197     * Used as an int extra field in {@link #ACTION_SCAN_MODE_CHANGED}
198     * intents to request the current scan mode. Possible values are:
199     * {@link #SCAN_MODE_NONE},
200     * {@link #SCAN_MODE_CONNECTABLE},
201     * {@link #SCAN_MODE_CONNECTABLE_DISCOVERABLE},
202     */
203    public static final String EXTRA_SCAN_MODE = "android.bluetooth.adapter.extra.SCAN_MODE";
204    /**
205     * Used as an int extra field in {@link #ACTION_SCAN_MODE_CHANGED}
206     * intents to request the previous scan mode. Possible values are:
207     * {@link #SCAN_MODE_NONE},
208     * {@link #SCAN_MODE_CONNECTABLE},
209     * {@link #SCAN_MODE_CONNECTABLE_DISCOVERABLE},
210     */
211    public static final String EXTRA_PREVIOUS_SCAN_MODE =
212            "android.bluetooth.adapter.extra.PREVIOUS_SCAN_MODE";
213
214    /**
215     * Indicates that both inquiry scan and page scan are disabled on the local
216     * Bluetooth adapter. Therefore this device is neither discoverable
217     * nor connectable from remote Bluetooth devices.
218     */
219    public static final int SCAN_MODE_NONE = 20;
220    /**
221     * Indicates that inquiry scan is disabled, but page scan is enabled on the
222     * local Bluetooth adapter. Therefore this device is not discoverable from
223     * remote Bluetooth devices, but is connectable from remote devices that
224     * have previously discovered this device.
225     */
226    public static final int SCAN_MODE_CONNECTABLE = 21;
227    /**
228     * Indicates that both inquiry scan and page scan are enabled on the local
229     * Bluetooth adapter. Therefore this device is both discoverable and
230     * connectable from remote Bluetooth devices.
231     */
232    public static final int SCAN_MODE_CONNECTABLE_DISCOVERABLE = 23;
233
234
235    /**
236     * Broadcast Action: The local Bluetooth adapter has started the remote
237     * device discovery process.
238     * <p>This usually involves an inquiry scan of about 12 seconds, followed
239     * by a page scan of each new device to retrieve its Bluetooth name.
240     * <p>Register for {@link BluetoothDevice#ACTION_FOUND} to be notified as
241     * remote Bluetooth devices are found.
242     * <p>Device discovery is a heavyweight procedure. New connections to
243     * remote Bluetooth devices should not be attempted while discovery is in
244     * progress, and existing connections will experience limited bandwidth
245     * and high latency. Use {@link #cancelDiscovery()} to cancel an ongoing
246     * discovery.
247     * <p>Requires {@link android.Manifest.permission#BLUETOOTH} to receive.
248     */
249    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
250    public static final String ACTION_DISCOVERY_STARTED =
251            "android.bluetooth.adapter.action.DISCOVERY_STARTED";
252    /**
253     * Broadcast Action: The local Bluetooth adapter has finished the device
254     * discovery process.
255     * <p>Requires {@link android.Manifest.permission#BLUETOOTH} to receive.
256     */
257    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
258    public static final String ACTION_DISCOVERY_FINISHED =
259            "android.bluetooth.adapter.action.DISCOVERY_FINISHED";
260
261    /**
262     * Broadcast Action: The local Bluetooth adapter has changed its friendly
263     * Bluetooth name.
264     * <p>This name is visible to remote Bluetooth devices.
265     * <p>Always contains the extra field {@link #EXTRA_LOCAL_NAME} containing
266     * the name.
267     * <p>Requires {@link android.Manifest.permission#BLUETOOTH} to receive.
268     */
269    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
270    public static final String ACTION_LOCAL_NAME_CHANGED =
271            "android.bluetooth.adapter.action.LOCAL_NAME_CHANGED";
272    /**
273     * Used as a String extra field in {@link #ACTION_LOCAL_NAME_CHANGED}
274     * intents to request the local Bluetooth name.
275     */
276    public static final String EXTRA_LOCAL_NAME = "android.bluetooth.adapter.extra.LOCAL_NAME";
277
278    /** @hide */
279    public static final String BLUETOOTH_SERVICE = "bluetooth";
280
281    private static final int ADDRESS_LENGTH = 17;
282
283    /**
284     * Lazyily initialized singleton. Guaranteed final after first object
285     * constructed.
286     */
287    private static BluetoothAdapter sAdapter;
288
289    private final IBluetooth mService;
290
291    /**
292     * Get a handle to the default local Bluetooth adapter.
293     * <p>Currently Android only supports one Bluetooth adapter, but the API
294     * could be extended to support more. This will always return the default
295     * adapter.
296     * @return the default local adapter, or null if Bluetooth is not supported
297     *         on this hardware platform
298     */
299    public static synchronized BluetoothAdapter getDefaultAdapter() {
300        if (sAdapter == null) {
301            IBinder b = ServiceManager.getService(BluetoothAdapter.BLUETOOTH_SERVICE);
302            if (b != null) {
303                IBluetooth service = IBluetooth.Stub.asInterface(b);
304                sAdapter = new BluetoothAdapter(service);
305            }
306        }
307        return sAdapter;
308    }
309
310    /**
311     * Use {@link #getDefaultAdapter} to get the BluetoothAdapter instance.
312     * @hide
313     */
314    public BluetoothAdapter(IBluetooth service) {
315        if (service == null) {
316            throw new IllegalArgumentException("service is null");
317        }
318        mService = service;
319    }
320
321    /**
322     * Get a {@link BluetoothDevice} object for the given Bluetooth hardware
323     * address.
324     * <p>Valid Bluetooth hardware addresses must be upper case, in a format
325     * such as "00:11:22:33:AA:BB". The helper {@link #checkBluetoothAddress} is
326     * available to validate a Bluetooth address.
327     * <p>A {@link BluetoothDevice} will always be returned for a valid
328     * hardware address, even if this adapter has never seen that device.
329     *
330     * @param address valid Bluetooth MAC address
331     * @throws IllegalArgumentException if address is invalid
332     */
333    public BluetoothDevice getRemoteDevice(String address) {
334        return new BluetoothDevice(address);
335    }
336
337    /**
338     * Return true if Bluetooth is currently enabled and ready for use.
339     * <p>Equivalent to:
340     * <code>getBluetoothState() == STATE_ON</code>
341     * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
342     *
343     * @return true if the local adapter is turned on
344     */
345    public boolean isEnabled() {
346        try {
347            return mService.isEnabled();
348        } catch (RemoteException e) {Log.e(TAG, "", e);}
349        return false;
350    }
351
352    /**
353     * Get the current state of the local Bluetooth adapter.
354     * <p>Possible return values are
355     * {@link #STATE_OFF},
356     * {@link #STATE_TURNING_ON},
357     * {@link #STATE_ON},
358     * {@link #STATE_TURNING_OFF}.
359     * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
360     *
361     * @return current state of Bluetooth adapter
362     */
363    public int getState() {
364        try {
365            return mService.getBluetoothState();
366        } catch (RemoteException e) {Log.e(TAG, "", e);}
367        return STATE_OFF;
368    }
369
370    /**
371     * Turn on the local Bluetooth adapter.
372     * <p>This powers on the underlying Bluetooth hardware, and starts all
373     * Bluetooth system services.
374     * <p>This is an asynchronous call: it will return immediately, and
375     * clients should listen for {@link #ACTION_STATE_CHANGED}
376     * to be notified of subsequent adapter state changes. If this call returns
377     * true, then the adapter state will immediately transition from {@link
378     * #STATE_OFF} to {@link #STATE_TURNING_ON}, and some time
379     * later transition to either {@link #STATE_OFF} or {@link
380     * #STATE_ON}. If this call returns false then there was an
381     * immediate problem that will prevent the adapter from being turned on -
382     * such as Airplane mode, or the adapter is already turned on.
383     * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN}
384     *
385     * @return true to indicate adapter startup has begun, or false on
386     *         immediate error
387     */
388    public boolean enable() {
389        try {
390            return mService.enable();
391        } catch (RemoteException e) {Log.e(TAG, "", e);}
392        return false;
393    }
394
395    /**
396     * Turn off the local Bluetooth adapter.
397     * <p>This gracefully shuts down all Bluetooth connections, stops Bluetooth
398     * system services, and powers down the underlying Bluetooth hardware.
399     * <p>This is an asynchronous call: it will return immediately, and
400     * clients should listen for {@link #ACTION_STATE_CHANGED}
401     * to be notified of subsequent adapter state changes. If this call returns
402     * true, then the adapter state will immediately transition from {@link
403     * #STATE_ON} to {@link #STATE_TURNING_OFF}, and some time
404     * later transition to either {@link #STATE_OFF} or {@link
405     * #STATE_ON}. If this call returns false then there was an
406     * immediate problem that will prevent the adapter from being turned off -
407     * such as the adapter already being turned off.
408     * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN}
409     *
410     * @return true to indicate adapter shutdown has begun, or false on
411     *         immediate error
412     */
413    public boolean disable() {
414        try {
415            return mService.disable(true);
416        } catch (RemoteException e) {Log.e(TAG, "", e);}
417        return false;
418    }
419
420    /**
421     * Returns the hardware address of the local Bluetooth adapter.
422     * <p>For example, "00:11:22:AA:BB:CC".
423     * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
424     *
425     * @return Bluetooth hardware address as string
426     */
427    public String getAddress() {
428        try {
429            return mService.getAddress();
430        } catch (RemoteException e) {Log.e(TAG, "", e);}
431        return null;
432    }
433
434    /**
435     * Get the friendly Bluetooth name of the local Bluetooth adapter.
436     * <p>This name is visible to remote Bluetooth devices.
437     * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
438     *
439     * @return the Bluetooth name, or null on error
440     */
441    public String getName() {
442        try {
443            return mService.getName();
444        } catch (RemoteException e) {Log.e(TAG, "", e);}
445        return null;
446    }
447
448    /**
449     * Set the friendly Bluetooth name of the local Bluetoth adapter.
450     * <p>This name is visible to remote Bluetooth devices.
451     * <p>Valid Bluetooth names are a maximum of 248 UTF-8 characters, however
452     * many remote devices can only display the first 40 characters, and some
453     * may be limited to just 20.
454     * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN}
455     *
456     * @param name a valid Bluetooth name
457     * @return     true if the name was set, false otherwise
458     */
459    public boolean setName(String name) {
460        try {
461            return mService.setName(name);
462        } catch (RemoteException e) {Log.e(TAG, "", e);}
463        return false;
464    }
465
466    /**
467     * Get the current Bluetooth scan mode of the local Bluetooth adaper.
468     * <p>The Bluetooth scan mode determines if the local adapter is
469     * connectable and/or discoverable from remote Bluetooth devices.
470     * <p>Possible values are:
471     * {@link #SCAN_MODE_NONE},
472     * {@link #SCAN_MODE_CONNECTABLE},
473     * {@link #SCAN_MODE_CONNECTABLE_DISCOVERABLE}.
474     * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
475     *
476     * @return scan mode
477     */
478    public int getScanMode() {
479        try {
480            return mService.getScanMode();
481        } catch (RemoteException e) {Log.e(TAG, "", e);}
482        return SCAN_MODE_NONE;
483    }
484
485    /**
486     * Set the Bluetooth scan mode of the local Bluetooth adapter.
487     * <p>The Bluetooth scan mode determines if the local adapter is
488     * connectable and/or discoverable from remote Bluetooth devices.
489     * <p>For privacy reasons, discoverable mode is automatically turned off
490     * after <code>duration</code> seconds. For example, 120 seconds should be
491     * enough for a remote device to initiate and complete its discovery
492     * process.
493     * <p>Valid scan mode values are:
494     * {@link #SCAN_MODE_NONE},
495     * {@link #SCAN_MODE_CONNECTABLE},
496     * {@link #SCAN_MODE_CONNECTABLE_DISCOVERABLE}.
497     * <p>Requires {@link android.Manifest.permission#WRITE_SECURE_SETTINGS}
498     * <p>Applications cannot set the scan mode. They should use
499     * <code>startActivityForResult(
500     * BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE})
501     * </code>instead.
502     *
503     * @param mode valid scan mode
504     * @param duration time in seconds to apply scan mode, only used for
505     *                 {@link #SCAN_MODE_CONNECTABLE_DISCOVERABLE}
506     * @return     true if the scan mode was set, false otherwise
507     * @hide
508     */
509    public boolean setScanMode(int mode, int duration) {
510        try {
511            return mService.setScanMode(mode, duration);
512        } catch (RemoteException e) {Log.e(TAG, "", e);}
513        return false;
514    }
515
516    /** @hide */
517    public boolean setScanMode(int mode) {
518        return setScanMode(mode, 120);
519    }
520
521    /** @hide */
522    public int getDiscoverableTimeout() {
523        try {
524            return mService.getDiscoverableTimeout();
525        } catch (RemoteException e) {Log.e(TAG, "", e);}
526        return -1;
527    }
528
529    /** @hide */
530    public void setDiscoverableTimeout(int timeout) {
531        try {
532            mService.setDiscoverableTimeout(timeout);
533        } catch (RemoteException e) {Log.e(TAG, "", e);}
534    }
535
536    /**
537     * Start the remote device discovery process.
538     * <p>The discovery process usually involves an inquiry scan of about 12
539     * seconds, followed by a page scan of each new device to retrieve its
540     * Bluetooth name.
541     * <p>This is an asynchronous call, it will return immediately. Register
542     * for {@link #ACTION_DISCOVERY_STARTED} and {@link
543     * #ACTION_DISCOVERY_FINISHED} intents to determine exactly when the
544     * discovery starts and completes. Register for {@link
545     * BluetoothDevice#ACTION_FOUND} to be notified as remote Bluetooth devices
546     * are found.
547     * <p>Device discovery is a heavyweight procedure. New connections to
548     * remote Bluetooth devices should not be attempted while discovery is in
549     * progress, and existing connections will experience limited bandwidth
550     * and high latency. Use {@link #cancelDiscovery()} to cancel an ongoing
551     * discovery. Discovery is not managed by the Activity,
552     * but is run as a system service, so an application should always call
553     * {@link BluetoothAdapter#cancelDiscovery()} even if it
554     * did not directly request a discovery, just to be sure.
555     * <p>Device discovery will only find remote devices that are currently
556     * <i>discoverable</i> (inquiry scan enabled). Many Bluetooth devices are
557     * not discoverable by default, and need to be entered into a special mode.
558     * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN}.
559     *
560     * @return true on success, false on error
561     */
562    public boolean startDiscovery() {
563        try {
564            return mService.startDiscovery();
565        } catch (RemoteException e) {Log.e(TAG, "", e);}
566        return false;
567    }
568
569    /**
570     * Cancel the current device discovery process.
571     * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN}.
572     * <p>Because discovery is a heavyweight precedure for the Bluetooth
573     * adapter, this method should always be called before attempting to connect
574     * to a remote device with {@link
575     * android.bluetooth.BluetoothSocket#connect()}. Discovery is not managed by
576     * the  Activity, but is run as a system service, so an application should
577     * always call cancel discovery even if it did not directly request a
578     * discovery, just to be sure.
579     *
580     * @return true on success, false on error
581     */
582    public boolean cancelDiscovery() {
583        try {
584            mService.cancelDiscovery();
585        } catch (RemoteException e) {Log.e(TAG, "", e);}
586        return false;
587    }
588
589    /**
590     * Return true if the local Bluetooth adapter is currently in the device
591     * discovery process.
592     * <p>Device discovery is a heavyweight procedure. New connections to
593     * remote Bluetooth devices should not be attempted while discovery is in
594     * progress, and existing connections will experience limited bandwidth
595     * and high latency. Use {@link #cancelDiscovery()} to cancel an ongoing
596     * discovery.
597     * <p>Applications can also register for {@link #ACTION_DISCOVERY_STARTED}
598     * or {@link #ACTION_DISCOVERY_FINISHED} to be notified when discovery
599     * starts or completes.
600     * <p>Requires {@link android.Manifest.permission#BLUETOOTH}.
601     *
602     * @return true if discovering
603     */
604    public boolean isDiscovering() {
605        try {
606            return mService.isDiscovering();
607        } catch (RemoteException e) {Log.e(TAG, "", e);}
608        return false;
609    }
610
611    /**
612     * Return the set of {@link BluetoothDevice} objects that are bonded
613     * (paired) to the local adapter.
614     * <p>Requires {@link android.Manifest.permission#BLUETOOTH}.
615     *
616     * @return unmodifiable set of {@link BluetoothDevice}, or null on error
617     */
618    public Set<BluetoothDevice> getBondedDevices() {
619        try {
620            return toDeviceSet(mService.listBonds());
621        } catch (RemoteException e) {Log.e(TAG, "", e);}
622        return null;
623    }
624
625    /**
626     * Picks RFCOMM channels until none are left.
627     * Avoids reserved channels.
628     * Ideally we would pick random channels, but in the current implementation
629     * we start with the channel that is the hash of the UUID, and try every
630     * available channel from there. This means that in most cases a given
631     * uuid will use the same channel. This is a workaround for a Bluez SDP
632     * bug where we are not updating the cache when the channel changes for a
633     * uuid.
634     * TODO: Fix the Bluez SDP caching bug, and go back to random channel
635     * selection
636     */
637    private static class RfcommChannelPicker {
638        private static final int[] RESERVED_RFCOMM_CHANNELS =  new int[] {
639            10,  // HFAG
640            11,  // HSAG
641            12,  // OPUSH
642            19,  // PBAP
643        };
644        private static LinkedList<Integer> sChannels;  // master list of non-reserved channels
645        private static Random sRandom;
646
647        private final LinkedList<Integer> mChannels;  // local list of channels left to try
648
649        private final UUID mUuid;
650
651        public RfcommChannelPicker(UUID uuid) {
652            synchronized (RfcommChannelPicker.class) {
653                if (sChannels == null) {
654                    // lazy initialization of non-reserved rfcomm channels
655                    sChannels = new LinkedList<Integer>();
656                    for (int i = 1; i <= BluetoothSocket.MAX_RFCOMM_CHANNEL; i++) {
657                        sChannels.addLast(new Integer(i));
658                    }
659                    for (int reserved : RESERVED_RFCOMM_CHANNELS) {
660                        sChannels.remove(new Integer(reserved));
661                    }
662                    sRandom = new Random();
663                }
664                mChannels = (LinkedList<Integer>)sChannels.clone();
665            }
666            mUuid = uuid;
667        }
668        /* Returns next channel, or -1 if we're out */
669        public int nextChannel() {
670            int channel = mUuid.hashCode();  // always pick the same channel to try first
671            Integer channelInt;
672            while (mChannels.size() > 0) {
673                channelInt = new Integer(channel);
674                if (mChannels.remove(channelInt)) {
675                    return channel;
676                }
677                channel = (channel % BluetoothSocket.MAX_RFCOMM_CHANNEL) + 1;
678            }
679
680            return -1;
681        }
682    }
683
684    /**
685     * Create a listening, secure RFCOMM Bluetooth socket.
686     * <p>A remote device connecting to this socket will be authenticated and
687     * communication on this socket will be encrypted.
688     * <p>Use {@link BluetoothServerSocket#accept} to retrieve incoming
689     * connections from a listening {@link BluetoothServerSocket}.
690     * <p>Valid RFCOMM channels are in range 1 to 30.
691     * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN}
692     * @param channel RFCOMM channel to listen on
693     * @return a listening RFCOMM BluetoothServerSocket
694     * @throws IOException on error, for example Bluetooth not available, or
695     *                     insufficient permissions, or channel in use.
696     * @hide
697     */
698    public BluetoothServerSocket listenUsingRfcommOn(int channel) throws IOException {
699        BluetoothServerSocket socket = new BluetoothServerSocket(
700                BluetoothSocket.TYPE_RFCOMM, true, true, channel);
701        int errno = socket.mSocket.bindListen();
702        if (errno != 0) {
703            try {
704                socket.close();
705            } catch (IOException e) {}
706            socket.mSocket.throwErrnoNative(errno);
707        }
708        return socket;
709    }
710
711    /**
712     * Create a listening, secure RFCOMM Bluetooth socket with Service Record.
713     * <p>A remote device connecting to this socket will be authenticated and
714     * communication on this socket will be encrypted.
715     * <p>Use {@link BluetoothServerSocket#accept} to retrieve incoming
716     * connections from a listening {@link BluetoothServerSocket}.
717     * <p>The system will assign an unused RFCOMM channel to listen on.
718     * <p>The system will also register a Service Discovery
719     * Protocol (SDP) record with the local SDP server containing the specified
720     * UUID, service name, and auto-assigned channel. Remote Bluetooth devices
721     * can use the same UUID to query our SDP server and discover which channel
722     * to connect to. This SDP record will be removed when this socket is
723     * closed, or if this application closes unexpectedly.
724     * <p>Use {@link BluetoothDevice#createRfcommSocketToServiceRecord} to
725     * connect to this socket from another device using the same {@link UUID}.
726     * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
727     * @param name service name for SDP record
728     * @param uuid uuid for SDP record
729     * @return a listening RFCOMM BluetoothServerSocket
730     * @throws IOException on error, for example Bluetooth not available, or
731     *                     insufficient permissions, or channel in use.
732     */
733    public BluetoothServerSocket listenUsingRfcommWithServiceRecord(String name, UUID uuid)
734            throws IOException {
735        RfcommChannelPicker picker = new RfcommChannelPicker(uuid);
736
737        BluetoothServerSocket socket;
738        int channel;
739        int errno;
740        while (true) {
741            channel = picker.nextChannel();
742
743            if (channel == -1) {
744                throw new IOException("No available channels");
745            }
746
747            socket = new BluetoothServerSocket(
748                    BluetoothSocket.TYPE_RFCOMM, true, true, channel);
749            errno = socket.mSocket.bindListen();
750            if (errno == 0) {
751                if (DBG) Log.d(TAG, "listening on RFCOMM channel " + channel);
752                break;  // success
753            } else if (errno == BluetoothSocket.EADDRINUSE) {
754                if (DBG) Log.d(TAG, "RFCOMM channel " + channel + " in use");
755                try {
756                    socket.close();
757                } catch (IOException e) {}
758                continue;  // try another channel
759            } else {
760                try {
761                    socket.close();
762                } catch (IOException e) {}
763                socket.mSocket.throwErrnoNative(errno);  // Exception as a result of bindListen()
764            }
765        }
766
767        int handle = -1;
768        try {
769            handle = mService.addRfcommServiceRecord(name, new ParcelUuid(uuid), channel,
770                    new Binder());
771        } catch (RemoteException e) {Log.e(TAG, "", e);}
772        if (handle == -1) {
773            try {
774                socket.close();
775            } catch (IOException e) {}
776            throw new IOException("Not able to register SDP record for " + name);
777        }
778        socket.setCloseHandler(mHandler, handle);
779        return socket;
780    }
781
782    /**
783     * Construct an unencrypted, unauthenticated, RFCOMM server socket.
784     * Call #accept to retrieve connections to this socket.
785     * @return An RFCOMM BluetoothServerSocket
786     * @throws IOException On error, for example Bluetooth not available, or
787     *                     insufficient permissions.
788     * @hide
789     */
790    public BluetoothServerSocket listenUsingInsecureRfcommOn(int port) throws IOException {
791        BluetoothServerSocket socket = new BluetoothServerSocket(
792                BluetoothSocket.TYPE_RFCOMM, false, false, port);
793        int errno = socket.mSocket.bindListen();
794        if (errno != 0) {
795            try {
796                socket.close();
797            } catch (IOException e) {}
798            socket.mSocket.throwErrnoNative(errno);
799        }
800        return socket;
801    }
802
803    /**
804     * Construct a SCO server socket.
805     * Call #accept to retrieve connections to this socket.
806     * @return A SCO BluetoothServerSocket
807     * @throws IOException On error, for example Bluetooth not available, or
808     *                     insufficient permissions.
809     * @hide
810     */
811    public static BluetoothServerSocket listenUsingScoOn() throws IOException {
812        BluetoothServerSocket socket = new BluetoothServerSocket(
813                BluetoothSocket.TYPE_SCO, false, false, -1);
814        int errno = socket.mSocket.bindListen();
815        if (errno != 0) {
816            try {
817                socket.close();
818            } catch (IOException e) {}
819            socket.mSocket.throwErrnoNative(errno);
820        }
821        return socket;
822    }
823
824    private Set<BluetoothDevice> toDeviceSet(String[] addresses) {
825        Set<BluetoothDevice> devices = new HashSet<BluetoothDevice>(addresses.length);
826        for (int i = 0; i < addresses.length; i++) {
827            devices.add(getRemoteDevice(addresses[i]));
828        }
829        return Collections.unmodifiableSet(devices);
830    }
831
832    private Handler mHandler = new Handler() {
833        public void handleMessage(Message msg) {
834            /* handle socket closing */
835            int handle = msg.what;
836            try {
837                if (DBG) Log.d(TAG, "Removing service record " + Integer.toHexString(handle));
838                mService.removeServiceRecord(handle);
839            } catch (RemoteException e) {Log.e(TAG, "", e);}
840        }
841    };
842
843    /**
844     * Validate a Bluetooth address, such as "00:43:A8:23:10:F0"
845     * <p>Alphabetic characters must be uppercase to be valid.
846     *
847     * @param address Bluetooth address as string
848     * @return true if the address is valid, false otherwise
849     */
850    public static boolean checkBluetoothAddress(String address) {
851        if (address == null || address.length() != ADDRESS_LENGTH) {
852            return false;
853        }
854        for (int i = 0; i < ADDRESS_LENGTH; i++) {
855            char c = address.charAt(i);
856            switch (i % 3) {
857            case 0:
858            case 1:
859                if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F')) {
860                    // hex character, OK
861                    break;
862                }
863                return false;
864            case 2:
865                if (c == ':') {
866                    break;  // OK
867                }
868                return false;
869            }
870        }
871        return true;
872    }
873}
874