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