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