BluetoothAdapter.java revision 4b3db907f04d85cd20e0a0e35056ba44a10e8867
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 = false;
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     * <p>Requires {@link android.Manifest.permission#BLUETOOTH}.
573     *
574     * @return true if discovering
575     */
576    public boolean isDiscovering() {
577        try {
578            return mService.isDiscovering();
579        } catch (RemoteException e) {Log.e(TAG, "", e);}
580        return false;
581    }
582
583    /**
584     * Return the set of {@link BluetoothDevice} objects that are bonded
585     * (paired) to the local adapter.
586     * <p>Requires {@link android.Manifest.permission#BLUETOOTH}.
587     *
588     * @return unmodifiable set of {@link BluetoothDevice}, or null on error
589     */
590    public Set<BluetoothDevice> getBondedDevices() {
591        try {
592            return toDeviceSet(mService.listBonds());
593        } catch (RemoteException e) {Log.e(TAG, "", e);}
594        return null;
595    }
596
597    /**
598     * Picks RFCOMM channels until none are left.
599     * Avoids reserved channels.
600     */
601    private static class RfcommChannelPicker {
602        private static final int[] RESERVED_RFCOMM_CHANNELS =  new int[] {
603            10,  // HFAG
604            11,  // HSAG
605            12,  // OPUSH
606            19,  // PBAP
607        };
608        private static LinkedList<Integer> sChannels;  // master list of non-reserved channels
609        private static Random sRandom;
610
611        private final LinkedList<Integer> mChannels;  // local list of channels left to try
612
613        private final UUID mUuid;
614
615        public RfcommChannelPicker(UUID uuid) {
616            synchronized (RfcommChannelPicker.class) {
617                if (sChannels == null) {
618                    // lazy initialization of non-reserved rfcomm channels
619                    sChannels = new LinkedList<Integer>();
620                    for (int i = 1; i <= BluetoothSocket.MAX_RFCOMM_CHANNEL; i++) {
621                        sChannels.addLast(new Integer(i));
622                    }
623                    for (int reserved : RESERVED_RFCOMM_CHANNELS) {
624                        sChannels.remove(new Integer(reserved));
625                    }
626                    sRandom = new Random();
627                }
628                mChannels = (LinkedList<Integer>)sChannels.clone();
629            }
630            mUuid = uuid;
631        }
632        /* Returns next random channel, or -1 if we're out */
633        public int nextChannel() {
634            if (mChannels.size() == 0) {
635                return -1;
636            }
637            return mChannels.remove(sRandom.nextInt(mChannels.size()));
638        }
639    }
640
641    /**
642     * Create a listening, secure RFCOMM Bluetooth socket.
643     * <p>A remote device connecting to this socket will be authenticated and
644     * communication on this socket will be encrypted.
645     * <p>Use {@link BluetoothServerSocket#accept} to retrieve incoming
646     * connections from a listening {@link BluetoothServerSocket}.
647     * <p>Valid RFCOMM channels are in range 1 to 30.
648     * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN}
649     * @param channel RFCOMM channel to listen on
650     * @return a listening RFCOMM BluetoothServerSocket
651     * @throws IOException on error, for example Bluetooth not available, or
652     *                     insufficient permissions, or channel in use.
653     * @hide
654     */
655    public BluetoothServerSocket listenUsingRfcommOn(int channel) throws IOException {
656        BluetoothServerSocket socket = new BluetoothServerSocket(
657                BluetoothSocket.TYPE_RFCOMM, true, true, channel);
658        int errno = socket.mSocket.bindListen();
659        if (errno != 0) {
660            try {
661                socket.close();
662            } catch (IOException e) {}
663            socket.mSocket.throwErrnoNative(errno);
664        }
665        return socket;
666    }
667
668    /**
669     * Create a listening, secure RFCOMM Bluetooth socket with Service Record.
670     * <p>A remote device connecting to this socket will be authenticated and
671     * communication on this socket will be encrypted.
672     * <p>Use {@link BluetoothServerSocket#accept} to retrieve incoming
673     * connections from a listening {@link BluetoothServerSocket}.
674     * <p>The system will assign an unused RFCOMM channel to listen on.
675     * <p>The system will also register a Service Discovery
676     * Protocol (SDP) record with the local SDP server containing the specified
677     * UUID, service name, and auto-assigned channel. Remote Bluetooth devices
678     * can use the same UUID to query our SDP server and discover which channel
679     * to connect to. This SDP record will be removed when this socket is
680     * closed, or if this application closes unexpectedly.
681     * <p>Use {@link BluetoothDevice#createRfcommSocketToServiceRecord} to
682     * connect to this socket from another device using the same {@link UUID}.
683     * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
684     * @param name service name for SDP record
685     * @param uuid uuid for SDP record
686     * @return a listening RFCOMM BluetoothServerSocket
687     * @throws IOException on error, for example Bluetooth not available, or
688     *                     insufficient permissions, or channel in use.
689     */
690    public BluetoothServerSocket listenUsingRfcommWithServiceRecord(String name, UUID uuid)
691            throws IOException {
692        RfcommChannelPicker picker = new RfcommChannelPicker(uuid);
693
694        BluetoothServerSocket socket;
695        int channel;
696        int errno;
697        while (true) {
698            channel = picker.nextChannel();
699
700            if (channel == -1) {
701                throw new IOException("No available channels");
702            }
703
704            socket = new BluetoothServerSocket(
705                    BluetoothSocket.TYPE_RFCOMM, true, true, channel);
706            errno = socket.mSocket.bindListen();
707            if (errno == 0) {
708                if (DBG) Log.d(TAG, "listening on RFCOMM channel " + channel);
709                break;  // success
710            } else if (errno == BluetoothSocket.EADDRINUSE) {
711                if (DBG) Log.d(TAG, "RFCOMM channel " + channel + " in use");
712                try {
713                    socket.close();
714                } catch (IOException e) {}
715                continue;  // try another channel
716            } else {
717                try {
718                    socket.close();
719                } catch (IOException e) {}
720                socket.mSocket.throwErrnoNative(errno);  // Exception as a result of bindListen()
721            }
722        }
723
724        int handle = -1;
725        try {
726            handle = mService.addRfcommServiceRecord(name, new ParcelUuid(uuid), channel,
727                    new Binder());
728        } catch (RemoteException e) {Log.e(TAG, "", e);}
729        if (handle == -1) {
730            try {
731                socket.close();
732            } catch (IOException e) {}
733            throw new IOException("Not able to register SDP record for " + name);
734        }
735        socket.setCloseHandler(mHandler, handle);
736        return socket;
737    }
738
739    /**
740     * Construct an unencrypted, unauthenticated, RFCOMM server socket.
741     * Call #accept to retrieve connections to this socket.
742     * @return An RFCOMM BluetoothServerSocket
743     * @throws IOException On error, for example Bluetooth not available, or
744     *                     insufficient permissions.
745     * @hide
746     */
747    public BluetoothServerSocket listenUsingInsecureRfcommOn(int port) throws IOException {
748        BluetoothServerSocket socket = new BluetoothServerSocket(
749                BluetoothSocket.TYPE_RFCOMM, false, false, port);
750        int errno = socket.mSocket.bindListen();
751        if (errno != 0) {
752            try {
753                socket.close();
754            } catch (IOException e) {}
755            socket.mSocket.throwErrnoNative(errno);
756        }
757        return socket;
758    }
759
760    /**
761     * Construct a SCO server socket.
762     * Call #accept to retrieve connections to this socket.
763     * @return A SCO BluetoothServerSocket
764     * @throws IOException On error, for example Bluetooth not available, or
765     *                     insufficient permissions.
766     * @hide
767     */
768    public static BluetoothServerSocket listenUsingScoOn() throws IOException {
769        BluetoothServerSocket socket = new BluetoothServerSocket(
770                BluetoothSocket.TYPE_SCO, false, false, -1);
771        int errno = socket.mSocket.bindListen();
772        if (errno != 0) {
773            try {
774                socket.close();
775            } catch (IOException e) {}
776            socket.mSocket.throwErrnoNative(errno);
777        }
778        return socket;
779    }
780
781    private Set<BluetoothDevice> toDeviceSet(String[] addresses) {
782        Set<BluetoothDevice> devices = new HashSet<BluetoothDevice>(addresses.length);
783        for (int i = 0; i < addresses.length; i++) {
784            devices.add(getRemoteDevice(addresses[i]));
785        }
786        return Collections.unmodifiableSet(devices);
787    }
788
789    private Handler mHandler = new Handler() {
790        public void handleMessage(Message msg) {
791            /* handle socket closing */
792            int handle = msg.what;
793            try {
794                if (DBG) Log.d(TAG, "Removing service record " + Integer.toHexString(handle));
795                mService.removeServiceRecord(handle);
796            } catch (RemoteException e) {Log.e(TAG, "", e);}
797        }
798    };
799
800    /**
801     * Validate a Bluetooth address, such as "00:43:A8:23:10:F0"
802     * <p>Alphabetic characters must be uppercase to be valid.
803     *
804     * @param address Bluetooth address as string
805     * @return true if the address is valid, false otherwise
806     */
807    public static boolean checkBluetoothAddress(String address) {
808        if (address == null || address.length() != ADDRESS_LENGTH) {
809            return false;
810        }
811        for (int i = 0; i < ADDRESS_LENGTH; i++) {
812            char c = address.charAt(i);
813            switch (i % 3) {
814            case 0:
815            case 1:
816                if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F')) {
817                    // hex character, OK
818                    break;
819                }
820                return false;
821            case 2:
822                if (c == ':') {
823                    break;  // OK
824                }
825                return false;
826            }
827        }
828        return true;
829    }
830}
831