2 * Copyright (C) 2009 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package android.bluetooth;
19 import android.annotation.SdkConstant;
20 import android.annotation.SdkConstant.SdkConstantType;
21 import android.annotation.SystemApi;
22 import android.content.Context;
23 import android.os.Parcel;
24 import android.os.Parcelable;
25 import android.os.ParcelUuid;
26 import android.os.RemoteException;
27 import android.util.Log;
29 import java.io.IOException;
30 import java.io.UnsupportedEncodingException;
31 import java.util.UUID;
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.
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
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)}.
54 * <p class="note"><strong>Note:</strong>
55 * Requires the {@link android.Manifest.permission#BLUETOOTH} permission.
57 * <div class="special reference">
58 * <h3>Developer Guides</h3>
59 * <p>For more information about using Bluetooth, read the
60 * <a href="{@docRoot}guide/topics/wireless/bluetooth.html">Bluetooth</a> developer guide.</p>
63 * {@see BluetoothAdapter}
64 * {@see BluetoothSocket}
66 public final class BluetoothDevice implements Parcelable {
67 private static final String TAG = "BluetoothDevice";
68 private static final boolean DBG = false;
71 * Connection state bitmask as returned by getConnectionState.
73 private static final int CONNECTION_STATE_DISCONNECTED = 0;
74 private static final int CONNECTION_STATE_CONNECTED = 1;
75 private static final int CONNECTION_STATE_ENCRYPTED_BREDR = 2;
76 private static final int CONNECTION_STATE_ENCRYPTED_LE = 4;
79 * Sentinel error value for this class. Guaranteed to not equal any other
80 * integer constant in this class. Provided as a convenience for functions
81 * that require a sentinel error value, for example:
82 * <p><code>Intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE,
83 * BluetoothDevice.ERROR)</code>
85 public static final int ERROR = Integer.MIN_VALUE;
88 * Broadcast Action: Remote device discovered.
89 * <p>Sent when a remote device is found during discovery.
90 * <p>Always contains the extra fields {@link #EXTRA_DEVICE} and {@link
91 * #EXTRA_CLASS}. Can contain the extra fields {@link #EXTRA_NAME} and/or
92 * {@link #EXTRA_RSSI} if they are available.
93 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} to receive.
95 // TODO: Change API to not broadcast RSSI if not available (incoming connection)
96 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
97 public static final String ACTION_FOUND =
98 "android.bluetooth.device.action.FOUND";
101 * Broadcast Action: Remote device disappeared.
102 * <p>Sent when a remote device that was found in the last discovery is not
103 * found in the current discovery.
104 * <p>Always contains the extra field {@link #EXTRA_DEVICE}.
105 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} to receive.
108 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
109 public static final String ACTION_DISAPPEARED =
110 "android.bluetooth.device.action.DISAPPEARED";
113 * Broadcast Action: Bluetooth class of a remote device has changed.
114 * <p>Always contains the extra fields {@link #EXTRA_DEVICE} and {@link
116 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} to receive.
117 * {@see BluetoothClass}
119 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
120 public static final String ACTION_CLASS_CHANGED =
121 "android.bluetooth.device.action.CLASS_CHANGED";
124 * Broadcast Action: Indicates a low level (ACL) connection has been
125 * established with a remote device.
126 * <p>Always contains the extra field {@link #EXTRA_DEVICE}.
127 * <p>ACL connections are managed automatically by the Android Bluetooth
129 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} to receive.
131 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
132 public static final String ACTION_ACL_CONNECTED =
133 "android.bluetooth.device.action.ACL_CONNECTED";
136 * Broadcast Action: Indicates that a low level (ACL) disconnection has
137 * been requested for a remote device, and it will soon be disconnected.
138 * <p>This is useful for graceful disconnection. Applications should use
139 * this intent as a hint to immediately terminate higher level connections
140 * (RFCOMM, L2CAP, or profile connections) to the remote device.
141 * <p>Always contains the extra field {@link #EXTRA_DEVICE}.
142 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} to receive.
144 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
145 public static final String ACTION_ACL_DISCONNECT_REQUESTED =
146 "android.bluetooth.device.action.ACL_DISCONNECT_REQUESTED";
149 * Broadcast Action: Indicates a low level (ACL) disconnection from a
151 * <p>Always contains the extra field {@link #EXTRA_DEVICE}.
152 * <p>ACL connections are managed automatically by the Android Bluetooth
154 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} to receive.
156 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
157 public static final String ACTION_ACL_DISCONNECTED =
158 "android.bluetooth.device.action.ACL_DISCONNECTED";
161 * Broadcast Action: Indicates the friendly name of a remote device has
162 * been retrieved for the first time, or changed since the last retrieval.
163 * <p>Always contains the extra fields {@link #EXTRA_DEVICE} and {@link
165 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} to receive.
167 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
168 public static final String ACTION_NAME_CHANGED =
169 "android.bluetooth.device.action.NAME_CHANGED";
172 * Broadcast Action: Indicates the alias of a remote device has been
174 * <p>Always contains the extra field {@link #EXTRA_DEVICE}.
175 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} to receive.
179 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
180 public static final String ACTION_ALIAS_CHANGED =
181 "android.bluetooth.device.action.ALIAS_CHANGED";
184 * Broadcast Action: Indicates a change in the bond state of a remote
185 * device. For example, if a device is bonded (paired).
186 * <p>Always contains the extra fields {@link #EXTRA_DEVICE}, {@link
187 * #EXTRA_BOND_STATE} and {@link #EXTRA_PREVIOUS_BOND_STATE}.
188 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} to receive.
190 // Note: When EXTRA_BOND_STATE is BOND_NONE then this will also
191 // contain a hidden extra field EXTRA_REASON with the result code.
192 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
193 public static final String ACTION_BOND_STATE_CHANGED =
194 "android.bluetooth.device.action.BOND_STATE_CHANGED";
197 * Used as a Parcelable {@link BluetoothDevice} extra field in every intent
198 * broadcast by this class. It contains the {@link BluetoothDevice} that
199 * the intent applies to.
201 public static final String EXTRA_DEVICE = "android.bluetooth.device.extra.DEVICE";
204 * Used as a String extra field in {@link #ACTION_NAME_CHANGED} and {@link
205 * #ACTION_FOUND} intents. It contains the friendly Bluetooth name.
207 public static final String EXTRA_NAME = "android.bluetooth.device.extra.NAME";
210 * Used as an optional short extra field in {@link #ACTION_FOUND} intents.
211 * Contains the RSSI value of the remote device as reported by the
212 * Bluetooth hardware.
214 public static final String EXTRA_RSSI = "android.bluetooth.device.extra.RSSI";
217 * Used as a Parcelable {@link BluetoothClass} extra field in {@link
218 * #ACTION_FOUND} and {@link #ACTION_CLASS_CHANGED} intents.
220 public static final String EXTRA_CLASS = "android.bluetooth.device.extra.CLASS";
223 * Used as an int extra field in {@link #ACTION_BOND_STATE_CHANGED} intents.
224 * Contains the bond state of the remote device.
225 * <p>Possible values are:
226 * {@link #BOND_NONE},
227 * {@link #BOND_BONDING},
228 * {@link #BOND_BONDED}.
230 public static final String EXTRA_BOND_STATE = "android.bluetooth.device.extra.BOND_STATE";
232 * Used as an int extra field in {@link #ACTION_BOND_STATE_CHANGED} intents.
233 * Contains the previous bond state of the remote device.
234 * <p>Possible values are:
235 * {@link #BOND_NONE},
236 * {@link #BOND_BONDING},
237 * {@link #BOND_BONDED}.
239 public static final String EXTRA_PREVIOUS_BOND_STATE =
240 "android.bluetooth.device.extra.PREVIOUS_BOND_STATE";
242 * Indicates the remote device is not bonded (paired).
243 * <p>There is no shared link key with the remote device, so communication
244 * (if it is allowed at all) will be unauthenticated and unencrypted.
246 public static final int BOND_NONE = 10;
248 * Indicates bonding (pairing) is in progress with the remote device.
250 public static final int BOND_BONDING = 11;
252 * Indicates the remote device is bonded (paired).
253 * <p>A shared link keys exists locally for the remote device, so
254 * communication can be authenticated and encrypted.
255 * <p><i>Being bonded (paired) with a remote device does not necessarily
256 * mean the device is currently connected. It just means that the pending
257 * procedure was completed at some earlier time, and the link key is still
258 * stored locally, ready to use on the next connection.
261 public static final int BOND_BONDED = 12;
264 * Used as an int extra field in {@link #ACTION_PAIRING_REQUEST}
265 * intents for unbond reason.
268 public static final String EXTRA_REASON = "android.bluetooth.device.extra.REASON";
271 * Used as an int extra field in {@link #ACTION_PAIRING_REQUEST}
272 * intents to indicate pairing method used. Possible values are:
273 * {@link #PAIRING_VARIANT_PIN},
274 * {@link #PAIRING_VARIANT_PASSKEY_CONFIRMATION},
276 public static final String EXTRA_PAIRING_VARIANT =
277 "android.bluetooth.device.extra.PAIRING_VARIANT";
280 * Used as an int extra field in {@link #ACTION_PAIRING_REQUEST}
281 * intents as the value of passkey.
283 public static final String EXTRA_PAIRING_KEY = "android.bluetooth.device.extra.PAIRING_KEY";
286 * Bluetooth device type, Unknown
288 public static final int DEVICE_TYPE_UNKNOWN = 0;
291 * Bluetooth device type, Classic - BR/EDR devices
293 public static final int DEVICE_TYPE_CLASSIC = 1;
296 * Bluetooth device type, Low Energy - LE-only
298 public static final int DEVICE_TYPE_LE = 2;
301 * Bluetooth device type, Dual Mode - BR/EDR/LE
303 public static final int DEVICE_TYPE_DUAL = 3;
306 * Broadcast Action: This intent is used to broadcast the {@link UUID}
307 * wrapped as a {@link android.os.ParcelUuid} of the remote device after it
308 * has been fetched. This intent is sent only when the UUIDs of the remote
309 * device are requested to be fetched using Service Discovery Protocol
310 * <p> Always contains the extra field {@link #EXTRA_DEVICE}
311 * <p> Always contains the extra field {@link #EXTRA_UUID}
312 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} to receive.
314 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
315 public static final String ACTION_UUID =
316 "android.bluetooth.device.action.UUID";
319 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
320 public static final String ACTION_MAS_INSTANCE =
321 "android.bluetooth.device.action.MAS_INSTANCE";
324 * Broadcast Action: Indicates a failure to retrieve the name of a remote
326 * <p>Always contains the extra field {@link #EXTRA_DEVICE}.
327 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} to receive.
330 //TODO: is this actually useful?
331 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
332 public static final String ACTION_NAME_FAILED =
333 "android.bluetooth.device.action.NAME_FAILED";
336 * Broadcast Action: This intent is used to broadcast PAIRING REQUEST
337 * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN} to
340 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
341 public static final String ACTION_PAIRING_REQUEST =
342 "android.bluetooth.device.action.PAIRING_REQUEST";
344 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
345 public static final String ACTION_PAIRING_CANCEL =
346 "android.bluetooth.device.action.PAIRING_CANCEL";
349 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
350 public static final String ACTION_CONNECTION_ACCESS_REQUEST =
351 "android.bluetooth.device.action.CONNECTION_ACCESS_REQUEST";
354 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
355 public static final String ACTION_CONNECTION_ACCESS_REPLY =
356 "android.bluetooth.device.action.CONNECTION_ACCESS_REPLY";
359 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
360 public static final String ACTION_CONNECTION_ACCESS_CANCEL =
361 "android.bluetooth.device.action.CONNECTION_ACCESS_CANCEL";
364 * Used as an extra field in {@link #ACTION_CONNECTION_ACCESS_REQUEST} intent.
367 public static final String EXTRA_ACCESS_REQUEST_TYPE =
368 "android.bluetooth.device.extra.ACCESS_REQUEST_TYPE";
371 public static final int REQUEST_TYPE_PROFILE_CONNECTION = 1;
374 public static final int REQUEST_TYPE_PHONEBOOK_ACCESS = 2;
377 public static final int REQUEST_TYPE_MESSAGE_ACCESS = 3;
380 * Used as an extra field in {@link #ACTION_CONNECTION_ACCESS_REQUEST} intents,
381 * Contains package name to return reply intent to.
384 public static final String EXTRA_PACKAGE_NAME = "android.bluetooth.device.extra.PACKAGE_NAME";
387 * Used as an extra field in {@link #ACTION_CONNECTION_ACCESS_REQUEST} intents,
388 * Contains class name to return reply intent to.
391 public static final String EXTRA_CLASS_NAME = "android.bluetooth.device.extra.CLASS_NAME";
394 * Used as an extra field in {@link #ACTION_CONNECTION_ACCESS_REPLY} intent.
397 public static final String EXTRA_CONNECTION_ACCESS_RESULT =
398 "android.bluetooth.device.extra.CONNECTION_ACCESS_RESULT";
401 public static final int CONNECTION_ACCESS_YES = 1;
404 public static final int CONNECTION_ACCESS_NO = 2;
407 * Used as an extra field in {@link #ACTION_CONNECTION_ACCESS_REPLY} intents,
408 * Contains boolean to indicate if the allowed response is once-for-all so that
409 * next request will be granted without asking user again.
412 public static final String EXTRA_ALWAYS_ALLOWED =
413 "android.bluetooth.device.extra.ALWAYS_ALLOWED";
416 * A bond attempt succeeded
419 public static final int BOND_SUCCESS = 0;
422 * A bond attempt failed because pins did not match, or remote device did
423 * not respond to pin request in time
426 public static final int UNBOND_REASON_AUTH_FAILED = 1;
429 * A bond attempt failed because the other side explicitly rejected
433 public static final int UNBOND_REASON_AUTH_REJECTED = 2;
436 * A bond attempt failed because we canceled the bonding process
439 public static final int UNBOND_REASON_AUTH_CANCELED = 3;
442 * A bond attempt failed because we could not contact the remote device
445 public static final int UNBOND_REASON_REMOTE_DEVICE_DOWN = 4;
448 * A bond attempt failed because a discovery is in progress
451 public static final int UNBOND_REASON_DISCOVERY_IN_PROGRESS = 5;
454 * A bond attempt failed because of authentication timeout
457 public static final int UNBOND_REASON_AUTH_TIMEOUT = 6;
460 * A bond attempt failed because of repeated attempts
463 public static final int UNBOND_REASON_REPEATED_ATTEMPTS = 7;
466 * A bond attempt failed because we received an Authentication Cancel
470 public static final int UNBOND_REASON_REMOTE_AUTH_CANCELED = 8;
473 * An existing bond was explicitly revoked
476 public static final int UNBOND_REASON_REMOVED = 9;
479 * The user will be prompted to enter a pin or
480 * an app will enter a pin for user.
482 public static final int PAIRING_VARIANT_PIN = 0;
485 * The user will be prompted to enter a passkey
488 public static final int PAIRING_VARIANT_PASSKEY = 1;
491 * The user will be prompted to confirm the passkey displayed on the screen or
492 * an app will confirm the passkey for the user.
494 public static final int PAIRING_VARIANT_PASSKEY_CONFIRMATION = 2;
497 * The user will be prompted to accept or deny the incoming pairing request
500 public static final int PAIRING_VARIANT_CONSENT = 3;
503 * The user will be prompted to enter the passkey displayed on remote device
504 * This is used for Bluetooth 2.1 pairing.
507 public static final int PAIRING_VARIANT_DISPLAY_PASSKEY = 4;
510 * The user will be prompted to enter the PIN displayed on remote device.
511 * This is used for Bluetooth 2.0 pairing.
514 public static final int PAIRING_VARIANT_DISPLAY_PIN = 5;
517 * The user will be prompted to accept or deny the OOB pairing request
520 public static final int PAIRING_VARIANT_OOB_CONSENT = 6;
523 * Used as an extra field in {@link #ACTION_UUID} intents,
524 * Contains the {@link android.os.ParcelUuid}s of the remote device which
525 * is a parcelable version of {@link UUID}.
527 public static final String EXTRA_UUID = "android.bluetooth.device.extra.UUID";
530 * For {@link #getPhonebookAccessPermission}, {@link #setPhonebookAccessPermission},
531 * {@link #getMessageAccessPermission} and {@link #setMessageAccessPermission}.
534 public static final int ACCESS_UNKNOWN = 0;
537 * For {@link #getPhonebookAccessPermission}, {@link #setPhonebookAccessPermission},
538 * {@link #getMessageAccessPermission} and {@link #setMessageAccessPermission}.
541 public static final int ACCESS_ALLOWED = 1;
544 * For {@link #getPhonebookAccessPermission}, {@link #setPhonebookAccessPermission},
545 * {@link #getMessageAccessPermission} and {@link #setMessageAccessPermission}.
548 public static final int ACCESS_REJECTED = 2;
551 * No preferrence of physical transport for GATT connections to remote dual-mode devices
554 public static final int TRANSPORT_AUTO = 0;
557 * Prefer BR/EDR transport for GATT connections to remote dual-mode devices
560 public static final int TRANSPORT_BREDR = 1;
563 * Prefer LE transport for GATT connections to remote dual-mode devices
566 public static final int TRANSPORT_LE = 2;
569 public static final String EXTRA_MAS_INSTANCE =
570 "android.bluetooth.device.extra.MAS_INSTANCE";
573 * Lazy initialization. Guaranteed final after first object constructed, or
574 * getService() called.
575 * TODO: Unify implementation of sService amongst BluetoothFoo API's
577 private static IBluetooth sService;
579 private final String mAddress;
581 /*package*/ static IBluetooth getService() {
582 synchronized (BluetoothDevice.class) {
583 if (sService == null) {
584 BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
585 sService = adapter.getBluetoothService(mStateChangeCallback);
591 static IBluetoothManagerCallback mStateChangeCallback = new IBluetoothManagerCallback.Stub() {
593 public void onBluetoothServiceUp(IBluetooth bluetoothService)
594 throws RemoteException {
595 synchronized (BluetoothDevice.class) {
596 sService = bluetoothService;
600 public void onBluetoothServiceDown()
601 throws RemoteException {
602 synchronized (BluetoothDevice.class) {
608 * Create a new BluetoothDevice
609 * Bluetooth MAC address must be upper case, such as "00:11:22:33:AA:BB",
610 * and is validated in this constructor.
611 * @param address valid Bluetooth MAC address
612 * @throws RuntimeException Bluetooth is not available on this platform
613 * @throws IllegalArgumentException address is invalid
616 /*package*/ BluetoothDevice(String address) {
617 getService(); // ensures sService is initialized
618 if (!BluetoothAdapter.checkBluetoothAddress(address)) {
619 throw new IllegalArgumentException(address + " is not a valid Bluetooth address");
626 public boolean equals(Object o) {
627 if (o instanceof BluetoothDevice) {
628 return mAddress.equals(((BluetoothDevice)o).getAddress());
634 public int hashCode() {
635 return mAddress.hashCode();
639 * Returns a string representation of this BluetoothDevice.
640 * <p>Currently this is the Bluetooth hardware address, for example
641 * "00:11:22:AA:BB:CC". However, you should always use {@link #getAddress}
642 * if you explicitly require the Bluetooth hardware address in case the
643 * {@link #toString} representation changes in the future.
644 * @return string representation of this BluetoothDevice
647 public String toString() {
651 public int describeContents() {
655 public static final Parcelable.Creator<BluetoothDevice> CREATOR =
656 new Parcelable.Creator<BluetoothDevice>() {
657 public BluetoothDevice createFromParcel(Parcel in) {
658 return new BluetoothDevice(in.readString());
660 public BluetoothDevice[] newArray(int size) {
661 return new BluetoothDevice[size];
665 public void writeToParcel(Parcel out, int flags) {
666 out.writeString(mAddress);
670 * Returns the hardware address of this BluetoothDevice.
671 * <p> For example, "00:11:22:AA:BB:CC".
672 * @return Bluetooth hardware address as string
674 public String getAddress() {
675 if (DBG) Log.d(TAG, "mAddress: " + mAddress);
680 * Get the friendly Bluetooth name of the remote device.
682 * <p>The local adapter will automatically retrieve remote names when
683 * performing a device scan, and will cache them. This method just returns
684 * the name for this device from the cache.
685 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
687 * @return the Bluetooth name, or null if there was a problem.
689 public String getName() {
690 if (sService == null) {
691 Log.e(TAG, "BT not enabled. Cannot get Remote Device name");
695 return sService.getRemoteName(this);
696 } catch (RemoteException e) {Log.e(TAG, "", e);}
701 * Get the Bluetooth device type of the remote device.
703 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
705 * @return the device type {@link #DEVICE_TYPE_CLASSIC}, {@link #DEVICE_TYPE_LE}
706 * {@link #DEVICE_TYPE_DUAL}.
707 * {@link #DEVICE_TYPE_UNKNOWN} if it's not available
709 public int getType() {
710 if (sService == null) {
711 Log.e(TAG, "BT not enabled. Cannot get Remote Device type");
712 return DEVICE_TYPE_UNKNOWN;
715 return sService.getRemoteType(this);
716 } catch (RemoteException e) {Log.e(TAG, "", e);}
717 return DEVICE_TYPE_UNKNOWN;
721 * Get the Bluetooth alias of the remote device.
722 * <p>Alias is the locally modified name of a remote device.
724 * @return the Bluetooth alias, or null if no alias or there was a problem
727 public String getAlias() {
728 if (sService == null) {
729 Log.e(TAG, "BT not enabled. Cannot get Remote Device Alias");
733 return sService.getRemoteAlias(this);
734 } catch (RemoteException e) {Log.e(TAG, "", e);}
739 * Set the Bluetooth alias of the remote device.
740 * <p>Alias is the locally modified name of a remote device.
741 * <p>This methoid overwrites the alias. The changed
742 * alias is saved in the local storage so that the change
743 * is preserved over power cycle.
745 * @return true on success, false on error
748 public boolean setAlias(String alias) {
749 if (sService == null) {
750 Log.e(TAG, "BT not enabled. Cannot set Remote Device name");
754 return sService.setRemoteAlias(this, alias);
755 } catch (RemoteException e) {Log.e(TAG, "", e);}
760 * Get the Bluetooth alias of the remote device.
761 * If Alias is null, get the Bluetooth name instead.
765 * @return the Bluetooth alias, or null if no alias or there was a problem
768 public String getAliasName() {
769 String name = getAlias();
777 * Start the bonding (pairing) process with the remote device.
778 * <p>This is an asynchronous call, it will return immediately. Register
779 * for {@link #ACTION_BOND_STATE_CHANGED} intents to be notified when
780 * the bonding process completes, and its result.
781 * <p>Android system services will handle the necessary user interactions
782 * to confirm and complete the bonding process.
783 * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN}.
785 * @return false on immediate error, true if bonding will begin
787 public boolean createBond() {
788 if (sService == null) {
789 Log.e(TAG, "BT not enabled. Cannot create bond to Remote Device");
793 return sService.createBond(this, TRANSPORT_AUTO);
794 } catch (RemoteException e) {Log.e(TAG, "", e);}
799 * Start the bonding (pairing) process with the remote device using the
800 * specified transport.
802 * <p>This is an asynchronous call, it will return immediately. Register
803 * for {@link #ACTION_BOND_STATE_CHANGED} intents to be notified when
804 * the bonding process completes, and its result.
805 * <p>Android system services will handle the necessary user interactions
806 * to confirm and complete the bonding process.
807 * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN}.
809 * @param transport The transport to use for the pairing procedure.
810 * @return false on immediate error, true if bonding will begin
811 * @throws IllegalArgumentException if an invalid transport was specified
814 public boolean createBond(int transport) {
815 if (sService == null) {
816 Log.e(TAG, "BT not enabled. Cannot create bond to Remote Device");
819 if (TRANSPORT_AUTO > transport || transport > TRANSPORT_LE)
821 throw new IllegalArgumentException(transport + " is not a valid Bluetooth transport");
824 return sService.createBond(this, transport);
825 } catch (RemoteException e) {Log.e(TAG, "", e);}
830 * Start the bonding (pairing) process with the remote device using the
831 * Out Of Band mechanism.
833 * <p>This is an asynchronous call, it will return immediately. Register
834 * for {@link #ACTION_BOND_STATE_CHANGED} intents to be notified when
835 * the bonding process completes, and its result.
837 * <p>Android system services will handle the necessary user interactions
838 * to confirm and complete the bonding process.
840 * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN}.
842 * @param hash - Simple Secure pairing hash
843 * @param randomizer - The random key obtained using OOB
844 * @return false on immediate error, true if bonding will begin
848 public boolean createBondOutOfBand(byte[] hash, byte[] randomizer) {
852 return sService.createBondOutOfBand(this, hash, randomizer);
853 } catch (RemoteException e) {Log.e(TAG, "", e);}*/
858 * Set the Out Of Band data for a remote device to be used later
859 * in the pairing mechanism. Users can obtain this data through other
862 * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN}.
864 * @param hash Simple Secure pairing hash
865 * @param randomizer The random key obtained using OOB
866 * @return false on error; true otherwise
870 public boolean setDeviceOutOfBandData(byte[] hash, byte[] randomizer) {
874 return sService.setDeviceOutOfBandData(this, hash, randomizer);
875 } catch (RemoteException e) {Log.e(TAG, "", e);} */
880 * Cancel an in-progress bonding request started with {@link #createBond}.
881 * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN}.
883 * @return true on success, false on error
886 public boolean cancelBondProcess() {
887 if (sService == null) {
888 Log.e(TAG, "BT not enabled. Cannot cancel Remote Device bond");
892 return sService.cancelBondProcess(this);
893 } catch (RemoteException e) {Log.e(TAG, "", e);}
898 * Remove bond (pairing) with the remote device.
899 * <p>Delete the link key associated with the remote device, and
900 * immediately terminate connections to that device that require
901 * authentication and encryption.
902 * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN}.
904 * @return true on success, false on error
907 public boolean removeBond() {
908 if (sService == null) {
909 Log.e(TAG, "BT not enabled. Cannot remove Remote Device bond");
913 return sService.removeBond(this);
914 } catch (RemoteException e) {Log.e(TAG, "", e);}
919 * Get the bond state of the remote device.
920 * <p>Possible values for the bond state are:
921 * {@link #BOND_NONE},
922 * {@link #BOND_BONDING},
923 * {@link #BOND_BONDED}.
924 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}.
926 * @return the bond state
928 public int getBondState() {
929 if (sService == null) {
930 Log.e(TAG, "BT not enabled. Cannot get bond state");
934 return sService.getBondState(this);
935 } catch (RemoteException e) {Log.e(TAG, "", e);}
936 catch (NullPointerException npe) {
937 // Handle case where bluetooth service proxy
939 Log.e(TAG, "NullPointerException for getBondState() of device ("+
940 getAddress()+")", npe);
946 * Returns whether there is an open connection to this device.
947 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}.
949 * @return True if there is at least one open connection to this device.
953 public boolean isConnected() {
954 if (sService == null) {
955 // BT is not enabled, we cannot be connected.
959 return sService.getConnectionState(this) != CONNECTION_STATE_DISCONNECTED;
960 } catch (RemoteException e) {
967 * Returns whether there is an open connection to this device
968 * that has been encrypted.
969 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}.
971 * @return True if there is at least one encrypted connection to this device.
975 public boolean isEncrypted() {
976 if (sService == null) {
977 // BT is not enabled, we cannot be connected.
981 return sService.getConnectionState(this) > CONNECTION_STATE_CONNECTED;
982 } catch (RemoteException e) {
989 * Get the Bluetooth class of the remote device.
990 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}.
992 * @return Bluetooth class object, or null on error
994 public BluetoothClass getBluetoothClass() {
995 if (sService == null) {
996 Log.e(TAG, "BT not enabled. Cannot get Bluetooth Class");
1000 int classInt = sService.getRemoteClass(this);
1001 if (classInt == BluetoothClass.ERROR) return null;
1002 return new BluetoothClass(classInt);
1003 } catch (RemoteException e) {Log.e(TAG, "", e);}
1008 * Returns the supported features (UUIDs) of the remote device.
1010 * <p>This method does not start a service discovery procedure to retrieve the UUIDs
1011 * from the remote device. Instead, the local cached copy of the service
1012 * UUIDs are returned.
1013 * <p>Use {@link #fetchUuidsWithSdp} if fresh UUIDs are desired.
1014 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}.
1016 * @return the supported features (UUIDs) of the remote device,
1019 public ParcelUuid[] getUuids() {
1020 if (sService == null) {
1021 Log.e(TAG, "BT not enabled. Cannot get remote device Uuids");
1025 return sService.getRemoteUuids(this);
1026 } catch (RemoteException e) {Log.e(TAG, "", e);}
1031 * Perform a service discovery on the remote device to get the UUIDs supported.
1033 * <p>This API is asynchronous and {@link #ACTION_UUID} intent is sent,
1034 * with the UUIDs supported by the remote end. If there is an error
1035 * in getting the SDP records or if the process takes a long time,
1036 * {@link #ACTION_UUID} intent is sent with the UUIDs that is currently
1037 * present in the cache. Clients should use the {@link #getUuids} to get UUIDs
1038 * if service discovery is not to be performed.
1039 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}.
1041 * @return False if the sanity check fails, True if the process
1042 * of initiating an ACL connection to the remote device
1045 public boolean fetchUuidsWithSdp() {
1046 IBluetooth service = sService;
1047 if (service == null) {
1048 Log.e(TAG, "BT not enabled. Cannot fetchUuidsWithSdp");
1052 return service.fetchRemoteUuids(this);
1053 } catch (RemoteException e) {Log.e(TAG, "", e);}
1058 public boolean fetchMasInstances() {
1059 if (sService == null) {
1060 Log.e(TAG, "BT not enabled. Cannot query remote device for MAS instances");
1064 return sService.fetchRemoteMasInstances(this);
1065 } catch (RemoteException e) {Log.e(TAG, "", e);}
1070 public int getServiceChannel(ParcelUuid uuid) {
1074 return sService.getRemoteServiceChannel(this, uuid);
1075 } catch (RemoteException e) {Log.e(TAG, "", e);}*/
1076 return BluetoothDevice.ERROR;
1080 * Set the pin during pairing when the pairing method is {@link #PAIRING_VARIANT_PIN}
1081 * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN}.
1083 * @return true pin has been set
1086 public boolean setPin(byte[] pin) {
1087 if (sService == null) {
1088 Log.e(TAG, "BT not enabled. Cannot set Remote Device pin");
1092 return sService.setPin(this, true, pin.length, pin);
1093 } catch (RemoteException e) {Log.e(TAG, "", e);}
1098 public boolean setPasskey(int passkey) {
1102 return sService.setPasskey(this, true, 4, passkey);
1103 } catch (RemoteException e) {Log.e(TAG, "", e);}*/
1108 * Confirm passkey for {@link #PAIRING_VARIANT_PASSKEY_CONFIRMATION} pairing.
1109 * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN}.
1111 * @return true confirmation has been sent out
1114 public boolean setPairingConfirmation(boolean confirm) {
1115 if (sService == null) {
1116 Log.e(TAG, "BT not enabled. Cannot set pairing confirmation");
1120 return sService.setPairingConfirmation(this, confirm);
1121 } catch (RemoteException e) {Log.e(TAG, "", e);}
1126 public boolean setRemoteOutOfBandData() {
1130 return sService.setRemoteOutOfBandData(this);
1131 } catch (RemoteException e) {Log.e(TAG, "", e);}*/
1136 public boolean cancelPairingUserInput() {
1137 if (sService == null) {
1138 Log.e(TAG, "BT not enabled. Cannot create pairing user input");
1142 return sService.cancelBondProcess(this);
1143 } catch (RemoteException e) {Log.e(TAG, "", e);}
1148 public boolean isBluetoothDock() {
1152 return sService.isBluetoothDock(this);
1153 } catch (RemoteException e) {Log.e(TAG, "", e);}*/
1158 * Requires {@link android.Manifest.permission#BLUETOOTH}.
1159 * @return Whether the phonebook access is allowed to this device. Can be
1160 * {@link #ACCESS_UNKNOWN}, {@link #ACCESS_ALLOWED} or {@link #ACCESS_REJECTED}.
1163 public int getPhonebookAccessPermission() {
1164 if (sService == null) {
1165 return ACCESS_UNKNOWN;
1168 return sService.getPhonebookAccessPermission(this);
1169 } catch (RemoteException e) {
1172 return ACCESS_UNKNOWN;
1176 * Sets whether the phonebook access is allowed to this device.
1177 * <p>Requires {@link android.Manifest.permission#BLUETOOTH_PRIVILEGED}.
1178 * @param value Can be {@link #ACCESS_UNKNOWN}, {@link #ACCESS_ALLOWED} or
1179 * {@link #ACCESS_REJECTED}.
1180 * @return Whether the value has been successfully set.
1183 public boolean setPhonebookAccessPermission(int value) {
1184 if (sService == null) {
1188 return sService.setPhonebookAccessPermission(this, value);
1189 } catch (RemoteException e) {
1196 * Requires {@link android.Manifest.permission#BLUETOOTH}.
1197 * @return Whether the message access is allowed to this device. Can be
1198 * {@link #ACCESS_UNKNOWN}, {@link #ACCESS_ALLOWED} or {@link #ACCESS_REJECTED}.
1201 public int getMessageAccessPermission() {
1202 if (sService == null) {
1203 return ACCESS_UNKNOWN;
1206 return sService.getMessageAccessPermission(this);
1207 } catch (RemoteException e) {
1210 return ACCESS_UNKNOWN;
1214 * Sets whether the message access is allowed to this device.
1215 * <p>Requires {@link android.Manifest.permission#BLUETOOTH_PRIVILEGED}.
1216 * @param value Can be {@link #ACCESS_UNKNOWN}, {@link #ACCESS_ALLOWED} or
1217 * {@link #ACCESS_REJECTED}.
1218 * @return Whether the value has been successfully set.
1221 public boolean setMessageAccessPermission(int value) {
1222 if (sService == null) {
1226 return sService.setMessageAccessPermission(this, value);
1227 } catch (RemoteException e) {
1234 * Create an RFCOMM {@link BluetoothSocket} ready to start a secure
1235 * outgoing connection to this remote device on given channel.
1236 * <p>The remote device will be authenticated and communication on this
1237 * socket will be encrypted.
1238 * <p> Use this socket only if an authenticated socket link is possible.
1239 * Authentication refers to the authentication of the link key to
1240 * prevent man-in-the-middle type of attacks.
1241 * For example, for Bluetooth 2.1 devices, if any of the devices does not
1242 * have an input and output capability or just has the ability to
1243 * display a numeric key, a secure socket connection is not possible.
1244 * In such a case, use {#link createInsecureRfcommSocket}.
1245 * For more details, refer to the Security Model section 5.2 (vol 3) of
1246 * Bluetooth Core Specification version 2.1 + EDR.
1247 * <p>Use {@link BluetoothSocket#connect} to initiate the outgoing
1249 * <p>Valid RFCOMM channels are in range 1 to 30.
1250 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
1252 * @param channel RFCOMM channel to connect to
1253 * @return a RFCOMM BluetoothServerSocket ready for an outgoing connection
1254 * @throws IOException on error, for example Bluetooth not available, or
1255 * insufficient permissions
1258 public BluetoothSocket createRfcommSocket(int channel) throws IOException {
1259 return new BluetoothSocket(BluetoothSocket.TYPE_RFCOMM, -1, true, true, this, channel,
1264 * Create an RFCOMM {@link BluetoothSocket} ready to start a secure
1265 * outgoing connection to this remote device using SDP lookup of uuid.
1266 * <p>This is designed to be used with {@link
1267 * BluetoothAdapter#listenUsingRfcommWithServiceRecord} for peer-peer
1268 * Bluetooth applications.
1269 * <p>Use {@link BluetoothSocket#connect} to initiate the outgoing
1270 * connection. This will also perform an SDP lookup of the given uuid to
1271 * determine which channel to connect to.
1272 * <p>The remote device will be authenticated and communication on this
1273 * socket will be encrypted.
1274 * <p> Use this socket only if an authenticated socket link is possible.
1275 * Authentication refers to the authentication of the link key to
1276 * prevent man-in-the-middle type of attacks.
1277 * For example, for Bluetooth 2.1 devices, if any of the devices does not
1278 * have an input and output capability or just has the ability to
1279 * display a numeric key, a secure socket connection is not possible.
1280 * In such a case, use {#link createInsecureRfcommSocketToServiceRecord}.
1281 * For more details, refer to the Security Model section 5.2 (vol 3) of
1282 * Bluetooth Core Specification version 2.1 + EDR.
1283 * <p>Hint: If you are connecting to a Bluetooth serial board then try
1284 * using the well-known SPP UUID 00001101-0000-1000-8000-00805F9B34FB.
1285 * However if you are connecting to an Android peer then please generate
1286 * your own unique UUID.
1287 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
1289 * @param uuid service record uuid to lookup RFCOMM channel
1290 * @return a RFCOMM BluetoothServerSocket ready for an outgoing connection
1291 * @throws IOException on error, for example Bluetooth not available, or
1292 * insufficient permissions
1294 public BluetoothSocket createRfcommSocketToServiceRecord(UUID uuid) throws IOException {
1295 return new BluetoothSocket(BluetoothSocket.TYPE_RFCOMM, -1, true, true, this, -1,
1296 new ParcelUuid(uuid));
1300 * Create an RFCOMM {@link BluetoothSocket} socket ready to start an insecure
1301 * outgoing connection to this remote device using SDP lookup of uuid.
1302 * <p> The communication channel will not have an authenticated link key
1303 * i.e it will be subject to man-in-the-middle attacks. For Bluetooth 2.1
1304 * devices, the link key will be encrypted, as encryption is mandatory.
1305 * For legacy devices (pre Bluetooth 2.1 devices) the link key will
1306 * be not be encrypted. Use {@link #createRfcommSocketToServiceRecord} if an
1307 * encrypted and authenticated communication channel is desired.
1308 * <p>This is designed to be used with {@link
1309 * BluetoothAdapter#listenUsingInsecureRfcommWithServiceRecord} for peer-peer
1310 * Bluetooth applications.
1311 * <p>Use {@link BluetoothSocket#connect} to initiate the outgoing
1312 * connection. This will also perform an SDP lookup of the given uuid to
1313 * determine which channel to connect to.
1314 * <p>The remote device will be authenticated and communication on this
1315 * socket will be encrypted.
1316 * <p>Hint: If you are connecting to a Bluetooth serial board then try
1317 * using the well-known SPP UUID 00001101-0000-1000-8000-00805F9B34FB.
1318 * However if you are connecting to an Android peer then please generate
1319 * your own unique UUID.
1320 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
1322 * @param uuid service record uuid to lookup RFCOMM channel
1323 * @return a RFCOMM BluetoothServerSocket ready for an outgoing connection
1324 * @throws IOException on error, for example Bluetooth not available, or
1325 * insufficient permissions
1327 public BluetoothSocket createInsecureRfcommSocketToServiceRecord(UUID uuid) throws IOException {
1328 return new BluetoothSocket(BluetoothSocket.TYPE_RFCOMM, -1, false, false, this, -1,
1329 new ParcelUuid(uuid));
1333 * Construct an insecure RFCOMM socket ready to start an outgoing
1335 * Call #connect on the returned #BluetoothSocket to begin the connection.
1336 * The remote device will not be authenticated and communication on this
1337 * socket will not be encrypted.
1338 * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN}
1340 * @param port remote port
1341 * @return An RFCOMM BluetoothSocket
1342 * @throws IOException On error, for example Bluetooth not available, or
1343 * insufficient permissions.
1346 public BluetoothSocket createInsecureRfcommSocket(int port) throws IOException {
1347 return new BluetoothSocket(BluetoothSocket.TYPE_RFCOMM, -1, false, false, this, port,
1352 * Construct a SCO socket ready to start an outgoing connection.
1353 * Call #connect on the returned #BluetoothSocket to begin the connection.
1354 * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN}
1356 * @return a SCO BluetoothSocket
1357 * @throws IOException on error, for example Bluetooth not available, or
1358 * insufficient permissions.
1361 public BluetoothSocket createScoSocket() throws IOException {
1362 return new BluetoothSocket(BluetoothSocket.TYPE_SCO, -1, true, true, this, -1, null);
1366 * Check that a pin is valid and convert to byte array.
1368 * Bluetooth pin's are 1 to 16 bytes of UTF-8 characters.
1369 * @param pin pin as java String
1370 * @return the pin code as a UTF-8 byte array, or null if it is an invalid
1374 public static byte[] convertPinToBytes(String pin) {
1380 pinBytes = pin.getBytes("UTF-8");
1381 } catch (UnsupportedEncodingException uee) {
1382 Log.e(TAG, "UTF-8 not supported?!?"); // this should not happen
1385 if (pinBytes.length <= 0 || pinBytes.length > 16) {
1392 * Connect to GATT Server hosted by this device. Caller acts as GATT client.
1393 * The callback is used to deliver results to Caller, such as connection status as well
1394 * as any further GATT client operations.
1395 * The method returns a BluetoothGatt instance. You can use BluetoothGatt to conduct
1396 * GATT client operations.
1397 * @param callback GATT callback handler that will receive asynchronous callbacks.
1398 * @param autoConnect Whether to directly connect to the remote device (false)
1399 * or to automatically connect as soon as the remote
1400 * device becomes available (true).
1401 * @throws IllegalArgumentException if callback is null
1403 public BluetoothGatt connectGatt(Context context, boolean autoConnect,
1404 BluetoothGattCallback callback) {
1405 return (connectGatt(context, autoConnect,callback, TRANSPORT_AUTO));
1409 * Connect to GATT Server hosted by this device. Caller acts as GATT client.
1410 * The callback is used to deliver results to Caller, such as connection status as well
1411 * as any further GATT client operations.
1412 * The method returns a BluetoothGatt instance. You can use BluetoothGatt to conduct
1413 * GATT client operations.
1414 * @param callback GATT callback handler that will receive asynchronous callbacks.
1415 * @param autoConnect Whether to directly connect to the remote device (false)
1416 * or to automatically connect as soon as the remote
1417 * device becomes available (true).
1418 * @param transport preferred transport for GATT connections to remote dual-mode devices
1419 * {@link BluetoothDevice#TRANSPORT_AUTO} or
1420 * {@link BluetoothDevice#TRANSPORT_BREDR} or {@link BluetoothDevice#TRANSPORT_LE}
1421 * @throws IllegalArgumentException if callback is null
1424 public BluetoothGatt connectGatt(Context context, boolean autoConnect,
1425 BluetoothGattCallback callback, int transport) {
1426 // TODO(Bluetooth) check whether platform support BLE
1427 // Do the check here or in GattServer?
1428 BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
1429 IBluetoothManager managerService = adapter.getBluetoothManager();
1431 IBluetoothGatt iGatt = managerService.getBluetoothGatt();
1432 if (iGatt == null) {
1433 // BLE is not supported
1436 BluetoothGatt gatt = new BluetoothGatt(context, iGatt, this, transport);
1437 gatt.connect(autoConnect, callback);
1439 } catch (RemoteException e) {Log.e(TAG, "", e);}