BluetoothDevice.java revision ae5839dcad76625313e6736d69eeaf37af435a3f
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.IBinder;
22import android.os.Parcel;
23import android.os.Parcelable;
24import android.os.ParcelUuid;
25import android.os.RemoteException;
26import android.os.ServiceManager;
27import android.util.Log;
28
29import java.io.IOException;
30import java.io.UnsupportedEncodingException;
31import java.util.UUID;
32
33/**
34 * Represents a remote Bluetooth device. A {@link BluetoothDevice} lets you
35 * create a connection with the respective device or query information about
36 * it, such as the name, address, class, and bonding state.
37 *
38 * <p>This class is really just a thin wrapper for a Bluetooth hardware
39 * address. Objects of this class are immutable. Operations on this class
40 * are performed on the remote Bluetooth hardware address, using the
41 * {@link BluetoothAdapter} that was used to create this {@link
42 * BluetoothDevice}.
43 *
44 * <p>To get a {@link BluetoothDevice}, use
45 * {@link BluetoothAdapter#getRemoteDevice(String)
46 * BluetoothAdapter.getRemoteDevice(String)} to create one representing a device
47 * of a known MAC address (which you can get through device discovery with
48 * {@link BluetoothAdapter}) or get one from the set of bonded devices
49 * returned by {@link BluetoothAdapter#getBondedDevices()
50 * BluetoothAdapter.getBondedDevices()}. You can then open a
51 * {@link BluetoothSocket} for communication with the remote device, using
52 * {@link #createRfcommSocketToServiceRecord(UUID)}.
53 *
54 * <p class="note"><strong>Note:</strong>
55 * Requires the {@link android.Manifest.permission#BLUETOOTH} permission.
56 *
57 * {@see BluetoothAdapter}
58 * {@see BluetoothSocket}
59 */
60public final class BluetoothDevice implements Parcelable {
61    private static final String TAG = "BluetoothDevice";
62
63    /**
64     * Sentinel error value for this class. Guaranteed to not equal any other
65     * integer constant in this class. Provided as a convenience for functions
66     * that require a sentinel error value, for example:
67     * <p><code>Intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE,
68     * BluetoothDevice.ERROR)</code>
69     */
70    public static final int ERROR = Integer.MIN_VALUE;
71
72    /**
73     * Broadcast Action: Remote device discovered.
74     * <p>Sent when a remote device is found during discovery.
75     * <p>Always contains the extra fields {@link #EXTRA_DEVICE} and {@link
76     * #EXTRA_CLASS}. Can contain the extra fields {@link #EXTRA_NAME} and/or
77     * {@link #EXTRA_RSSI} if they are available.
78     * <p>Requires {@link android.Manifest.permission#BLUETOOTH} to receive.
79     */
80     // TODO: Change API to not broadcast RSSI if not available (incoming connection)
81    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
82    public static final String ACTION_FOUND =
83            "android.bluetooth.device.action.FOUND";
84
85    /**
86     * Broadcast Action: Remote device disappeared.
87     * <p>Sent when a remote device that was found in the last discovery is not
88     * found in the current discovery.
89     * <p>Always contains the extra field {@link #EXTRA_DEVICE}.
90     * <p>Requires {@link android.Manifest.permission#BLUETOOTH} to receive.
91     * @hide
92     */
93    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
94    public static final String ACTION_DISAPPEARED =
95            "android.bluetooth.device.action.DISAPPEARED";
96
97    /**
98     * Broadcast Action: Bluetooth class of a remote device has changed.
99     * <p>Always contains the extra fields {@link #EXTRA_DEVICE} and {@link
100     * #EXTRA_CLASS}.
101     * <p>Requires {@link android.Manifest.permission#BLUETOOTH} to receive.
102     * @see {@link BluetoothClass}
103     */
104    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
105    public static final String ACTION_CLASS_CHANGED =
106            "android.bluetooth.device.action.CLASS_CHANGED";
107
108    /**
109     * Broadcast Action: Indicates a low level (ACL) connection has been
110     * established with a remote device.
111     * <p>Always contains the extra field {@link #EXTRA_DEVICE}.
112     * <p>ACL connections are managed automatically by the Android Bluetooth
113     * stack.
114     * <p>Requires {@link android.Manifest.permission#BLUETOOTH} to receive.
115     */
116    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
117    public static final String ACTION_ACL_CONNECTED =
118            "android.bluetooth.device.action.ACL_CONNECTED";
119
120    /**
121     * Broadcast Action: Indicates that a low level (ACL) disconnection has
122     * been requested for a remote device, and it will soon be disconnected.
123     * <p>This is useful for graceful disconnection. Applications should use
124     * this intent as a hint to immediately terminate higher level connections
125     * (RFCOMM, L2CAP, or profile connections) to the remote device.
126     * <p>Always contains the extra field {@link #EXTRA_DEVICE}.
127     * <p>Requires {@link android.Manifest.permission#BLUETOOTH} to receive.
128     */
129    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
130    public static final String ACTION_ACL_DISCONNECT_REQUESTED =
131            "android.bluetooth.device.action.ACL_DISCONNECT_REQUESTED";
132
133    /**
134     * Broadcast Action: Indicates a low level (ACL) disconnection from a
135     * remote device.
136     * <p>Always contains the extra field {@link #EXTRA_DEVICE}.
137     * <p>ACL connections are managed automatically by the Android Bluetooth
138     * stack.
139     * <p>Requires {@link android.Manifest.permission#BLUETOOTH} to receive.
140     */
141    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
142    public static final String ACTION_ACL_DISCONNECTED =
143            "android.bluetooth.device.action.ACL_DISCONNECTED";
144
145    /**
146     * Broadcast Action: Indicates the friendly name of a remote device has
147     * been retrieved for the first time, or changed since the last retrieval.
148     * <p>Always contains the extra fields {@link #EXTRA_DEVICE} and {@link
149     * #EXTRA_NAME}.
150     * <p>Requires {@link android.Manifest.permission#BLUETOOTH} to receive.
151     */
152    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
153    public static final String ACTION_NAME_CHANGED =
154            "android.bluetooth.device.action.NAME_CHANGED";
155
156    /**
157     * Broadcast Action: Indicates a change in the bond state of a remote
158     * device. For example, if a device is bonded (paired).
159     * <p>Always contains the extra fields {@link #EXTRA_DEVICE}, {@link
160     * #EXTRA_BOND_STATE} and {@link #EXTRA_PREVIOUS_BOND_STATE}.
161     * <p>Requires {@link android.Manifest.permission#BLUETOOTH} to receive.
162     */
163    // Note: When EXTRA_BOND_STATE is BOND_NONE then this will also
164    // contain a hidden extra field EXTRA_REASON with the result code.
165    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
166    public static final String ACTION_BOND_STATE_CHANGED =
167            "android.bluetooth.device.action.BOND_STATE_CHANGED";
168
169    /**
170     * Used as a Parcelable {@link BluetoothDevice} extra field in every intent
171     * broadcast by this class. It contains the {@link BluetoothDevice} that
172     * the intent applies to.
173     */
174    public static final String EXTRA_DEVICE = "android.bluetooth.device.extra.DEVICE";
175
176    /**
177     * Used as a String extra field in {@link #ACTION_NAME_CHANGED} and {@link
178     * #ACTION_FOUND} intents. It contains the friendly Bluetooth name.
179     */
180    public static final String EXTRA_NAME = "android.bluetooth.device.extra.NAME";
181
182    /**
183     * Used as an optional short extra field in {@link #ACTION_FOUND} intents.
184     * Contains the RSSI value of the remote device as reported by the
185     * Bluetooth hardware.
186     */
187    public static final String EXTRA_RSSI = "android.bluetooth.device.extra.RSSI";
188
189    /**
190     * Used as an Parcelable {@link BluetoothClass} extra field in {@link
191     * #ACTION_FOUND} and {@link #ACTION_CLASS_CHANGED} intents.
192     */
193    public static final String EXTRA_CLASS = "android.bluetooth.device.extra.CLASS";
194
195    /**
196     * Used as an int extra field in {@link #ACTION_BOND_STATE_CHANGED} intents.
197     * Contains the bond state of the remote device.
198     * <p>Possible values are:
199     * {@link #BOND_NONE},
200     * {@link #BOND_BONDING},
201     * {@link #BOND_BONDED}.
202      */
203    public static final String EXTRA_BOND_STATE = "android.bluetooth.device.extra.BOND_STATE";
204    /**
205     * Used as an int extra field in {@link #ACTION_BOND_STATE_CHANGED} intents.
206     * Contains the previous bond state of the remote device.
207     * <p>Possible values are:
208     * {@link #BOND_NONE},
209     * {@link #BOND_BONDING},
210     * {@link #BOND_BONDED}.
211      */
212    public static final String EXTRA_PREVIOUS_BOND_STATE =
213            "android.bluetooth.device.extra.PREVIOUS_BOND_STATE";
214    /**
215     * Indicates the remote device is not bonded (paired).
216     * <p>There is no shared link key with the remote device, so communication
217     * (if it is allowed at all) will be unauthenticated and unencrypted.
218     */
219    public static final int BOND_NONE = 10;
220    /**
221     * Indicates bonding (pairing) is in progress with the remote device.
222     */
223    public static final int BOND_BONDING = 11;
224    /**
225     * Indicates the remote device is bonded (paired).
226     * <p>A shared link keys exists locally for the remote device, so
227     * communication can be authenticated and encrypted.
228     * <p><i>Being bonded (paired) with a remote device does not necessarily
229     * mean the device is currently connected. It just means that the pending
230     * procedure was completed at some earlier time, and the link key is still
231     * stored locally, ready to use on the next connection.
232     * </i>
233     */
234    public static final int BOND_BONDED = 12;
235
236    /** @hide */
237    public static final String EXTRA_REASON = "android.bluetooth.device.extra.REASON";
238    /** @hide */
239    public static final String EXTRA_PAIRING_VARIANT =
240            "android.bluetooth.device.extra.PAIRING_VARIANT";
241    /** @hide */
242    public static final String EXTRA_PAIRING_KEY = "android.bluetooth.device.extra.PAIRING_KEY";
243
244    /**
245     * Broadcast Action: This intent is used to broadcast the {@link UUID}
246     * wrapped as a {@link android.os.ParcelUuid} of the remote device after it
247     * has been fetched. This intent is sent only when the UUIDs of the remote
248     * device are requested to be fetched using Service Discovery Protocol
249     * <p> Always contains the extra field {@link #EXTRA_DEVICE}
250     * <p> Always contains the extra filed {@link #EXTRA_UUID}
251     * <p>Requires {@link android.Manifest.permission#BLUETOOTH} to receive.
252     */
253    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
254    public static final String ACTION_UUID =
255            "android.bluetooth.device.action.UUID";
256
257    /**
258     * Broadcast Action: Indicates a failure to retrieve the name of a remote
259     * device.
260     * <p>Always contains the extra field {@link #EXTRA_DEVICE}.
261     * <p>Requires {@link android.Manifest.permission#BLUETOOTH} to receive.
262     * @hide
263     */
264    //TODO: is this actually useful?
265    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
266    public static final String ACTION_NAME_FAILED =
267            "android.bluetooth.device.action.NAME_FAILED";
268
269    /** @hide */
270    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
271    public static final String ACTION_PAIRING_REQUEST =
272            "android.bluetooth.device.action.PAIRING_REQUEST";
273    /** @hide */
274    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
275    public static final String ACTION_PAIRING_CANCEL =
276            "android.bluetooth.device.action.PAIRING_CANCEL";
277
278    /** @hide */
279    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
280    public static final String ACTION_CONNECTION_ACCESS_REQUEST =
281            "android.bluetooth.device.action.CONNECTION_ACCESS_REQUEST";
282
283    /** @hide */
284    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
285    public static final String ACTION_CONNECTION_ACCESS_REPLY =
286            "android.bluetooth.device.action.CONNECTION_ACCESS_REPLY";
287
288    /** @hide */
289    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
290    public static final String ACTION_CONNECTION_ACCESS_CANCEL =
291            "android.bluetooth.device.action.CONNECTION_ACCESS_CANCEL";
292
293    /**
294     * Used as an extra field in {@link #ACTION_CONNECTION_ACCESS_REQUEST} intent.
295     * @hide
296     */
297    public static final String EXTRA_ACCESS_REQUEST_TYPE =
298        "android.bluetooth.device.extra.ACCESS_REQUEST_TYPE";
299
300    /**@hide*/
301    public static final int REQUEST_TYPE_PROFILE_CONNECTION = 1;
302
303    /**@hide*/
304    public static final int REQUEST_TYPE_PHONEBOOK_ACCESS = 2;
305
306    /**
307     * Used as an extra field in {@link #ACTION_CONNECTION_ACCESS_REQUEST} intents,
308     * Contains package name to return reply intent to.
309     * @hide
310     */
311    public static final String EXTRA_PACKAGE_NAME = "android.bluetooth.device.extra.PACKAGE_NAME";
312
313    /**
314     * Used as an extra field in {@link #ACTION_CONNECTION_ACCESS_REQUEST} intents,
315     * Contains class name to return reply intent to.
316     * @hide
317     */
318    public static final String EXTRA_CLASS_NAME = "android.bluetooth.device.extra.CLASS_NAME";
319
320    /**
321     * Used as an extra field in {@link #ACTION_CONNECTION_ACCESS_REPLY} intent.
322     * @hide
323     */
324    public static final String EXTRA_CONNECTION_ACCESS_RESULT =
325        "android.bluetooth.device.extra.CONNECTION_ACCESS_RESULT";
326
327    /**@hide*/
328    public static final int CONNECTION_ACCESS_YES = 1;
329
330    /**@hide*/
331    public static final int CONNECTION_ACCESS_NO = 2;
332
333    /**
334     * Used as an extra field in {@link #ACTION_CONNECTION_ACCESS_REPLY} intents,
335     * Contains boolean to indicate if the allowed response is once-for-all so that
336     * next request will be granted without asking user again.
337     * @hide
338     */
339    public static final String EXTRA_ALWAYS_ALLOWED =
340        "android.bluetooth.device.extra.ALWAYS_ALLOWED";
341
342    /**
343     * A bond attempt succeeded
344     * @hide
345     */
346    public static final int BOND_SUCCESS = 0;
347
348    /**
349     * A bond attempt failed because pins did not match, or remote device did
350     * not respond to pin request in time
351     * @hide
352     */
353    public static final int UNBOND_REASON_AUTH_FAILED = 1;
354
355    /**
356     * A bond attempt failed because the other side explicitly rejected
357     * bonding
358     * @hide
359     */
360    public static final int UNBOND_REASON_AUTH_REJECTED = 2;
361
362    /**
363     * A bond attempt failed because we canceled the bonding process
364     * @hide
365     */
366    public static final int UNBOND_REASON_AUTH_CANCELED = 3;
367
368    /**
369     * A bond attempt failed because we could not contact the remote device
370     * @hide
371     */
372    public static final int UNBOND_REASON_REMOTE_DEVICE_DOWN = 4;
373
374    /**
375     * A bond attempt failed because a discovery is in progress
376     * @hide
377     */
378    public static final int UNBOND_REASON_DISCOVERY_IN_PROGRESS = 5;
379
380    /**
381     * A bond attempt failed because of authentication timeout
382     * @hide
383     */
384    public static final int UNBOND_REASON_AUTH_TIMEOUT = 6;
385
386    /**
387     * A bond attempt failed because of repeated attempts
388     * @hide
389     */
390    public static final int UNBOND_REASON_REPEATED_ATTEMPTS = 7;
391
392    /**
393     * A bond attempt failed because we received an Authentication Cancel
394     * by remote end
395     * @hide
396     */
397    public static final int UNBOND_REASON_REMOTE_AUTH_CANCELED = 8;
398
399    /**
400     * An existing bond was explicitly revoked
401     * @hide
402     */
403    public static final int UNBOND_REASON_REMOVED = 9;
404
405    /**
406     * The user will be prompted to enter a pin
407     * @hide
408     */
409    public static final int PAIRING_VARIANT_PIN = 0;
410
411    /**
412     * The user will be prompted to enter a passkey
413     * @hide
414     */
415    public static final int PAIRING_VARIANT_PASSKEY = 1;
416
417    /**
418     * The user will be prompted to confirm the passkey displayed on the screen
419     * @hide
420     */
421    public static final int PAIRING_VARIANT_PASSKEY_CONFIRMATION = 2;
422
423    /**
424     * The user will be prompted to accept or deny the incoming pairing request
425     * @hide
426     */
427    public static final int PAIRING_VARIANT_CONSENT = 3;
428
429    /**
430     * The user will be prompted to enter the passkey displayed on remote device
431     * This is used for Bluetooth 2.1 pairing.
432     * @hide
433     */
434    public static final int PAIRING_VARIANT_DISPLAY_PASSKEY = 4;
435
436    /**
437     * The user will be prompted to enter the PIN displayed on remote device.
438     * This is used for Bluetooth 2.0 pairing.
439     * @hide
440     */
441    public static final int PAIRING_VARIANT_DISPLAY_PIN = 5;
442
443    /**
444     * The user will be prompted to accept or deny the OOB pairing request
445     * @hide
446     */
447    public static final int PAIRING_VARIANT_OOB_CONSENT = 6;
448
449    /**
450     * Used as an extra field in {@link #ACTION_UUID} intents,
451     * Contains the {@link android.os.ParcelUuid}s of the remote device which
452     * is a parcelable version of {@link UUID}.
453     * @hide
454     */
455    public static final String EXTRA_UUID = "android.bluetooth.device.extra.UUID";
456
457    /**
458     * Lazy initialization. Guaranteed final after first object constructed, or
459     * getService() called.
460     * TODO: Unify implementation of sService amongst BluetoothFoo API's
461     */
462    private static IBluetooth sService;
463
464    private final String mAddress;
465
466    /*package*/ static IBluetooth getService() {
467        synchronized (BluetoothDevice.class) {
468            if (sService == null) {
469                IBinder b = ServiceManager.getService(BluetoothAdapter.BLUETOOTH_SERVICE);
470                if (b == null) {
471                    throw new RuntimeException("Bluetooth service not available");
472                }
473                sService = IBluetooth.Stub.asInterface(b);
474            }
475        }
476        return sService;
477    }
478
479    /**
480     * Create a new BluetoothDevice
481     * Bluetooth MAC address must be upper case, such as "00:11:22:33:AA:BB",
482     * and is validated in this constructor.
483     * @param address valid Bluetooth MAC address
484     * @throws RuntimeException Bluetooth is not available on this platform
485     * @throws IllegalArgumentException address is invalid
486     * @hide
487     */
488    /*package*/ BluetoothDevice(String address) {
489        getService();  // ensures sService is initialized
490        if (!BluetoothAdapter.checkBluetoothAddress(address)) {
491            throw new IllegalArgumentException(address + " is not a valid Bluetooth address");
492        }
493
494        mAddress = address;
495    }
496
497    @Override
498    public boolean equals(Object o) {
499        if (o instanceof BluetoothDevice) {
500            return mAddress.equals(((BluetoothDevice)o).getAddress());
501        }
502        return false;
503    }
504
505    @Override
506    public int hashCode() {
507        return mAddress.hashCode();
508    }
509
510    /**
511     * Returns a string representation of this BluetoothDevice.
512     * <p>Currently this is the Bluetooth hardware address, for example
513     * "00:11:22:AA:BB:CC". However, you should always use {@link #getAddress}
514     * if you explicitly require the Bluetooth hardware address in case the
515     * {@link #toString} representation changes in the future.
516     * @return string representation of this BluetoothDevice
517     */
518    @Override
519    public String toString() {
520        return mAddress;
521    }
522
523    public int describeContents() {
524        return 0;
525    }
526
527    public static final Parcelable.Creator<BluetoothDevice> CREATOR =
528            new Parcelable.Creator<BluetoothDevice>() {
529        public BluetoothDevice createFromParcel(Parcel in) {
530            return new BluetoothDevice(in.readString());
531        }
532        public BluetoothDevice[] newArray(int size) {
533            return new BluetoothDevice[size];
534        }
535    };
536
537    public void writeToParcel(Parcel out, int flags) {
538        out.writeString(mAddress);
539    }
540
541    /**
542     * Returns the hardware address of this BluetoothDevice.
543     * <p> For example, "00:11:22:AA:BB:CC".
544     * @return Bluetooth hardware address as string
545     */
546    public String getAddress() {
547        return mAddress;
548    }
549
550    /**
551     * Get the friendly Bluetooth name of the remote device.
552     *
553     * <p>The local adapter will automatically retrieve remote names when
554     * performing a device scan, and will cache them. This method just returns
555     * the name for this device from the cache.
556     * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
557     *
558     * @return the Bluetooth name, or null if there was a problem.
559     */
560    public String getName() {
561        try {
562            return sService.getRemoteName(mAddress);
563        } catch (RemoteException e) {Log.e(TAG, "", e);}
564        return null;
565    }
566
567    /**
568     * Get the Bluetooth alias of the remote device.
569     * <p>Alias is the locally modified name of a remote device.
570     *
571     * @return the Bluetooth alias, or null if no alias or there was a problem
572     * @hide
573     */
574    public String getAlias() {
575        try {
576            return sService.getRemoteAlias(mAddress);
577        } catch (RemoteException e) {Log.e(TAG, "", e);}
578        return null;
579    }
580
581    /**
582     * Set the Bluetooth alias of the remote device.
583     * <p>Alias is the locally modified name of a remote device.
584     * <p>This methoid overwrites the alias. The changed
585     * alias is saved in the local storage so that the change
586     * is preserved over power cycle.
587     *
588     * @return true on success, false on error
589     * @hide
590     */
591    public boolean setAlias(String alias) {
592        try {
593            return sService.setRemoteAlias(mAddress, alias);
594        } catch (RemoteException e) {Log.e(TAG, "", e);}
595        return false;
596    }
597
598    /**
599     * Get the Bluetooth alias of the remote device.
600     * If Alias is null, get the Bluetooth name instead.
601     * @see #getAlias()
602     * @see #getName()
603     *
604     * @return the Bluetooth alias, or null if no alias or there was a problem
605     * @hide
606     */
607    public String getAliasName() {
608        String name = getAlias();
609        if (name == null) {
610            name = getName();
611        }
612        return name;
613    }
614
615    /**
616     * Start the bonding (pairing) process with the remote device.
617     * <p>This is an asynchronous call, it will return immediately. Register
618     * for {@link #ACTION_BOND_STATE_CHANGED} intents to be notified when
619     * the bonding process completes, and its result.
620     * <p>Android system services will handle the necessary user interactions
621     * to confirm and complete the bonding process.
622     * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN}.
623     *
624     * @return false on immediate error, true if bonding will begin
625     * @hide
626     */
627    public boolean createBond() {
628        try {
629            return sService.createBond(mAddress);
630        } catch (RemoteException e) {Log.e(TAG, "", e);}
631        return false;
632    }
633
634    /**
635     * Start the bonding (pairing) process with the remote device using the
636     * Out Of Band mechanism.
637     *
638     * <p>This is an asynchronous call, it will return immediately. Register
639     * for {@link #ACTION_BOND_STATE_CHANGED} intents to be notified when
640     * the bonding process completes, and its result.
641     *
642     * <p>Android system services will handle the necessary user interactions
643     * to confirm and complete the bonding process.
644     *
645     * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN}.
646     *
647     * @param hash - Simple Secure pairing hash
648     * @param randomizer - The random key obtained using OOB
649     * @return false on immediate error, true if bonding will begin
650     *
651     * @hide
652     */
653    public boolean createBondOutOfBand(byte[] hash, byte[] randomizer) {
654        try {
655            return sService.createBondOutOfBand(mAddress, hash, randomizer);
656        } catch (RemoteException e) {Log.e(TAG, "", e);}
657        return false;
658    }
659
660    /**
661     * Set the Out Of Band data for a remote device to be used later
662     * in the pairing mechanism. Users can obtain this data through other
663     * trusted channels
664     *
665     * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN}.
666     *
667     * @param hash Simple Secure pairing hash
668     * @param randomizer The random key obtained using OOB
669     * @return false on error; true otherwise
670     *
671     * @hide
672     */
673    public boolean setDeviceOutOfBandData(byte[] hash, byte[] randomizer) {
674      try {
675        return sService.setDeviceOutOfBandData(mAddress, hash, randomizer);
676      } catch (RemoteException e) {Log.e(TAG, "", e);}
677      return false;
678    }
679
680    /**
681     * Cancel an in-progress bonding request started with {@link #createBond}.
682     * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN}.
683     *
684     * @return true on success, false on error
685     * @hide
686     */
687    public boolean cancelBondProcess() {
688        try {
689            return sService.cancelBondProcess(mAddress);
690        } catch (RemoteException e) {Log.e(TAG, "", e);}
691        return false;
692    }
693
694    /**
695     * Remove bond (pairing) with the remote device.
696     * <p>Delete the link key associated with the remote device, and
697     * immediately terminate connections to that device that require
698     * authentication and encryption.
699     * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN}.
700     *
701     * @return true on success, false on error
702     * @hide
703     */
704    public boolean removeBond() {
705        try {
706            return sService.removeBond(mAddress);
707        } catch (RemoteException e) {Log.e(TAG, "", e);}
708        return false;
709    }
710
711    /**
712     * Get the bond state of the remote device.
713     * <p>Possible values for the bond state are:
714     * {@link #BOND_NONE},
715     * {@link #BOND_BONDING},
716     * {@link #BOND_BONDED}.
717     * <p>Requires {@link android.Manifest.permission#BLUETOOTH}.
718     *
719     * @return the bond state
720     */
721    public int getBondState() {
722        try {
723            return sService.getBondState(mAddress);
724        } catch (RemoteException e) {Log.e(TAG, "", e);}
725        return BOND_NONE;
726    }
727
728    /**
729     * Get the Bluetooth class of the remote device.
730     * <p>Requires {@link android.Manifest.permission#BLUETOOTH}.
731     *
732     * @return Bluetooth class object, or null on error
733     */
734    public BluetoothClass getBluetoothClass() {
735        try {
736            int classInt = sService.getRemoteClass(mAddress);
737            if (classInt == BluetoothClass.ERROR) return null;
738            return new BluetoothClass(classInt);
739        } catch (RemoteException e) {Log.e(TAG, "", e);}
740        return null;
741    }
742
743    /**
744     * Get trust state of a remote device.
745     * <p>Requires {@link android.Manifest.permission#BLUETOOTH}.
746     * @hide
747     */
748    public boolean getTrustState() {
749        try {
750            return sService.getTrustState(mAddress);
751        } catch (RemoteException e) {
752            Log.e(TAG, "", e);
753        }
754        return false;
755    }
756
757    /**
758     * Set trust state for a remote device.
759     * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN}.
760     * @param value the trust state value (true or false)
761     * @hide
762     */
763    public boolean setTrust(boolean value) {
764        try {
765            return sService.setTrust(mAddress, value);
766        } catch (RemoteException e) {
767            Log.e(TAG, "", e);
768        }
769        return false;
770    }
771
772    /**
773     * Returns the supported features (UUIDs) of the remote device.
774     *
775     * <p>This method does not start a service discovery procedure to retrieve the UUIDs
776     * from the remote device. Instead, the local cached copy of the service
777     * UUIDs are returned.
778     * <p>Use {@link #fetchUuidsWithSdp} if fresh UUIDs are desired.
779     * <p>Requires {@link android.Manifest.permission#BLUETOOTH}.
780     *
781     * @return the supported features (UUIDs) of the remote device,
782     *         or null on error
783     */
784     public ParcelUuid[] getUuids() {
785        try {
786            return sService.getRemoteUuids(mAddress);
787        } catch (RemoteException e) {Log.e(TAG, "", e);}
788        return null;
789    }
790
791     /**
792      * Perform a service discovery on the remote device to get the UUIDs supported.
793      *
794      * <p>This API is asynchronous and {@link #ACTION_UUID} intent is sent,
795      * with the UUIDs supported by the remote end. If there is an error
796      * in getting the SDP records or if the process takes a long time,
797      * {@link #ACTION_UUID} intent is sent with the UUIDs that is currently
798      * present in the cache. Clients should use the {@link #getUuids} to get UUIDs
799      * if service discovery is not to be performed.
800      * <p>Requires {@link android.Manifest.permission#BLUETOOTH}.
801      *
802      * @return False if the sanity check fails, True if the process
803      *               of initiating an ACL connection to the remote device
804      *               was started.
805      */
806     public boolean fetchUuidsWithSdp() {
807        try {
808            return sService.fetchRemoteUuids(mAddress, null, null);
809        } catch (RemoteException e) {Log.e(TAG, "", e);}
810        return false;
811    }
812
813    /** @hide */
814    public int getServiceChannel(ParcelUuid uuid) {
815         try {
816             return sService.getRemoteServiceChannel(mAddress, uuid);
817         } catch (RemoteException e) {Log.e(TAG, "", e);}
818         return BluetoothDevice.ERROR;
819    }
820
821    /** @hide */
822    public boolean setPin(byte[] pin) {
823        try {
824            return sService.setPin(mAddress, pin);
825        } catch (RemoteException e) {Log.e(TAG, "", e);}
826        return false;
827    }
828
829    /** @hide */
830    public boolean setPasskey(int passkey) {
831        try {
832            return sService.setPasskey(mAddress, passkey);
833        } catch (RemoteException e) {Log.e(TAG, "", e);}
834        return false;
835    }
836
837    /** @hide */
838    public boolean setPairingConfirmation(boolean confirm) {
839        try {
840            return sService.setPairingConfirmation(mAddress, confirm);
841        } catch (RemoteException e) {Log.e(TAG, "", e);}
842        return false;
843    }
844
845    /** @hide */
846    public boolean setRemoteOutOfBandData() {
847        try {
848          return sService.setRemoteOutOfBandData(mAddress);
849      } catch (RemoteException e) {Log.e(TAG, "", e);}
850      return false;
851    }
852
853    /** @hide */
854    public boolean cancelPairingUserInput() {
855        try {
856            return sService.cancelPairingUserInput(mAddress);
857        } catch (RemoteException e) {Log.e(TAG, "", e);}
858        return false;
859    }
860
861    /** @hide */
862    public boolean isBluetoothDock() {
863        try {
864            return sService.isBluetoothDock(mAddress);
865        } catch (RemoteException e) {Log.e(TAG, "", e);}
866        return false;
867    }
868
869    /**
870     * Create an RFCOMM {@link BluetoothSocket} ready to start a secure
871     * outgoing connection to this remote device on given channel.
872     * <p>The remote device will be authenticated and communication on this
873     * socket will be encrypted.
874     * <p> Use this socket only if an authenticated socket link is possible.
875     * Authentication refers to the authentication of the link key to
876     * prevent man-in-the-middle type of attacks.
877     * For example, for Bluetooth 2.1 devices, if any of the devices does not
878     * have an input and output capability or just has the ability to
879     * display a numeric key, a secure socket connection is not possible.
880     * In such a case, use {#link createInsecureRfcommSocket}.
881     * For more details, refer to the Security Model section 5.2 (vol 3) of
882     * Bluetooth Core Specification version 2.1 + EDR.
883     * <p>Use {@link BluetoothSocket#connect} to initiate the outgoing
884     * connection.
885     * <p>Valid RFCOMM channels are in range 1 to 30.
886     * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
887     *
888     * @param channel RFCOMM channel to connect to
889     * @return a RFCOMM BluetoothServerSocket ready for an outgoing connection
890     * @throws IOException on error, for example Bluetooth not available, or
891     *                     insufficient permissions
892     * @hide
893     */
894    public BluetoothSocket createRfcommSocket(int channel) throws IOException {
895        return new BluetoothSocket(BluetoothSocket.TYPE_RFCOMM, -1, true, true, this, channel,
896                null);
897    }
898
899    /**
900     * Create an RFCOMM {@link BluetoothSocket} ready to start a secure
901     * outgoing connection to this remote device using SDP lookup of uuid.
902     * <p>This is designed to be used with {@link
903     * BluetoothAdapter#listenUsingRfcommWithServiceRecord} for peer-peer
904     * Bluetooth applications.
905     * <p>Use {@link BluetoothSocket#connect} to initiate the outgoing
906     * connection. This will also perform an SDP lookup of the given uuid to
907     * determine which channel to connect to.
908     * <p>The remote device will be authenticated and communication on this
909     * socket will be encrypted.
910     * <p> Use this socket only if an authenticated socket link is possible.
911     * Authentication refers to the authentication of the link key to
912     * prevent man-in-the-middle type of attacks.
913     * For example, for Bluetooth 2.1 devices, if any of the devices does not
914     * have an input and output capability or just has the ability to
915     * display a numeric key, a secure socket connection is not possible.
916     * In such a case, use {#link createInsecureRfcommSocketToServiceRecord}.
917     * For more details, refer to the Security Model section 5.2 (vol 3) of
918     * Bluetooth Core Specification version 2.1 + EDR.
919     * <p>Hint: If you are connecting to a Bluetooth serial board then try
920     * using the well-known SPP UUID 00001101-0000-1000-8000-00805F9B34FB.
921     * However if you are connecting to an Android peer then please generate
922     * your own unique UUID.
923     * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
924     *
925     * @param uuid service record uuid to lookup RFCOMM channel
926     * @return a RFCOMM BluetoothServerSocket ready for an outgoing connection
927     * @throws IOException on error, for example Bluetooth not available, or
928     *                     insufficient permissions
929     */
930    public BluetoothSocket createRfcommSocketToServiceRecord(UUID uuid) throws IOException {
931        return new BluetoothSocket(BluetoothSocket.TYPE_RFCOMM, -1, true, true, this, -1,
932                new ParcelUuid(uuid));
933    }
934
935    /**
936     * Create an RFCOMM {@link BluetoothSocket} socket ready to start an insecure
937     * outgoing connection to this remote device using SDP lookup of uuid.
938     * <p> The communication channel will not have an authenticated link key
939     * i.e it will be subject to man-in-the-middle attacks. For Bluetooth 2.1
940     * devices, the link key will be encrypted, as encryption is mandatory.
941     * For legacy devices (pre Bluetooth 2.1 devices) the link key will
942     * be not be encrypted. Use {@link #createRfcommSocketToServiceRecord} if an
943     * encrypted and authenticated communication channel is desired.
944     * <p>This is designed to be used with {@link
945     * BluetoothAdapter#listenUsingInsecureRfcommWithServiceRecord} for peer-peer
946     * Bluetooth applications.
947     * <p>Use {@link BluetoothSocket#connect} to initiate the outgoing
948     * connection. This will also perform an SDP lookup of the given uuid to
949     * determine which channel to connect to.
950     * <p>The remote device will be authenticated and communication on this
951     * socket will be encrypted.
952     * <p>Hint: If you are connecting to a Bluetooth serial board then try
953     * using the well-known SPP UUID 00001101-0000-1000-8000-00805F9B34FB.
954     * However if you are connecting to an Android peer then please generate
955     * your own unique UUID.
956     * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
957     *
958     * @param uuid service record uuid to lookup RFCOMM channel
959     * @return a RFCOMM BluetoothServerSocket ready for an outgoing connection
960     * @throws IOException on error, for example Bluetooth not available, or
961     *                     insufficient permissions
962     */
963    public BluetoothSocket createInsecureRfcommSocketToServiceRecord(UUID uuid) throws IOException {
964        return new BluetoothSocket(BluetoothSocket.TYPE_RFCOMM, -1, false, false, this, -1,
965                new ParcelUuid(uuid));
966    }
967
968    /**
969     * Construct an insecure RFCOMM socket ready to start an outgoing
970     * connection.
971     * Call #connect on the returned #BluetoothSocket to begin the connection.
972     * The remote device will not be authenticated and communication on this
973     * socket will not be encrypted.
974     * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN}
975     *
976     * @param port    remote port
977     * @return An RFCOMM BluetoothSocket
978     * @throws IOException On error, for example Bluetooth not available, or
979     *                     insufficient permissions.
980     * @hide
981     */
982    public BluetoothSocket createInsecureRfcommSocket(int port) throws IOException {
983        return new BluetoothSocket(BluetoothSocket.TYPE_RFCOMM, -1, false, false, this, port,
984                null);
985    }
986
987    /**
988     * Construct a SCO socket ready to start an outgoing connection.
989     * Call #connect on the returned #BluetoothSocket to begin the connection.
990     * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN}
991     *
992     * @return a SCO BluetoothSocket
993     * @throws IOException on error, for example Bluetooth not available, or
994     *                     insufficient permissions.
995     * @hide
996     */
997    public BluetoothSocket createScoSocket() throws IOException {
998        return new BluetoothSocket(BluetoothSocket.TYPE_SCO, -1, true, true, this, -1, null);
999    }
1000
1001    /**
1002     * Check that a pin is valid and convert to byte array.
1003     *
1004     * Bluetooth pin's are 1 to 16 bytes of UTF-8 characters.
1005     * @param pin pin as java String
1006     * @return the pin code as a UTF-8 byte array, or null if it is an invalid
1007     *         Bluetooth pin.
1008     * @hide
1009     */
1010    public static byte[] convertPinToBytes(String pin) {
1011        if (pin == null) {
1012            return null;
1013        }
1014        byte[] pinBytes;
1015        try {
1016            pinBytes = pin.getBytes("UTF-8");
1017        } catch (UnsupportedEncodingException uee) {
1018            Log.e(TAG, "UTF-8 not supported?!?");  // this should not happen
1019            return null;
1020        }
1021        if (pinBytes.length <= 0 || pinBytes.length > 16) {
1022            return null;
1023        }
1024        return pinBytes;
1025    }
1026
1027}
1028