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