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