blob: 0ad46e6f239ec940527ae12931ad8d0f7d53ca32 [file] [log] [blame]
Nick Pellybd022f42009-08-14 18:33:38 -07001/*
Joseph Pirozzocfa8a642016-03-04 13:02:54 -08002 * Copyright (C) 2009-2016 The Android Open Source Project
Casper Bonde238e0f92015-04-09 09:24:48 +02003 * Copyright (C) 2015 Samsung LSI
Nick Pellybd022f42009-08-14 18:33:38 -07004 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18package android.bluetooth;
19
Tor Norbye2d497522015-04-23 17:10:21 -070020import android.Manifest;
21import android.annotation.IntDef;
22import android.annotation.RequiresPermission;
Nick Pellyde893f52009-09-08 13:15:33 -070023import android.annotation.SdkConstant;
24import android.annotation.SdkConstant.SdkConstantType;
Wei Wangd91f1932015-03-19 15:09:56 -070025import android.annotation.SystemApi;
Wei Wang6d811182014-05-22 12:10:25 -070026import android.bluetooth.le.BluetoothLeAdvertiser;
27import android.bluetooth.le.BluetoothLeScanner;
Wei Wangaf74e662014-07-09 14:03:42 -070028import android.bluetooth.le.ScanCallback;
Wei Wangc3059cc2014-07-23 23:34:00 -070029import android.bluetooth.le.ScanFilter;
30import android.bluetooth.le.ScanRecord;
Wei Wang9fb17912014-07-01 15:10:06 -070031import android.bluetooth.le.ScanResult;
Wei Wangaf74e662014-07-09 14:03:42 -070032import android.bluetooth.le.ScanSettings;
Jaikumar Ganesh62c37ef2010-08-24 17:36:13 -070033import android.content.Context;
Adam Lesinski010bf372016-04-11 12:18:18 -070034import android.os.BatteryStats;
Wei Wang46ab7232015-05-07 16:25:33 -070035import android.os.Binder;
Nick Pellyf242b7b2009-10-08 00:12:45 +020036import android.os.IBinder;
Nick Pellyaef439e2009-09-28 12:33:17 -070037import android.os.ParcelUuid;
Nick Pellybd022f42009-08-14 18:33:38 -070038import android.os.RemoteException;
Adam Lesinski010bf372016-04-11 12:18:18 -070039import android.os.ResultReceiver;
Nick Pellyf242b7b2009-10-08 00:12:45 +020040import android.os.ServiceManager;
Adam Lesinski010bf372016-04-11 12:18:18 -070041import android.os.SynchronousResultReceiver;
Ajay Panickerb6e1daf2016-02-29 16:09:14 -080042import android.os.SystemProperties;
Nick Pellybd022f42009-08-14 18:33:38 -070043import android.util.Log;
Jaikumar Ganeshcc5494c2010-09-09 15:37:57 -070044import android.util.Pair;
Wei Wang18c76932013-10-29 21:05:37 -070045
Nick Pellybd022f42009-08-14 18:33:38 -070046import java.io.IOException;
Tor Norbye2d497522015-04-23 17:10:21 -070047import java.lang.annotation.Retention;
48import java.lang.annotation.RetentionPolicy;
fredc903ac6f2012-04-24 03:59:57 -070049import java.util.ArrayList;
Jaikumar Ganeshcc5494c2010-09-09 15:37:57 -070050import java.util.Arrays;
Nick Pellybd022f42009-08-14 18:33:38 -070051import java.util.Collections;
Matthew Xiecdd94e32013-04-11 16:36:26 -070052import java.util.HashMap;
Wei Wang18c76932013-10-29 21:05:37 -070053import java.util.HashSet;
Wei Wang9fb17912014-07-01 15:10:06 -070054import java.util.List;
Jeff Sharkeyfea17de2013-06-11 14:13:09 -070055import java.util.Locale;
Matthew Xiecdd94e32013-04-11 16:36:26 -070056import java.util.Map;
Nick Pelly24bb9b82009-10-02 20:34:18 -070057import java.util.Set;
Nick Pelly16fb88a2009-10-07 07:44:03 +020058import java.util.UUID;
Adam Lesinski010bf372016-04-11 12:18:18 -070059import java.util.concurrent.TimeoutException;
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -070060import java.util.concurrent.locks.ReentrantReadWriteLock;
Nick Pellybd022f42009-08-14 18:33:38 -070061
62/**
Scott Main9fab0ae2009-11-03 18:17:59 -080063 * Represents the local device Bluetooth adapter. The {@link BluetoothAdapter}
64 * lets you perform fundamental Bluetooth tasks, such as initiate
65 * device discovery, query a list of bonded (paired) devices,
66 * instantiate a {@link BluetoothDevice} using a known MAC address, and create
67 * a {@link BluetoothServerSocket} to listen for connection requests from other
Matthew Xieb30f91e2013-05-29 10:19:06 -070068 * devices, and start a scan for Bluetooth LE devices.
Scott Main9fab0ae2009-11-03 18:17:59 -080069 *
70 * <p>To get a {@link BluetoothAdapter} representing the local Bluetooth
Kim Schulz0d376052013-08-22 11:18:02 +020071 * adapter, when running on JELLY_BEAN_MR1 and below, call the
Matthew Xieb30f91e2013-05-29 10:19:06 -070072 * static {@link #getDefaultAdapter} method; when running on JELLY_BEAN_MR2 and
Florian Salbrechter05416af2015-07-31 14:43:15 +010073 * higher, call {@link BluetoothManager#getAdapter}.
Scott Main9fab0ae2009-11-03 18:17:59 -080074 * Fundamentally, this is your starting point for all
75 * Bluetooth actions. Once you have the local adapter, you can get a set of
76 * {@link BluetoothDevice} objects representing all paired devices with
77 * {@link #getBondedDevices()}; start device discovery with
78 * {@link #startDiscovery()}; or create a {@link BluetoothServerSocket} to
79 * listen for incoming connection requests with
Matthew Xieb30f91e2013-05-29 10:19:06 -070080 * {@link #listenUsingRfcommWithServiceRecord(String,UUID)}; or start a scan for
81 * Bluetooth LE devices with {@link #startLeScan(LeScanCallback callback)}.
Scott Main9fab0ae2009-11-03 18:17:59 -080082 *
Neil Fullerbf0dc0f2015-11-24 18:19:06 +000083 * <p>This class is thread safe.
84 *
Scott Main9fab0ae2009-11-03 18:17:59 -080085 * <p class="note"><strong>Note:</strong>
86 * Most methods require the {@link android.Manifest.permission#BLUETOOTH}
87 * permission and some also require the
88 * {@link android.Manifest.permission#BLUETOOTH_ADMIN} permission.
89 *
Joe Fernandez3aef8e1d2011-12-20 10:38:34 -080090 * <div class="special reference">
91 * <h3>Developer Guides</h3>
Hemal Patel65813df2016-08-17 13:18:14 -070092 * <p>
93 * For more information about using Bluetooth, read the <a href=
94 * "{@docRoot}guide/topics/connectivity/bluetooth.html">Bluetooth</a> developer
95 * guide.
96 * </p>
Joe Fernandez3aef8e1d2011-12-20 10:38:34 -080097 * </div>
98 *
Scott Main9fab0ae2009-11-03 18:17:59 -080099 * {@see BluetoothDevice}
100 * {@see BluetoothServerSocket}
Nick Pellybd022f42009-08-14 18:33:38 -0700101 */
102public final class BluetoothAdapter {
103 private static final String TAG = "BluetoothAdapter";
fredc0f420372012-04-12 00:02:00 -0700104 private static final boolean DBG = true;
Matthew Xie3b6214f2012-08-29 00:12:29 -0700105 private static final boolean VDBG = false;
Nick Pellybd022f42009-08-14 18:33:38 -0700106
Nick Pellyde893f52009-09-08 13:15:33 -0700107 /**
Svet Ganov408abf72015-05-12 19:13:36 -0700108 * Default MAC address reported to a client that does not have the
109 * android.permission.LOCAL_MAC_ADDRESS permission.
110 *
111 * @hide
112 */
113 public static final String DEFAULT_MAC_ADDRESS = "02:00:00:00:00:00";
114
115 /**
Nick Pellyb24e11b2009-09-08 17:40:43 -0700116 * Sentinel error value for this class. Guaranteed to not equal any other
117 * integer constant in this class. Provided as a convenience for functions
118 * that require a sentinel error value, for example:
119 * <p><code>Intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
120 * BluetoothAdapter.ERROR)</code>
121 */
Nick Pelly005b2282009-09-10 10:21:56 -0700122 public static final int ERROR = Integer.MIN_VALUE;
Nick Pellyb24e11b2009-09-08 17:40:43 -0700123
124 /**
Nick Pellyde893f52009-09-08 13:15:33 -0700125 * Broadcast Action: The state of the local Bluetooth adapter has been
126 * changed.
127 * <p>For example, Bluetooth has been turned on or off.
Nick Pelly005b2282009-09-10 10:21:56 -0700128 * <p>Always contains the extra fields {@link #EXTRA_STATE} and {@link
Nick Pellyde893f52009-09-08 13:15:33 -0700129 * #EXTRA_PREVIOUS_STATE} containing the new and old states
130 * respectively.
131 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} to receive.
132 */
133 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
134 public static final String ACTION_STATE_CHANGED =
Nick Pelly005b2282009-09-10 10:21:56 -0700135 "android.bluetooth.adapter.action.STATE_CHANGED";
Nick Pellybd022f42009-08-14 18:33:38 -0700136
Nick Pellyde893f52009-09-08 13:15:33 -0700137 /**
138 * Used as an int extra field in {@link #ACTION_STATE_CHANGED}
139 * intents to request the current power state. Possible values are:
140 * {@link #STATE_OFF},
141 * {@link #STATE_TURNING_ON},
142 * {@link #STATE_ON},
143 * {@link #STATE_TURNING_OFF},
144 */
145 public static final String EXTRA_STATE =
Nick Pelly005b2282009-09-10 10:21:56 -0700146 "android.bluetooth.adapter.extra.STATE";
Nick Pellyde893f52009-09-08 13:15:33 -0700147 /**
148 * Used as an int extra field in {@link #ACTION_STATE_CHANGED}
149 * intents to request the previous power state. Possible values are:
150 * {@link #STATE_OFF},
151 * {@link #STATE_TURNING_ON},
152 * {@link #STATE_ON},
Etan Cohenfd840dd2015-04-23 18:25:08 -0700153 * {@link #STATE_TURNING_OFF}
Nick Pellyde893f52009-09-08 13:15:33 -0700154 */
155 public static final String EXTRA_PREVIOUS_STATE =
Nick Pelly005b2282009-09-10 10:21:56 -0700156 "android.bluetooth.adapter.extra.PREVIOUS_STATE";
Nick Pellybd022f42009-08-14 18:33:38 -0700157
Tor Norbye2d497522015-04-23 17:10:21 -0700158 /** @hide */
159 @IntDef({STATE_OFF, STATE_TURNING_ON, STATE_ON, STATE_TURNING_OFF, STATE_BLE_TURNING_ON,
160 STATE_BLE_ON, STATE_BLE_TURNING_OFF})
161 @Retention(RetentionPolicy.SOURCE)
162 public @interface AdapterState {}
163
Nick Pellyde893f52009-09-08 13:15:33 -0700164 /**
165 * Indicates the local Bluetooth adapter is off.
166 */
Nick Pelly005b2282009-09-10 10:21:56 -0700167 public static final int STATE_OFF = 10;
Nick Pellyde893f52009-09-08 13:15:33 -0700168 /**
169 * Indicates the local Bluetooth adapter is turning on. However local
170 * clients should wait for {@link #STATE_ON} before attempting to
171 * use the adapter.
172 */
Nick Pelly005b2282009-09-10 10:21:56 -0700173 public static final int STATE_TURNING_ON = 11;
Nick Pellyde893f52009-09-08 13:15:33 -0700174 /**
175 * Indicates the local Bluetooth adapter is on, and ready for use.
176 */
Nick Pelly005b2282009-09-10 10:21:56 -0700177 public static final int STATE_ON = 12;
Nick Pellyde893f52009-09-08 13:15:33 -0700178 /**
179 * Indicates the local Bluetooth adapter is turning off. Local clients
180 * should immediately attempt graceful disconnection of any remote links.
181 */
Nick Pelly005b2282009-09-10 10:21:56 -0700182 public static final int STATE_TURNING_OFF = 13;
Nick Pellyde893f52009-09-08 13:15:33 -0700183
184 /**
Nitin Arorad055adb2015-03-02 15:03:51 -0800185 * Indicates the local Bluetooth adapter is turning Bluetooth LE mode on.
186 * @hide
187 */
188 public static final int STATE_BLE_TURNING_ON = 14;
189
190 /**
191 * Indicates the local Bluetooth adapter is in LE only mode.
192 * @hide
193 */
194 public static final int STATE_BLE_ON = 15;
195
196 /**
197 * Indicates the local Bluetooth adapter is turning off LE only mode.
198 * @hide
199 */
200 public static final int STATE_BLE_TURNING_OFF = 16;
201
202 /**
Nick Pelly18b1e792009-09-24 11:14:15 -0700203 * Activity Action: Show a system activity that requests discoverable mode.
Scott Main6d95fc02009-11-19 17:00:19 -0800204 * This activity will also request the user to turn on Bluetooth if it
Nick Pelly1acdcc12009-09-28 10:33:55 -0700205 * is not currently enabled.
Nick Pelly18b1e792009-09-24 11:14:15 -0700206 * <p>Discoverable mode is equivalent to {@link
207 * #SCAN_MODE_CONNECTABLE_DISCOVERABLE}. It allows remote devices to see
208 * this Bluetooth adapter when they perform a discovery.
Scott Main6d95fc02009-11-19 17:00:19 -0800209 * <p>For privacy, Android is not discoverable by default.
210 * <p>The sender of this Intent can optionally use extra field {@link
Nick Pelly18b1e792009-09-24 11:14:15 -0700211 * #EXTRA_DISCOVERABLE_DURATION} to request the duration of
212 * discoverability. Currently the default duration is 120 seconds, and
213 * maximum duration is capped at 300 seconds for each request.
214 * <p>Notification of the result of this activity is posted using the
215 * {@link android.app.Activity#onActivityResult} callback. The
216 * <code>resultCode</code>
Michael Chancdd28642009-11-05 18:29:01 -0800217 * will be the duration (in seconds) of discoverability or
218 * {@link android.app.Activity#RESULT_CANCELED} if the user rejected
219 * discoverability or an error has occurred.
Nick Pelly18b1e792009-09-24 11:14:15 -0700220 * <p>Applications can also listen for {@link #ACTION_SCAN_MODE_CHANGED}
Scott Main6d95fc02009-11-19 17:00:19 -0800221 * for global notification whenever the scan mode changes. For example, an
222 * application can be notified when the device has ended discoverability.
Nick Pelly1acdcc12009-09-28 10:33:55 -0700223 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
Nick Pelly18b1e792009-09-24 11:14:15 -0700224 */
225 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
226 public static final String ACTION_REQUEST_DISCOVERABLE =
227 "android.bluetooth.adapter.action.REQUEST_DISCOVERABLE";
228
229 /**
230 * Used as an optional int extra field in {@link
231 * #ACTION_REQUEST_DISCOVERABLE} intents to request a specific duration
232 * for discoverability in seconds. The current default is 120 seconds, and
233 * requests over 300 seconds will be capped. These values could change.
234 */
235 public static final String EXTRA_DISCOVERABLE_DURATION =
236 "android.bluetooth.adapter.extra.DISCOVERABLE_DURATION";
237
238 /**
Nick Pelly1acdcc12009-09-28 10:33:55 -0700239 * Activity Action: Show a system activity that allows the user to turn on
240 * Bluetooth.
241 * <p>This system activity will return once Bluetooth has completed turning
242 * on, or the user has decided not to turn Bluetooth on.
243 * <p>Notification of the result of this activity is posted using the
244 * {@link android.app.Activity#onActivityResult} callback. The
245 * <code>resultCode</code>
Michael Chancdd28642009-11-05 18:29:01 -0800246 * will be {@link android.app.Activity#RESULT_OK} if Bluetooth has been
247 * turned on or {@link android.app.Activity#RESULT_CANCELED} if the user
248 * has rejected the request or an error has occurred.
Nick Pelly1acdcc12009-09-28 10:33:55 -0700249 * <p>Applications can also listen for {@link #ACTION_STATE_CHANGED}
250 * for global notification whenever Bluetooth is turned on or off.
251 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
252 */
253 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
254 public static final String ACTION_REQUEST_ENABLE =
255 "android.bluetooth.adapter.action.REQUEST_ENABLE";
256
257 /**
Wei Wangd91f1932015-03-19 15:09:56 -0700258 * Activity Action: Show a system activity that allows user to enable BLE scans even when
259 * Bluetooth is turned off.<p>
260 *
261 * Notification of result of this activity is posted using
262 * {@link android.app.Activity#onActivityResult}. The <code>resultCode</code> will be
263 * {@link android.app.Activity#RESULT_OK} if BLE scan always available setting is turned on or
264 * {@link android.app.Activity#RESULT_CANCELED} if the user has rejected the request or an
265 * error occurred.
266 *
267 * @hide
268 */
269 @SystemApi
270 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
271 public static final String ACTION_REQUEST_BLE_SCAN_ALWAYS_AVAILABLE =
272 "android.bluetooth.adapter.action.REQUEST_BLE_SCAN_ALWAYS_AVAILABLE";
273
274 /**
Nick Pellyde893f52009-09-08 13:15:33 -0700275 * Broadcast Action: Indicates the Bluetooth scan mode of the local Adapter
276 * has changed.
Nick Pelly005b2282009-09-10 10:21:56 -0700277 * <p>Always contains the extra fields {@link #EXTRA_SCAN_MODE} and {@link
Nick Pellyde893f52009-09-08 13:15:33 -0700278 * #EXTRA_PREVIOUS_SCAN_MODE} containing the new and old scan modes
279 * respectively.
280 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
281 */
282 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
283 public static final String ACTION_SCAN_MODE_CHANGED =
Nick Pelly005b2282009-09-10 10:21:56 -0700284 "android.bluetooth.adapter.action.SCAN_MODE_CHANGED";
Nick Pellyde893f52009-09-08 13:15:33 -0700285
286 /**
287 * Used as an int extra field in {@link #ACTION_SCAN_MODE_CHANGED}
288 * intents to request the current scan mode. Possible values are:
289 * {@link #SCAN_MODE_NONE},
290 * {@link #SCAN_MODE_CONNECTABLE},
291 * {@link #SCAN_MODE_CONNECTABLE_DISCOVERABLE},
292 */
Nick Pelly005b2282009-09-10 10:21:56 -0700293 public static final String EXTRA_SCAN_MODE = "android.bluetooth.adapter.extra.SCAN_MODE";
Nick Pellyde893f52009-09-08 13:15:33 -0700294 /**
295 * Used as an int extra field in {@link #ACTION_SCAN_MODE_CHANGED}
296 * intents to request the previous scan mode. Possible values are:
297 * {@link #SCAN_MODE_NONE},
298 * {@link #SCAN_MODE_CONNECTABLE},
299 * {@link #SCAN_MODE_CONNECTABLE_DISCOVERABLE},
300 */
301 public static final String EXTRA_PREVIOUS_SCAN_MODE =
Nick Pelly005b2282009-09-10 10:21:56 -0700302 "android.bluetooth.adapter.extra.PREVIOUS_SCAN_MODE";
Nick Pellyde893f52009-09-08 13:15:33 -0700303
Tor Norbye2d497522015-04-23 17:10:21 -0700304 /** @hide */
305 @IntDef({SCAN_MODE_NONE, SCAN_MODE_CONNECTABLE, SCAN_MODE_CONNECTABLE_DISCOVERABLE})
306 @Retention(RetentionPolicy.SOURCE)
307 public @interface ScanMode {}
308
Nick Pellyde893f52009-09-08 13:15:33 -0700309 /**
310 * Indicates that both inquiry scan and page scan are disabled on the local
311 * Bluetooth adapter. Therefore this device is neither discoverable
312 * nor connectable from remote Bluetooth devices.
313 */
Nick Pelly005b2282009-09-10 10:21:56 -0700314 public static final int SCAN_MODE_NONE = 20;
Nick Pellyde893f52009-09-08 13:15:33 -0700315 /**
316 * Indicates that inquiry scan is disabled, but page scan is enabled on the
317 * local Bluetooth adapter. Therefore this device is not discoverable from
318 * remote Bluetooth devices, but is connectable from remote devices that
319 * have previously discovered this device.
320 */
Nick Pelly005b2282009-09-10 10:21:56 -0700321 public static final int SCAN_MODE_CONNECTABLE = 21;
Nick Pellyde893f52009-09-08 13:15:33 -0700322 /**
323 * Indicates that both inquiry scan and page scan are enabled on the local
324 * Bluetooth adapter. Therefore this device is both discoverable and
325 * connectable from remote Bluetooth devices.
326 */
Nick Pelly005b2282009-09-10 10:21:56 -0700327 public static final int SCAN_MODE_CONNECTABLE_DISCOVERABLE = 23;
Nick Pellybd022f42009-08-14 18:33:38 -0700328
Nick Pelly005b2282009-09-10 10:21:56 -0700329 /**
330 * Broadcast Action: The local Bluetooth adapter has started the remote
331 * device discovery process.
332 * <p>This usually involves an inquiry scan of about 12 seconds, followed
333 * by a page scan of each new device to retrieve its Bluetooth name.
334 * <p>Register for {@link BluetoothDevice#ACTION_FOUND} to be notified as
335 * remote Bluetooth devices are found.
336 * <p>Device discovery is a heavyweight procedure. New connections to
337 * remote Bluetooth devices should not be attempted while discovery is in
338 * progress, and existing connections will experience limited bandwidth
339 * and high latency. Use {@link #cancelDiscovery()} to cancel an ongoing
340 * discovery.
341 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} to receive.
342 */
343 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
344 public static final String ACTION_DISCOVERY_STARTED =
345 "android.bluetooth.adapter.action.DISCOVERY_STARTED";
346 /**
347 * Broadcast Action: The local Bluetooth adapter has finished the device
348 * discovery process.
349 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} to receive.
350 */
351 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
352 public static final String ACTION_DISCOVERY_FINISHED =
353 "android.bluetooth.adapter.action.DISCOVERY_FINISHED";
354
355 /**
356 * Broadcast Action: The local Bluetooth adapter has changed its friendly
357 * Bluetooth name.
358 * <p>This name is visible to remote Bluetooth devices.
359 * <p>Always contains the extra field {@link #EXTRA_LOCAL_NAME} containing
360 * the name.
361 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} to receive.
362 */
363 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
364 public static final String ACTION_LOCAL_NAME_CHANGED =
365 "android.bluetooth.adapter.action.LOCAL_NAME_CHANGED";
366 /**
367 * Used as a String extra field in {@link #ACTION_LOCAL_NAME_CHANGED}
368 * intents to request the local Bluetooth name.
369 */
370 public static final String EXTRA_LOCAL_NAME = "android.bluetooth.adapter.extra.LOCAL_NAME";
371
Jaikumar Ganesh62c37ef2010-08-24 17:36:13 -0700372 /**
373 * Intent used to broadcast the change in connection state of the local
374 * Bluetooth adapter to a profile of the remote device. When the adapter is
375 * not connected to any profiles of any remote devices and it attempts a
376 * connection to a profile this intent will sent. Once connected, this intent
377 * will not be sent for any more connection attempts to any profiles of any
378 * remote device. When the adapter disconnects from the last profile its
379 * connected to of any remote device, this intent will be sent.
380 *
381 * <p> This intent is useful for applications that are only concerned about
382 * whether the local adapter is connected to any profile of any device and
383 * are not really concerned about which profile. For example, an application
384 * which displays an icon to display whether Bluetooth is connected or not
385 * can use this intent.
386 *
387 * <p>This intent will have 3 extras:
Jaikumar Ganesh0b5b35f2011-02-01 16:47:11 -0800388 * {@link #EXTRA_CONNECTION_STATE} - The current connection state.
389 * {@link #EXTRA_PREVIOUS_CONNECTION_STATE}- The previous connection state.
Jaikumar Ganesh62c37ef2010-08-24 17:36:13 -0700390 * {@link BluetoothDevice#EXTRA_DEVICE} - The remote device.
391 *
Jaikumar Ganesh0b5b35f2011-02-01 16:47:11 -0800392 * {@link #EXTRA_CONNECTION_STATE} or {@link #EXTRA_PREVIOUS_CONNECTION_STATE}
393 * can be any of {@link #STATE_DISCONNECTED}, {@link #STATE_CONNECTING},
Jaikumar Ganesh62c37ef2010-08-24 17:36:13 -0700394 * {@link #STATE_CONNECTED}, {@link #STATE_DISCONNECTING}.
395 *
396 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} to receive.
397 */
398 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
399 public static final String ACTION_CONNECTION_STATE_CHANGED =
400 "android.bluetooth.adapter.action.CONNECTION_STATE_CHANGED";
401
402 /**
403 * Extra used by {@link #ACTION_CONNECTION_STATE_CHANGED}
404 *
405 * This extra represents the current connection state.
406 */
407 public static final String EXTRA_CONNECTION_STATE =
408 "android.bluetooth.adapter.extra.CONNECTION_STATE";
409
410 /**
411 * Extra used by {@link #ACTION_CONNECTION_STATE_CHANGED}
412 *
413 * This extra represents the previous connection state.
414 */
415 public static final String EXTRA_PREVIOUS_CONNECTION_STATE =
416 "android.bluetooth.adapter.extra.PREVIOUS_CONNECTION_STATE";
417
Nitin Arorad055adb2015-03-02 15:03:51 -0800418 /**
419 * Broadcast Action: The Bluetooth adapter state has changed in LE only mode.
420 * @hide
421 */
Wei Wangf9e3e9e2015-06-01 12:14:28 -0700422 @SystemApi
Nitin Arorad055adb2015-03-02 15:03:51 -0800423 public static final String ACTION_BLE_STATE_CHANGED =
tturney1b43e432015-04-29 12:01:00 -0700424 "android.bluetooth.adapter.action.BLE_STATE_CHANGED";
Nitin Arorad055adb2015-03-02 15:03:51 -0800425
426 /**
427 * Broadcast Action: The notifys Bluetooth ACL connected event. This will be
428 * by BLE Always on enabled application to know the ACL_CONNECTED event
429 * when Bluetooth state in STATE_BLE_ON. This denotes GATT connection
430 * as Bluetooth LE is the only feature available in STATE_BLE_ON
431 *
432 * This is counterpart of {@link BluetoothDevice#ACTION_ACL_CONNECTED} which
433 * works in Bluetooth state STATE_ON
434 * @hide
435 */
436 public static final String ACTION_BLE_ACL_CONNECTED =
437 "android.bluetooth.adapter.action.BLE_ACL_CONNECTED";
438
439 /**
440 * Broadcast Action: The notifys Bluetooth ACL connected event. This will be
441 * by BLE Always on enabled application to know the ACL_DISCONNECTED event
442 * when Bluetooth state in STATE_BLE_ON. This denotes GATT disconnection as Bluetooth
443 * LE is the only feature available in STATE_BLE_ON
444 *
445 * This is counterpart of {@link BluetoothDevice#ACTION_ACL_DISCONNECTED} which
446 * works in Bluetooth state STATE_ON
447 * @hide
448 */
449 public static final String ACTION_BLE_ACL_DISCONNECTED =
450 "android.bluetooth.adapter.action.BLE_ACL_DISCONNECTED";
451
Jaikumar Ganesh62c37ef2010-08-24 17:36:13 -0700452 /** The profile is in disconnected state */
453 public static final int STATE_DISCONNECTED = 0;
454 /** The profile is in connecting state */
455 public static final int STATE_CONNECTING = 1;
456 /** The profile is in connected state */
457 public static final int STATE_CONNECTED = 2;
458 /** The profile is in disconnecting state */
459 public static final int STATE_DISCONNECTING = 3;
460
Nick Pellyf242b7b2009-10-08 00:12:45 +0200461 /** @hide */
fredc0f420372012-04-12 00:02:00 -0700462 public static final String BLUETOOTH_MANAGER_SERVICE = "bluetooth_manager";
Nitin Arorad055adb2015-03-02 15:03:51 -0800463 private final IBinder mToken;
Nick Pellyf242b7b2009-10-08 00:12:45 +0200464
Casper Bonde238e0f92015-04-09 09:24:48 +0200465
466 /** When creating a ServerSocket using listenUsingRfcommOn() or
467 * listenUsingL2capOn() use SOCKET_CHANNEL_AUTO_STATIC to create
468 * a ServerSocket that auto assigns a channel number to the first
469 * bluetooth socket.
470 * The channel number assigned to this first Bluetooth Socket will
471 * be stored in the ServerSocket, and reused for subsequent Bluetooth
472 * sockets.
473 * @hide */
474 public static final int SOCKET_CHANNEL_AUTO_STATIC_NO_SDP = -2;
475
476
Nick Pelly005b2282009-09-10 10:21:56 -0700477 private static final int ADDRESS_LENGTH = 17;
Nick Pellybd022f42009-08-14 18:33:38 -0700478
Nick Pellyf242b7b2009-10-08 00:12:45 +0200479 /**
Jake Hambyf51eada2010-09-21 13:39:53 -0700480 * Lazily initialized singleton. Guaranteed final after first object
Nick Pellyf242b7b2009-10-08 00:12:45 +0200481 * constructed.
482 */
483 private static BluetoothAdapter sAdapter;
484
Wei Wangc3059cc2014-07-23 23:34:00 -0700485 private static BluetoothLeScanner sBluetoothLeScanner;
486 private static BluetoothLeAdvertiser sBluetoothLeAdvertiser;
487
fredc0f420372012-04-12 00:02:00 -0700488 private final IBluetoothManager mManagerService;
489 private IBluetooth mService;
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700490 private final ReentrantReadWriteLock mServiceLock =
491 new ReentrantReadWriteLock();
Nick Pellybd022f42009-08-14 18:33:38 -0700492
Wei Wangf3055892014-03-11 22:22:41 -0700493 private final Object mLock = new Object();
Wei Wangc3059cc2014-07-23 23:34:00 -0700494 private final Map<LeScanCallback, ScanCallback> mLeScanClients;
Matthew Xie484867a2011-08-25 16:45:58 -0700495
Nick Pellybd022f42009-08-14 18:33:38 -0700496 /**
Nick Pellyf242b7b2009-10-08 00:12:45 +0200497 * Get a handle to the default local Bluetooth adapter.
498 * <p>Currently Android only supports one Bluetooth adapter, but the API
499 * could be extended to support more. This will always return the default
500 * adapter.
501 * @return the default local adapter, or null if Bluetooth is not supported
502 * on this hardware platform
503 */
504 public static synchronized BluetoothAdapter getDefaultAdapter() {
505 if (sAdapter == null) {
fredc0f420372012-04-12 00:02:00 -0700506 IBinder b = ServiceManager.getService(BLUETOOTH_MANAGER_SERVICE);
Nick Pellyf242b7b2009-10-08 00:12:45 +0200507 if (b != null) {
fredc0f420372012-04-12 00:02:00 -0700508 IBluetoothManager managerService = IBluetoothManager.Stub.asInterface(b);
509 sAdapter = new BluetoothAdapter(managerService);
Jaikumar Ganeshe4caddb2012-01-25 16:16:48 -0800510 } else {
511 Log.e(TAG, "Bluetooth binder is null");
Nick Pellyf242b7b2009-10-08 00:12:45 +0200512 }
513 }
514 return sAdapter;
515 }
516
517 /**
518 * Use {@link #getDefaultAdapter} to get the BluetoothAdapter instance.
Nick Pellybd022f42009-08-14 18:33:38 -0700519 */
fredc0f420372012-04-12 00:02:00 -0700520 BluetoothAdapter(IBluetoothManager managerService) {
521
522 if (managerService == null) {
523 throw new IllegalArgumentException("bluetooth manager service is null");
Nick Pellybd022f42009-08-14 18:33:38 -0700524 }
fredc0f420372012-04-12 00:02:00 -0700525 try {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700526 mServiceLock.writeLock().lock();
fredc0f420372012-04-12 00:02:00 -0700527 mService = managerService.registerAdapter(mManagerCallback);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700528 } catch (RemoteException e) {
529 Log.e(TAG, "", e);
530 } finally {
531 mServiceLock.writeLock().unlock();
532 }
fredc0f420372012-04-12 00:02:00 -0700533 mManagerService = managerService;
Wei Wangc3059cc2014-07-23 23:34:00 -0700534 mLeScanClients = new HashMap<LeScanCallback, ScanCallback>();
Nitin Arorad055adb2015-03-02 15:03:51 -0800535 mToken = new Binder();
Nick Pellybd022f42009-08-14 18:33:38 -0700536 }
537
538 /**
Nick Pelly45e27042009-08-19 11:00:00 -0700539 * Get a {@link BluetoothDevice} object for the given Bluetooth hardware
540 * address.
541 * <p>Valid Bluetooth hardware addresses must be upper case, in a format
Nick Pelly005b2282009-09-10 10:21:56 -0700542 * such as "00:11:22:33:AA:BB". The helper {@link #checkBluetoothAddress} is
543 * available to validate a Bluetooth address.
Nick Pelly45e27042009-08-19 11:00:00 -0700544 * <p>A {@link BluetoothDevice} will always be returned for a valid
545 * hardware address, even if this adapter has never seen that device.
Nick Pellyde893f52009-09-08 13:15:33 -0700546 *
Nick Pellybd022f42009-08-14 18:33:38 -0700547 * @param address valid Bluetooth MAC address
Nick Pelly45e27042009-08-19 11:00:00 -0700548 * @throws IllegalArgumentException if address is invalid
Nick Pellybd022f42009-08-14 18:33:38 -0700549 */
550 public BluetoothDevice getRemoteDevice(String address) {
551 return new BluetoothDevice(address);
552 }
553
554 /**
Nick Pelly75596b42011-12-07 15:03:55 -0800555 * Get a {@link BluetoothDevice} object for the given Bluetooth hardware
556 * address.
557 * <p>Valid Bluetooth hardware addresses must be 6 bytes. This method
558 * expects the address in network byte order (MSB first).
559 * <p>A {@link BluetoothDevice} will always be returned for a valid
560 * hardware address, even if this adapter has never seen that device.
561 *
562 * @param address Bluetooth MAC address (6 bytes)
563 * @throws IllegalArgumentException if address is invalid
564 */
565 public BluetoothDevice getRemoteDevice(byte[] address) {
566 if (address == null || address.length != 6) {
567 throw new IllegalArgumentException("Bluetooth address must have 6 bytes");
568 }
Jeff Sharkeyfea17de2013-06-11 14:13:09 -0700569 return new BluetoothDevice(String.format(Locale.US, "%02X:%02X:%02X:%02X:%02X:%02X",
Nick Pelly75596b42011-12-07 15:03:55 -0800570 address[0], address[1], address[2], address[3], address[4], address[5]));
571 }
572
573 /**
Prerepa Viswanadham248edc32014-10-15 16:36:01 -0700574 * Returns a {@link BluetoothLeAdvertiser} object for Bluetooth LE Advertising operations.
575 * Will return null if Bluetooth is turned off or if Bluetooth LE Advertising is not
576 * supported on this device.
Wei Wangc3059cc2014-07-23 23:34:00 -0700577 * <p>
578 * Use {@link #isMultipleAdvertisementSupported()} to check whether LE Advertising is supported
579 * on this device before calling this method.
Wei Wangadf6aff2014-05-20 06:30:20 +0000580 */
581 public BluetoothLeAdvertiser getBluetoothLeAdvertiser() {
Nitin Arorad055adb2015-03-02 15:03:51 -0800582 if (!getLeAccess()) return null;
Wei Wangc3059cc2014-07-23 23:34:00 -0700583 synchronized(mLock) {
584 if (sBluetoothLeAdvertiser == null) {
585 sBluetoothLeAdvertiser = new BluetoothLeAdvertiser(mManagerService);
586 }
587 }
588 return sBluetoothLeAdvertiser;
Wei Wangadf6aff2014-05-20 06:30:20 +0000589 }
590
591 /**
592 * Returns a {@link BluetoothLeScanner} object for Bluetooth LE scan operations.
593 */
594 public BluetoothLeScanner getBluetoothLeScanner() {
Nitin Arorad055adb2015-03-02 15:03:51 -0800595 if (!getLeAccess()) return null;
Wei Wangc3059cc2014-07-23 23:34:00 -0700596 synchronized(mLock) {
597 if (sBluetoothLeScanner == null) {
598 sBluetoothLeScanner = new BluetoothLeScanner(mManagerService);
599 }
600 }
601 return sBluetoothLeScanner;
Wei Wangadf6aff2014-05-20 06:30:20 +0000602 }
603
604 /**
Nick Pellyde893f52009-09-08 13:15:33 -0700605 * Return true if Bluetooth is currently enabled and ready for use.
606 * <p>Equivalent to:
607 * <code>getBluetoothState() == STATE_ON</code>
608 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
Nick Pellybd022f42009-08-14 18:33:38 -0700609 *
Nick Pellyde893f52009-09-08 13:15:33 -0700610 * @return true if the local adapter is turned on
Nick Pellybd022f42009-08-14 18:33:38 -0700611 */
Tor Norbye2d497522015-04-23 17:10:21 -0700612 @RequiresPermission(Manifest.permission.BLUETOOTH)
Nick Pellybd022f42009-08-14 18:33:38 -0700613 public boolean isEnabled() {
614 try {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700615 mServiceLock.readLock().lock();
616 if (mService != null) return mService.isEnabled();
617 } catch (RemoteException e) {
618 Log.e(TAG, "", e);
619 } finally {
620 mServiceLock.readLock().unlock();
621 }
622
Nick Pellybd022f42009-08-14 18:33:38 -0700623 return false;
624 }
625
626 /**
Nitin Arorad055adb2015-03-02 15:03:51 -0800627 * Return true if Bluetooth LE(Always BLE On feature) is currently
628 * enabled and ready for use
629 * <p>This returns true if current state is either STATE_ON or STATE_BLE_ON
630 *
631 * @return true if the local Bluetooth LE adapter is turned on
632 * @hide
633 */
Wei Wangf9e3e9e2015-06-01 12:14:28 -0700634 @SystemApi
635 public boolean isLeEnabled() {
636 final int state = getLeState();
637 if (state == BluetoothAdapter.STATE_ON) {
638 if (DBG) Log.d (TAG, "STATE_ON");
639 } else if (state == BluetoothAdapter.STATE_BLE_ON) {
640 if (DBG) Log.d (TAG, "STATE_BLE_ON");
641 } else {
642 if (DBG) Log.d (TAG, "STATE_OFF");
643 return false;
644 }
645 return true;
Nitin Arorad055adb2015-03-02 15:03:51 -0800646 }
647
648 /**
649 * Performs action based on user action to turn BT ON
650 * or OFF if BT is in BLE_ON state
651 */
652 private void notifyUserAction(boolean enable) {
Nitin Arorad055adb2015-03-02 15:03:51 -0800653 try {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700654 mServiceLock.readLock().lock();
655 if (mService == null) {
656 Log.e(TAG, "mService is null");
657 return;
658 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800659 if (enable) {
660 mService.onLeServiceUp(); //NA:TODO implementation pending
661 } else {
662 mService.onBrEdrDown(); //NA:TODO implementation pending
663 }
664 } catch (RemoteException e) {
665 Log.e(TAG, "", e);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700666 } finally {
667 mServiceLock.readLock().unlock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800668 }
669 }
670
671 /**
Nitin Arorad055adb2015-03-02 15:03:51 -0800672 * Turns off Bluetooth LE which was earlier turned on by calling EnableBLE().
673 *
674 * <p> If the internal Adapter state is STATE_BLE_ON, this would trigger the transition
675 * to STATE_OFF and completely shut-down Bluetooth
676 *
677 * <p> If the Adapter state is STATE_ON, This would unregister the existance of
678 * special Bluetooth LE application and hence the further turning off of Bluetooth
679 * from UI would ensure the complete turn-off of Bluetooth rather than staying back
680 * BLE only state
681 *
682 * <p>This is an asynchronous call: it will return immediately, and
683 * clients should listen for {@link #ACTION_BLE_STATE_CHANGED}
684 * to be notified of subsequent adapter state changes If this call returns
685 * true, then the adapter state will immediately transition from {@link
686 * #STATE_ON} to {@link #STATE_TURNING_OFF}, and some time
687 * later transition to either {@link #STATE_BLE_ON} or {@link
688 * #STATE_OFF} based on the existance of the further Always BLE ON enabled applications
689 * If this call returns false then there was an
690 * immediate problem that will prevent the QAdapter from being turned off -
691 * such as the QAadapter already being turned off.
692 *
693 * @return true to indicate success, or false on
694 * immediate error
695 * @hide
696 */
Wei Wangf9e3e9e2015-06-01 12:14:28 -0700697 @SystemApi
Nitin Arorad055adb2015-03-02 15:03:51 -0800698 public boolean disableBLE() {
Wei Wang67d84162015-04-26 17:04:29 -0700699 if (!isBleScanAlwaysAvailable()) return false;
Nitin Arorad055adb2015-03-02 15:03:51 -0800700
701 int state = getLeState();
702 if (state == BluetoothAdapter.STATE_ON) {
703 if (DBG) Log.d (TAG, "STATE_ON: shouldn't disable");
704 try {
705 mManagerService.updateBleAppCount(mToken, false);
706 } catch (RemoteException e) {
707 Log.e(TAG, "", e);
708 }
709 return true;
710
711 } else if (state == BluetoothAdapter.STATE_BLE_ON) {
712 if (DBG) Log.d (TAG, "STATE_BLE_ON");
713 int bleAppCnt = 0;
714 try {
715 bleAppCnt = mManagerService.updateBleAppCount(mToken, false);
716 } catch (RemoteException e) {
717 Log.e(TAG, "", e);
718 }
719 if (bleAppCnt == 0) {
720 // Disable only if there are no other clients
721 notifyUserAction(false);
722 }
723 return true;
724 }
725
726 if (DBG) Log.d (TAG, "STATE_OFF: Already disabled");
727 return false;
728 }
729
730 /**
731 * Special Applications who want to only turn on Bluetooth Low Energy (BLE) would
732 * EnableBLE, EnableBLE brings-up Bluetooth so that application can access
733 * only LE related feature (Bluetooth GATT layers interfaces using the respective class)
734 * EnableBLE in turn registers the existance of a special App which wants to
735 * turn on Bluetooth Low enrgy part without making it visible at the settings UI
736 * as Bluetooth ON.
737 * <p>Invoking EnableBLE when Bluetooth is already in ON state, would just registers
738 * the existance of special Application and doesn't do anything to current BT state.
739 * when user turn OFF Bluetooth from UI, if there is an existance of special app, Bluetooth
740 * would stay in BLE_ON state so that LE features are still acessible to the special
741 * Applications.
742 *
743 * <p>This is an asynchronous call: it will return immediately, and
744 * clients should listen for {@link #ACTION_BLE_STATE_CHANGED}
745 * to be notified of subsequent adapter state changes. If this call returns
746 * true, then the adapter state will immediately transition from {@link
747 * #STATE_OFF} to {@link #STATE_BLE_TURNING_ON}, and some time
748 * later transition to either {@link #STATE_OFF} or {@link
749 * #STATE_BLE_ON}. If this call returns false then there was an
750 * immediate problem that will prevent the adapter from being turned on -
751 * such as Airplane mode, or the adapter is already turned on.
752 * (@link #ACTION_BLE_STATE_CHANGED) returns the Bluetooth Adapter's various
753 * states, It includes all the classic Bluetooth Adapter states along with
754 * internal BLE only states
755 *
756 * @return true to indicate Bluetooth LE start-up has begun, or false on
757 * immediate error
758 * @hide
759 */
Wei Wangf9e3e9e2015-06-01 12:14:28 -0700760 @SystemApi
Nitin Arorad055adb2015-03-02 15:03:51 -0800761 public boolean enableBLE() {
Wei Wang67d84162015-04-26 17:04:29 -0700762 if (!isBleScanAlwaysAvailable()) return false;
Nitin Arorad055adb2015-03-02 15:03:51 -0800763
Nitin Arorad055adb2015-03-02 15:03:51 -0800764 try {
Nitin Arorad055adb2015-03-02 15:03:51 -0800765 mManagerService.updateBleAppCount(mToken, true);
Marie Janssen6a383a72016-10-25 10:47:51 -0700766 if (isLeEnabled()) {
767 if (DBG) Log.d(TAG, "enableBLE(): Bluetooth already enabled");
768 return true;
769 }
770 if (DBG) Log.d(TAG, "enableBLE(): Calling enable");
Nitin Arorad055adb2015-03-02 15:03:51 -0800771 return mManagerService.enable();
772 } catch (RemoteException e) {
773 Log.e(TAG, "", e);
774 }
775
776 return false;
777 }
778
779 /**
Nick Pellyde893f52009-09-08 13:15:33 -0700780 * Get the current state of the local Bluetooth adapter.
781 * <p>Possible return values are
782 * {@link #STATE_OFF},
783 * {@link #STATE_TURNING_ON},
784 * {@link #STATE_ON},
785 * {@link #STATE_TURNING_OFF}.
786 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
Nick Pellybd022f42009-08-14 18:33:38 -0700787 *
Nick Pellyde893f52009-09-08 13:15:33 -0700788 * @return current state of Bluetooth adapter
Nick Pellybd022f42009-08-14 18:33:38 -0700789 */
Tor Norbye2d497522015-04-23 17:10:21 -0700790 @RequiresPermission(Manifest.permission.BLUETOOTH)
791 @AdapterState
Nick Pellyde893f52009-09-08 13:15:33 -0700792 public int getState() {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700793 int state = BluetoothAdapter.STATE_OFF;
794
Nick Pellybd022f42009-08-14 18:33:38 -0700795 try {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700796 mServiceLock.readLock().lock();
797 if (mService != null) {
798 state = mService.getState();
fredc0f420372012-04-12 00:02:00 -0700799 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700800 } catch (RemoteException e) {
801 Log.e(TAG, "", e);
802 } finally {
803 mServiceLock.readLock().unlock();
804 }
805
806 // Consider all internal states as OFF
807 if (state == BluetoothAdapter.STATE_BLE_ON
808 || state == BluetoothAdapter.STATE_BLE_TURNING_ON
809 || state == BluetoothAdapter.STATE_BLE_TURNING_OFF) {
810 if (VDBG) Log.d(TAG, "Consider internal state as OFF");
811 state = BluetoothAdapter.STATE_OFF;
812 }
813 if (VDBG) Log.d(TAG, "" + hashCode() + ": getState(). Returning " + state);
814 return state;
Nick Pellybd022f42009-08-14 18:33:38 -0700815 }
816
817 /**
Nitin Arorad055adb2015-03-02 15:03:51 -0800818 * Get the current state of the local Bluetooth adapter
819 * <p>This returns current internal state of Adapter including LE ON/OFF
820 *
821 * <p>Possible return values are
822 * {@link #STATE_OFF},
823 * {@link #STATE_BLE_TURNING_ON},
824 * {@link #STATE_BLE_ON},
825 * {@link #STATE_TURNING_ON},
826 * {@link #STATE_ON},
827 * {@link #STATE_TURNING_OFF},
828 * {@link #STATE_BLE_TURNING_OFF}.
829 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
830 *
831 * @return current state of Bluetooth adapter
832 * @hide
833 */
Tor Norbye2d497522015-04-23 17:10:21 -0700834 @RequiresPermission(Manifest.permission.BLUETOOTH)
835 @AdapterState
Nitin Arorad055adb2015-03-02 15:03:51 -0800836 public int getLeState() {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700837 int state = BluetoothAdapter.STATE_OFF;
838
Nitin Arorad055adb2015-03-02 15:03:51 -0800839 try {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700840 mServiceLock.readLock().lock();
841 if (mService != null) {
842 state = mService.getState();
Nitin Arorad055adb2015-03-02 15:03:51 -0800843 }
844 } catch (RemoteException e) {
845 Log.e(TAG, "", e);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700846 } finally {
847 mServiceLock.readLock().unlock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800848 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700849
850 if (VDBG) Log.d(TAG,"getLeState() returning " + state);
851 return state;
Nitin Arorad055adb2015-03-02 15:03:51 -0800852 }
853
854 boolean getLeAccess() {
855 if(getLeState() == STATE_ON)
856 return true;
857
858 else if (getLeState() == STATE_BLE_ON)
859 return true; // TODO: FILTER SYSTEM APPS HERE <--
860
861 return false;
862 }
863
864 /**
Scott Mained2a70d2009-12-09 16:07:39 -0800865 * Turn on the local Bluetooth adapter&mdash;do not use without explicit
866 * user action to turn on Bluetooth.
Nick Pellyde893f52009-09-08 13:15:33 -0700867 * <p>This powers on the underlying Bluetooth hardware, and starts all
868 * Bluetooth system services.
Scott Mained2a70d2009-12-09 16:07:39 -0800869 * <p class="caution"><strong>Bluetooth should never be enabled without
870 * direct user consent</strong>. If you want to turn on Bluetooth in order
871 * to create a wireless connection, you should use the {@link
872 * #ACTION_REQUEST_ENABLE} Intent, which will raise a dialog that requests
873 * user permission to turn on Bluetooth. The {@link #enable()} method is
874 * provided only for applications that include a user interface for changing
875 * system settings, such as a "power manager" app.</p>
Brad Fitzpatrick3219ab42009-09-25 16:31:39 +0400876 * <p>This is an asynchronous call: it will return immediately, and
Nick Pellyde893f52009-09-08 13:15:33 -0700877 * clients should listen for {@link #ACTION_STATE_CHANGED}
878 * to be notified of subsequent adapter state changes. If this call returns
879 * true, then the adapter state will immediately transition from {@link
880 * #STATE_OFF} to {@link #STATE_TURNING_ON}, and some time
881 * later transition to either {@link #STATE_OFF} or {@link
882 * #STATE_ON}. If this call returns false then there was an
883 * immediate problem that will prevent the adapter from being turned on -
884 * such as Airplane mode, or the adapter is already turned on.
Scott Mained2a70d2009-12-09 16:07:39 -0800885 * <p>Requires the {@link android.Manifest.permission#BLUETOOTH_ADMIN}
886 * permission
Nick Pellyde893f52009-09-08 13:15:33 -0700887 *
888 * @return true to indicate adapter startup has begun, or false on
889 * immediate error
Nick Pellybd022f42009-08-14 18:33:38 -0700890 */
Tor Norbye2d497522015-04-23 17:10:21 -0700891 @RequiresPermission(Manifest.permission.BLUETOOTH_ADMIN)
Nick Pellybd022f42009-08-14 18:33:38 -0700892 public boolean enable() {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700893 if (isEnabled() == true) {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700894 if (DBG) Log.d(TAG, "enable(): BT is already enabled..!");
895 return true;
896 }
Nick Pellybd022f42009-08-14 18:33:38 -0700897 try {
Kausik Sinnaswamya097f512012-04-16 16:38:27 +0530898 return mManagerService.enable();
Nick Pellybd022f42009-08-14 18:33:38 -0700899 } catch (RemoteException e) {Log.e(TAG, "", e);}
900 return false;
901 }
902
903 /**
Scott Mained2a70d2009-12-09 16:07:39 -0800904 * Turn off the local Bluetooth adapter&mdash;do not use without explicit
905 * user action to turn off Bluetooth.
Nick Pellyde893f52009-09-08 13:15:33 -0700906 * <p>This gracefully shuts down all Bluetooth connections, stops Bluetooth
907 * system services, and powers down the underlying Bluetooth hardware.
Jake Hambyf51eada2010-09-21 13:39:53 -0700908 * <p class="caution"><strong>Bluetooth should never be disabled without
Scott Mained2a70d2009-12-09 16:07:39 -0800909 * direct user consent</strong>. The {@link #disable()} method is
910 * provided only for applications that include a user interface for changing
911 * system settings, such as a "power manager" app.</p>
Brad Fitzpatrick3219ab42009-09-25 16:31:39 +0400912 * <p>This is an asynchronous call: it will return immediately, and
Nick Pellyde893f52009-09-08 13:15:33 -0700913 * clients should listen for {@link #ACTION_STATE_CHANGED}
914 * to be notified of subsequent adapter state changes. If this call returns
915 * true, then the adapter state will immediately transition from {@link
916 * #STATE_ON} to {@link #STATE_TURNING_OFF}, and some time
917 * later transition to either {@link #STATE_OFF} or {@link
918 * #STATE_ON}. If this call returns false then there was an
919 * immediate problem that will prevent the adapter from being turned off -
920 * such as the adapter already being turned off.
Scott Mained2a70d2009-12-09 16:07:39 -0800921 * <p>Requires the {@link android.Manifest.permission#BLUETOOTH_ADMIN}
922 * permission
Nick Pellybd022f42009-08-14 18:33:38 -0700923 *
Nick Pellyde893f52009-09-08 13:15:33 -0700924 * @return true to indicate adapter shutdown has begun, or false on
925 * immediate error
Nick Pellybd022f42009-08-14 18:33:38 -0700926 */
Tor Norbye2d497522015-04-23 17:10:21 -0700927 @RequiresPermission(Manifest.permission.BLUETOOTH_ADMIN)
Nick Pellybd022f42009-08-14 18:33:38 -0700928 public boolean disable() {
929 try {
fredc0f420372012-04-12 00:02:00 -0700930 return mManagerService.disable(true);
Jaikumar Ganeshe21a4ac2012-03-06 17:15:16 -0800931 } catch (RemoteException e) {Log.e(TAG, "", e);}
932 return false;
933 }
934
935 /**
936 * Turn off the local Bluetooth adapter and don't persist the setting.
937 *
938 * <p>Requires the {@link android.Manifest.permission#BLUETOOTH_ADMIN}
939 * permission
940 *
941 * @return true to indicate adapter shutdown has begun, or false on
942 * immediate error
943 * @hide
944 */
945 public boolean disable(boolean persist) {
fredc0f420372012-04-12 00:02:00 -0700946
Jaikumar Ganeshe21a4ac2012-03-06 17:15:16 -0800947 try {
fredc0f420372012-04-12 00:02:00 -0700948 return mManagerService.disable(persist);
Nick Pellybd022f42009-08-14 18:33:38 -0700949 } catch (RemoteException e) {Log.e(TAG, "", e);}
950 return false;
951 }
952
Nick Pellyde893f52009-09-08 13:15:33 -0700953 /**
954 * Returns the hardware address of the local Bluetooth adapter.
955 * <p>For example, "00:11:22:AA:BB:CC".
956 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
957 *
958 * @return Bluetooth hardware address as string
959 */
Tor Norbye2d497522015-04-23 17:10:21 -0700960 @RequiresPermission(Manifest.permission.BLUETOOTH)
Nick Pellybd022f42009-08-14 18:33:38 -0700961 public String getAddress() {
962 try {
fredc0f420372012-04-12 00:02:00 -0700963 return mManagerService.getAddress();
Nick Pellybd022f42009-08-14 18:33:38 -0700964 } catch (RemoteException e) {Log.e(TAG, "", e);}
965 return null;
966 }
967
968 /**
Nick Pellyde893f52009-09-08 13:15:33 -0700969 * Get the friendly Bluetooth name of the local Bluetooth adapter.
970 * <p>This name is visible to remote Bluetooth devices.
971 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
Nick Pellybd022f42009-08-14 18:33:38 -0700972 *
Nick Pellyde893f52009-09-08 13:15:33 -0700973 * @return the Bluetooth name, or null on error
Nick Pellybd022f42009-08-14 18:33:38 -0700974 */
975 public String getName() {
976 try {
fredc116d1d462012-04-20 14:47:08 -0700977 return mManagerService.getName();
Nick Pellybd022f42009-08-14 18:33:38 -0700978 } catch (RemoteException e) {Log.e(TAG, "", e);}
979 return null;
980 }
981
982 /**
Zhihai Xuaf5971e2013-06-10 20:28:31 -0700983 * enable or disable Bluetooth HCI snoop log.
984 *
985 * <p>Requires the {@link android.Manifest.permission#BLUETOOTH_ADMIN}
986 * permission
987 *
988 * @return true to indicate configure HCI log successfully, or false on
989 * immediate error
990 * @hide
991 */
992 public boolean configHciSnoopLog(boolean enable) {
993 try {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700994 mServiceLock.readLock().lock();
995 if (mService != null) return mService.configHciSnoopLog(enable);
996 } catch (RemoteException e) {
997 Log.e(TAG, "", e);
998 } finally {
999 mServiceLock.readLock().unlock();
1000 }
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001001 return false;
1002 }
1003
1004 /**
Ajay Panickercda6e872015-07-28 16:52:09 -07001005 * Factory reset bluetooth settings.
1006 *
1007 * <p>Requires the {@link android.Manifest.permission#BLUETOOTH_PRIVILEGED}
1008 * permission
1009 *
1010 * @return true to indicate that the config file was successfully cleared
1011 *
1012 * @hide
1013 */
1014 public boolean factoryReset() {
1015 try {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001016 mServiceLock.readLock().lock();
Ajay Panickercda6e872015-07-28 16:52:09 -07001017 if (mService != null) {
1018 return mService.factoryReset();
1019 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001020 SystemProperties.set("persist.bluetooth.factoryreset", "true");
1021 } catch (RemoteException e) {
1022 Log.e(TAG, "", e);
1023 } finally {
1024 mServiceLock.readLock().unlock();
1025 }
Ajay Panickercda6e872015-07-28 16:52:09 -07001026 return false;
1027 }
1028
1029 /**
Jaikumar Ganesh58b93c32010-11-23 20:03:10 -08001030 * Get the UUIDs supported by the local Bluetooth adapter.
1031 *
1032 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
1033 *
1034 * @return the UUIDs supported by the local Bluetooth Adapter.
1035 * @hide
1036 */
1037 public ParcelUuid[] getUuids() {
Matthew Xie44b58ab2011-11-16 12:27:57 -08001038 if (getState() != STATE_ON) return null;
Jaikumar Ganesh58b93c32010-11-23 20:03:10 -08001039 try {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001040 mServiceLock.readLock().lock();
1041 if (mService != null) return mService.getUuids();
1042 } catch (RemoteException e) {
1043 Log.e(TAG, "", e);
1044 } finally {
1045 mServiceLock.readLock().unlock();
1046 }
Jaikumar Ganesh58b93c32010-11-23 20:03:10 -08001047 return null;
1048 }
1049
1050 /**
Jake Hamby0f584302010-09-16 18:12:51 -07001051 * Set the friendly Bluetooth name of the local Bluetooth adapter.
Nick Pellyde893f52009-09-08 13:15:33 -07001052 * <p>This name is visible to remote Bluetooth devices.
Jake Hamby0f584302010-09-16 18:12:51 -07001053 * <p>Valid Bluetooth names are a maximum of 248 bytes using UTF-8
1054 * encoding, although many remote devices can only display the first
1055 * 40 characters, and some may be limited to just 20.
Jaikumar Ganeshfec86f42010-08-09 16:54:03 -07001056 * <p>If Bluetooth state is not {@link #STATE_ON}, this API
1057 * will return false. After turning on Bluetooth,
1058 * wait for {@link #ACTION_STATE_CHANGED} with {@link #STATE_ON}
1059 * to get the updated value.
Nick Pellyde893f52009-09-08 13:15:33 -07001060 * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN}
Nick Pellybd022f42009-08-14 18:33:38 -07001061 *
Nick Pellyde893f52009-09-08 13:15:33 -07001062 * @param name a valid Bluetooth name
1063 * @return true if the name was set, false otherwise
Nick Pellybd022f42009-08-14 18:33:38 -07001064 */
Tor Norbye2d497522015-04-23 17:10:21 -07001065 @RequiresPermission(Manifest.permission.BLUETOOTH_ADMIN)
Nick Pellybd022f42009-08-14 18:33:38 -07001066 public boolean setName(String name) {
Jaikumar Ganeshf5ff1702010-08-06 19:03:13 -07001067 if (getState() != STATE_ON) return false;
Nick Pellybd022f42009-08-14 18:33:38 -07001068 try {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001069 mServiceLock.readLock().lock();
1070 if (mService != null) return mService.setName(name);
1071 } catch (RemoteException e) {
1072 Log.e(TAG, "", e);
1073 } finally {
1074 mServiceLock.readLock().unlock();
1075 }
Nick Pellybd022f42009-08-14 18:33:38 -07001076 return false;
1077 }
1078
1079 /**
Jake Hamby0f584302010-09-16 18:12:51 -07001080 * Get the current Bluetooth scan mode of the local Bluetooth adapter.
Nick Pellyde893f52009-09-08 13:15:33 -07001081 * <p>The Bluetooth scan mode determines if the local adapter is
1082 * connectable and/or discoverable from remote Bluetooth devices.
1083 * <p>Possible values are:
1084 * {@link #SCAN_MODE_NONE},
1085 * {@link #SCAN_MODE_CONNECTABLE},
1086 * {@link #SCAN_MODE_CONNECTABLE_DISCOVERABLE}.
Jaikumar Ganeshfec86f42010-08-09 16:54:03 -07001087 * <p>If Bluetooth state is not {@link #STATE_ON}, this API
1088 * will return {@link #SCAN_MODE_NONE}. After turning on Bluetooth,
1089 * wait for {@link #ACTION_STATE_CHANGED} with {@link #STATE_ON}
1090 * to get the updated value.
Nick Pellyde893f52009-09-08 13:15:33 -07001091 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
1092 *
1093 * @return scan mode
Nick Pellybd022f42009-08-14 18:33:38 -07001094 */
Tor Norbye2d497522015-04-23 17:10:21 -07001095 @RequiresPermission(Manifest.permission.BLUETOOTH)
1096 @ScanMode
Nick Pellybd022f42009-08-14 18:33:38 -07001097 public int getScanMode() {
Jaikumar Ganeshf5ff1702010-08-06 19:03:13 -07001098 if (getState() != STATE_ON) return SCAN_MODE_NONE;
Nick Pellybd022f42009-08-14 18:33:38 -07001099 try {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001100 mServiceLock.readLock().lock();
1101 if (mService != null) return mService.getScanMode();
1102 } catch (RemoteException e) {
1103 Log.e(TAG, "", e);
1104 } finally {
1105 mServiceLock.readLock().unlock();
1106 }
Nick Pellyde893f52009-09-08 13:15:33 -07001107 return SCAN_MODE_NONE;
Nick Pellybd022f42009-08-14 18:33:38 -07001108 }
1109
1110 /**
Nick Pellyde893f52009-09-08 13:15:33 -07001111 * Set the Bluetooth scan mode of the local Bluetooth adapter.
1112 * <p>The Bluetooth scan mode determines if the local adapter is
1113 * connectable and/or discoverable from remote Bluetooth devices.
Nick Pelly12835472009-09-25 15:00:29 -07001114 * <p>For privacy reasons, discoverable mode is automatically turned off
1115 * after <code>duration</code> seconds. For example, 120 seconds should be
1116 * enough for a remote device to initiate and complete its discovery
1117 * process.
Nick Pellyde893f52009-09-08 13:15:33 -07001118 * <p>Valid scan mode values are:
1119 * {@link #SCAN_MODE_NONE},
1120 * {@link #SCAN_MODE_CONNECTABLE},
1121 * {@link #SCAN_MODE_CONNECTABLE_DISCOVERABLE}.
Jaikumar Ganeshfec86f42010-08-09 16:54:03 -07001122 * <p>If Bluetooth state is not {@link #STATE_ON}, this API
1123 * will return false. After turning on Bluetooth,
1124 * wait for {@link #ACTION_STATE_CHANGED} with {@link #STATE_ON}
1125 * to get the updated value.
Nick Pelly18b1e792009-09-24 11:14:15 -07001126 * <p>Requires {@link android.Manifest.permission#WRITE_SECURE_SETTINGS}
1127 * <p>Applications cannot set the scan mode. They should use
1128 * <code>startActivityForResult(
1129 * BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE})
1130 * </code>instead.
Nick Pellyde893f52009-09-08 13:15:33 -07001131 *
1132 * @param mode valid scan mode
Nick Pelly12835472009-09-25 15:00:29 -07001133 * @param duration time in seconds to apply scan mode, only used for
1134 * {@link #SCAN_MODE_CONNECTABLE_DISCOVERABLE}
Nick Pellyde893f52009-09-08 13:15:33 -07001135 * @return true if the scan mode was set, false otherwise
Nick Pelly18b1e792009-09-24 11:14:15 -07001136 * @hide
Nick Pellybd022f42009-08-14 18:33:38 -07001137 */
Tor Norbye2d497522015-04-23 17:10:21 -07001138 public boolean setScanMode(@ScanMode int mode, int duration) {
Jaikumar Ganeshf5ff1702010-08-06 19:03:13 -07001139 if (getState() != STATE_ON) return false;
Nick Pellybd022f42009-08-14 18:33:38 -07001140 try {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001141 mServiceLock.readLock().lock();
1142 if (mService != null) return mService.setScanMode(mode, duration);
1143 } catch (RemoteException e) {
1144 Log.e(TAG, "", e);
1145 } finally {
1146 mServiceLock.readLock().unlock();
1147 }
Nick Pellyde893f52009-09-08 13:15:33 -07001148 return false;
Nick Pellybd022f42009-08-14 18:33:38 -07001149 }
1150
Nick Pelly45e27042009-08-19 11:00:00 -07001151 /** @hide */
Nick Pelly12835472009-09-25 15:00:29 -07001152 public boolean setScanMode(int mode) {
Jaikumar Ganeshf5ff1702010-08-06 19:03:13 -07001153 if (getState() != STATE_ON) return false;
Srikanth Uppala827de2d2012-04-04 03:33:26 -07001154 /* getDiscoverableTimeout() to use the latest from NV than use 0 */
1155 return setScanMode(mode, getDiscoverableTimeout());
Nick Pelly12835472009-09-25 15:00:29 -07001156 }
1157
1158 /** @hide */
Nick Pellybd022f42009-08-14 18:33:38 -07001159 public int getDiscoverableTimeout() {
Jaikumar Ganeshf5ff1702010-08-06 19:03:13 -07001160 if (getState() != STATE_ON) return -1;
Nick Pellybd022f42009-08-14 18:33:38 -07001161 try {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001162 mServiceLock.readLock().lock();
1163 if (mService != null) return mService.getDiscoverableTimeout();
1164 } catch (RemoteException e) {
1165 Log.e(TAG, "", e);
1166 } finally {
1167 mServiceLock.readLock().unlock();
1168 }
Nick Pellybd022f42009-08-14 18:33:38 -07001169 return -1;
1170 }
1171
Nick Pelly45e27042009-08-19 11:00:00 -07001172 /** @hide */
Nick Pellybd022f42009-08-14 18:33:38 -07001173 public void setDiscoverableTimeout(int timeout) {
Jaikumar Ganeshf5ff1702010-08-06 19:03:13 -07001174 if (getState() != STATE_ON) return;
Nick Pellybd022f42009-08-14 18:33:38 -07001175 try {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001176 mServiceLock.readLock().lock();
1177 if (mService != null) mService.setDiscoverableTimeout(timeout);
1178 } catch (RemoteException e) {
1179 Log.e(TAG, "", e);
1180 } finally {
1181 mServiceLock.readLock().unlock();
1182 }
Nick Pellybd022f42009-08-14 18:33:38 -07001183 }
1184
Nick Pelly005b2282009-09-10 10:21:56 -07001185 /**
1186 * Start the remote device discovery process.
1187 * <p>The discovery process usually involves an inquiry scan of about 12
1188 * seconds, followed by a page scan of each new device to retrieve its
1189 * Bluetooth name.
1190 * <p>This is an asynchronous call, it will return immediately. Register
1191 * for {@link #ACTION_DISCOVERY_STARTED} and {@link
1192 * #ACTION_DISCOVERY_FINISHED} intents to determine exactly when the
1193 * discovery starts and completes. Register for {@link
1194 * BluetoothDevice#ACTION_FOUND} to be notified as remote Bluetooth devices
1195 * are found.
1196 * <p>Device discovery is a heavyweight procedure. New connections to
1197 * remote Bluetooth devices should not be attempted while discovery is in
1198 * progress, and existing connections will experience limited bandwidth
1199 * and high latency. Use {@link #cancelDiscovery()} to cancel an ongoing
Scott Main6d95fc02009-11-19 17:00:19 -08001200 * discovery. Discovery is not managed by the Activity,
1201 * but is run as a system service, so an application should always call
1202 * {@link BluetoothAdapter#cancelDiscovery()} even if it
1203 * did not directly request a discovery, just to be sure.
Nick Pelly005b2282009-09-10 10:21:56 -07001204 * <p>Device discovery will only find remote devices that are currently
1205 * <i>discoverable</i> (inquiry scan enabled). Many Bluetooth devices are
1206 * not discoverable by default, and need to be entered into a special mode.
Jaikumar Ganeshfec86f42010-08-09 16:54:03 -07001207 * <p>If Bluetooth state is not {@link #STATE_ON}, this API
1208 * will return false. After turning on Bluetooth,
1209 * wait for {@link #ACTION_STATE_CHANGED} with {@link #STATE_ON}
1210 * to get the updated value.
Nick Pelly005b2282009-09-10 10:21:56 -07001211 * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN}.
1212 *
1213 * @return true on success, false on error
1214 */
Tor Norbye2d497522015-04-23 17:10:21 -07001215 @RequiresPermission(Manifest.permission.BLUETOOTH_ADMIN)
Nick Pellybd022f42009-08-14 18:33:38 -07001216 public boolean startDiscovery() {
Jaikumar Ganeshf5ff1702010-08-06 19:03:13 -07001217 if (getState() != STATE_ON) return false;
Nick Pellybd022f42009-08-14 18:33:38 -07001218 try {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001219 mServiceLock.readLock().lock();
1220 if (mService != null) return mService.startDiscovery();
1221 } catch (RemoteException e) {
1222 Log.e(TAG, "", e);
1223 } finally {
1224 mServiceLock.readLock().unlock();
1225 }
Nick Pellybd022f42009-08-14 18:33:38 -07001226 return false;
1227 }
1228
Nick Pelly005b2282009-09-10 10:21:56 -07001229 /**
1230 * Cancel the current device discovery process.
1231 * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN}.
Jake Hamby0f584302010-09-16 18:12:51 -07001232 * <p>Because discovery is a heavyweight procedure for the Bluetooth
Scott Main6d95fc02009-11-19 17:00:19 -08001233 * adapter, this method should always be called before attempting to connect
1234 * to a remote device with {@link
1235 * android.bluetooth.BluetoothSocket#connect()}. Discovery is not managed by
1236 * the Activity, but is run as a system service, so an application should
1237 * always call cancel discovery even if it did not directly request a
1238 * discovery, just to be sure.
Jaikumar Ganeshfec86f42010-08-09 16:54:03 -07001239 * <p>If Bluetooth state is not {@link #STATE_ON}, this API
1240 * will return false. After turning on Bluetooth,
1241 * wait for {@link #ACTION_STATE_CHANGED} with {@link #STATE_ON}
1242 * to get the updated value.
Nick Pelly005b2282009-09-10 10:21:56 -07001243 *
1244 * @return true on success, false on error
1245 */
Tor Norbye2d497522015-04-23 17:10:21 -07001246 @RequiresPermission(Manifest.permission.BLUETOOTH_ADMIN)
Nick Pelly005b2282009-09-10 10:21:56 -07001247 public boolean cancelDiscovery() {
Jaikumar Ganeshf5ff1702010-08-06 19:03:13 -07001248 if (getState() != STATE_ON) return false;
Nick Pellybd022f42009-08-14 18:33:38 -07001249 try {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001250 mServiceLock.readLock().lock();
1251 if (mService != null) return mService.cancelDiscovery();
1252 } catch (RemoteException e) {
1253 Log.e(TAG, "", e);
1254 } finally {
1255 mServiceLock.readLock().unlock();
1256 }
Nick Pelly005b2282009-09-10 10:21:56 -07001257 return false;
Nick Pellybd022f42009-08-14 18:33:38 -07001258 }
1259
Nick Pelly005b2282009-09-10 10:21:56 -07001260 /**
1261 * Return true if the local Bluetooth adapter is currently in the device
1262 * discovery process.
1263 * <p>Device discovery is a heavyweight procedure. New connections to
1264 * remote Bluetooth devices should not be attempted while discovery is in
1265 * progress, and existing connections will experience limited bandwidth
1266 * and high latency. Use {@link #cancelDiscovery()} to cancel an ongoing
1267 * discovery.
1268 * <p>Applications can also register for {@link #ACTION_DISCOVERY_STARTED}
1269 * or {@link #ACTION_DISCOVERY_FINISHED} to be notified when discovery
1270 * starts or completes.
Jaikumar Ganeshfec86f42010-08-09 16:54:03 -07001271 * <p>If Bluetooth state is not {@link #STATE_ON}, this API
1272 * will return false. After turning on Bluetooth,
1273 * wait for {@link #ACTION_STATE_CHANGED} with {@link #STATE_ON}
1274 * to get the updated value.
Nick Pellye6ee3be2009-10-08 23:27:28 +02001275 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}.
Nick Pelly005b2282009-09-10 10:21:56 -07001276 *
1277 * @return true if discovering
1278 */
Tor Norbye2d497522015-04-23 17:10:21 -07001279 @RequiresPermission(Manifest.permission.BLUETOOTH)
Nick Pellybd022f42009-08-14 18:33:38 -07001280 public boolean isDiscovering() {
Jaikumar Ganeshf5ff1702010-08-06 19:03:13 -07001281 if (getState() != STATE_ON) return false;
Nick Pellybd022f42009-08-14 18:33:38 -07001282 try {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001283 mServiceLock.readLock().lock();
1284 if (mService != null) return mService.isDiscovering();
1285 } catch (RemoteException e) {
1286 Log.e(TAG, "", e);
1287 } finally {
1288 mServiceLock.readLock().unlock();
1289 }
Nick Pellybd022f42009-08-14 18:33:38 -07001290 return false;
1291 }
1292
1293 /**
Prerepa Viswanadham0c116e12014-07-02 12:30:38 -07001294 * Return true if the multi advertisement is supported by the chipset
1295 *
Prerepa Viswanadham0c116e12014-07-02 12:30:38 -07001296 * @return true if Multiple Advertisement feature is supported
1297 */
1298 public boolean isMultipleAdvertisementSupported() {
1299 if (getState() != STATE_ON) return false;
1300 try {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001301 mServiceLock.readLock().lock();
1302 if (mService != null) return mService.isMultiAdvertisementSupported();
Prerepa Viswanadham0c116e12014-07-02 12:30:38 -07001303 } catch (RemoteException e) {
1304 Log.e(TAG, "failed to get isMultipleAdvertisementSupported, error: ", e);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001305 } finally {
1306 mServiceLock.readLock().unlock();
Prerepa Viswanadham0c116e12014-07-02 12:30:38 -07001307 }
1308 return false;
1309 }
1310
1311 /**
Wei Wangd91f1932015-03-19 15:09:56 -07001312 * Returns {@code true} if BLE scan is always available, {@code false} otherwise. <p>
1313 *
1314 * If this returns {@code true}, application can issue {@link BluetoothLeScanner#startScan} and
1315 * fetch scan results even when Bluetooth is turned off.<p>
1316 *
1317 * To change this setting, use {@link #ACTION_REQUEST_BLE_SCAN_ALWAYS_AVAILABLE}.
1318 *
1319 * @hide
1320 */
1321 @SystemApi
1322 public boolean isBleScanAlwaysAvailable() {
Wei Wang67d84162015-04-26 17:04:29 -07001323 try {
1324 return mManagerService.isBleScanAlwaysAvailable();
1325 } catch (RemoteException e) {
1326 Log.e(TAG, "remote expection when calling isBleScanAlwaysAvailable", e);
1327 return false;
1328 }
Wei Wangd91f1932015-03-19 15:09:56 -07001329 }
1330
1331 /**
Prerepa Viswanadham0c116e12014-07-02 12:30:38 -07001332 * Return true if offloaded filters are supported
1333 *
Prerepa Viswanadham0c116e12014-07-02 12:30:38 -07001334 * @return true if chipset supports on-chip filtering
1335 */
1336 public boolean isOffloadedFilteringSupported() {
Wei Wang46ab7232015-05-07 16:25:33 -07001337 if (!getLeAccess()) return false;
Prerepa Viswanadham0c116e12014-07-02 12:30:38 -07001338 try {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001339 mServiceLock.readLock().lock();
1340 if (mService != null) return mService.isOffloadedFilteringSupported();
Prerepa Viswanadham0c116e12014-07-02 12:30:38 -07001341 } catch (RemoteException e) {
1342 Log.e(TAG, "failed to get isOffloadedFilteringSupported, error: ", e);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001343 } finally {
1344 mServiceLock.readLock().unlock();
Prerepa Viswanadham0c116e12014-07-02 12:30:38 -07001345 }
1346 return false;
1347 }
1348
1349 /**
1350 * Return true if offloaded scan batching is supported
1351 *
Prerepa Viswanadham0c116e12014-07-02 12:30:38 -07001352 * @return true if chipset supports on-chip scan batching
1353 */
1354 public boolean isOffloadedScanBatchingSupported() {
Wei Wang46ab7232015-05-07 16:25:33 -07001355 if (!getLeAccess()) return false;
Prerepa Viswanadham0c116e12014-07-02 12:30:38 -07001356 try {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001357 mServiceLock.readLock().lock();
1358 if (mService != null) return mService.isOffloadedScanBatchingSupported();
Prerepa Viswanadham0c116e12014-07-02 12:30:38 -07001359 } catch (RemoteException e) {
1360 Log.e(TAG, "failed to get isOffloadedScanBatchingSupported, error: ", e);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001361 } finally {
1362 mServiceLock.readLock().unlock();
Prerepa Viswanadham0c116e12014-07-02 12:30:38 -07001363 }
1364 return false;
1365 }
1366
1367 /**
Prerepa Viswanadhame593d0a2015-04-07 14:36:53 -07001368 * Return true if hardware has entries available for matching beacons
1369 *
1370 * @return true if there are hw entries available for matching beacons
1371 * @hide
1372 */
1373 public boolean isHardwareTrackingFiltersAvailable() {
Wei Wang46ab7232015-05-07 16:25:33 -07001374 if (!getLeAccess()) return false;
Prerepa Viswanadhame593d0a2015-04-07 14:36:53 -07001375 try {
Prerepa Viswanadhamdb1dbb82015-04-09 17:14:50 -07001376 IBluetoothGatt iGatt = mManagerService.getBluetoothGatt();
1377 if (iGatt == null) {
1378 // BLE is not supported
1379 return false;
Prerepa Viswanadhame593d0a2015-04-07 14:36:53 -07001380 }
Prerepa Viswanadhamdb1dbb82015-04-09 17:14:50 -07001381 return (iGatt.numHwTrackFiltersAvailable() != 0);
Prerepa Viswanadhame593d0a2015-04-07 14:36:53 -07001382 } catch (RemoteException e) {
1383 Log.e(TAG, "", e);
1384 }
1385 return false;
1386 }
1387
1388 /**
Prerepa Viswanadham8caac742014-07-22 17:00:09 -07001389 * Return the record of {@link BluetoothActivityEnergyInfo} object that
1390 * has the activity and energy info. This can be used to ascertain what
1391 * the controller has been up to, since the last sample.
1392 * @param updateType Type of info, cached vs refreshed.
1393 *
1394 * @return a record with {@link BluetoothActivityEnergyInfo} or null if
1395 * report is unavailable or unsupported
Adam Lesinski010bf372016-04-11 12:18:18 -07001396 * @deprecated use the asynchronous
Adam Lesinski991357f2016-05-10 14:00:03 -07001397 * {@link #requestControllerActivityEnergyInfo(ResultReceiver)} instead.
Prerepa Viswanadham8caac742014-07-22 17:00:09 -07001398 * @hide
1399 */
Adam Lesinski010bf372016-04-11 12:18:18 -07001400 @Deprecated
Prerepa Viswanadham8caac742014-07-22 17:00:09 -07001401 public BluetoothActivityEnergyInfo getControllerActivityEnergyInfo(int updateType) {
Adam Lesinski010bf372016-04-11 12:18:18 -07001402 SynchronousResultReceiver receiver = new SynchronousResultReceiver();
Adam Lesinski991357f2016-05-10 14:00:03 -07001403 requestControllerActivityEnergyInfo(receiver);
Prerepa Viswanadham8caac742014-07-22 17:00:09 -07001404 try {
Adam Lesinski010bf372016-04-11 12:18:18 -07001405 SynchronousResultReceiver.Result result = receiver.awaitResult(1000);
1406 if (result.bundle != null) {
1407 return result.bundle.getParcelable(BatteryStats.RESULT_RECEIVER_CONTROLLER_KEY);
1408 }
1409 } catch (TimeoutException e) {
1410 Log.e(TAG, "getControllerActivityEnergyInfo timed out");
1411 }
1412 return null;
1413 }
1414
1415 /**
1416 * Request the record of {@link BluetoothActivityEnergyInfo} object that
1417 * has the activity and energy info. This can be used to ascertain what
1418 * the controller has been up to, since the last sample.
1419 *
1420 * A null value for the activity info object may be sent if the bluetooth service is
1421 * unreachable or the device does not support reporting such information.
1422 *
Adam Lesinski010bf372016-04-11 12:18:18 -07001423 * @param result The callback to which to send the activity info.
1424 * @hide
1425 */
Adam Lesinski991357f2016-05-10 14:00:03 -07001426 public void requestControllerActivityEnergyInfo(ResultReceiver result) {
Adam Lesinski010bf372016-04-11 12:18:18 -07001427 try {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001428 mServiceLock.readLock().lock();
1429 if (mService != null) {
1430 mService.requestActivityInfo(result);
1431 result = null;
Prerepa Viswanadham8caac742014-07-22 17:00:09 -07001432 }
Prerepa Viswanadham8caac742014-07-22 17:00:09 -07001433 } catch (RemoteException e) {
1434 Log.e(TAG, "getControllerActivityEnergyInfoCallback: " + e);
Adam Lesinski991357f2016-05-10 14:00:03 -07001435 } finally {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001436 mServiceLock.readLock().unlock();
Adam Lesinski991357f2016-05-10 14:00:03 -07001437 if (result != null) {
1438 // Only send an immediate result if we failed.
1439 result.send(0, null);
1440 }
Prerepa Viswanadham8caac742014-07-22 17:00:09 -07001441 }
Prerepa Viswanadham8caac742014-07-22 17:00:09 -07001442 }
1443
1444 /**
Nick Pelly005b2282009-09-10 10:21:56 -07001445 * Return the set of {@link BluetoothDevice} objects that are bonded
1446 * (paired) to the local adapter.
Jaikumar Ganeshfec86f42010-08-09 16:54:03 -07001447 * <p>If Bluetooth state is not {@link #STATE_ON}, this API
1448 * will return an empty set. After turning on Bluetooth,
1449 * wait for {@link #ACTION_STATE_CHANGED} with {@link #STATE_ON}
1450 * to get the updated value.
Nick Pellye6ee3be2009-10-08 23:27:28 +02001451 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}.
Nick Pellybd022f42009-08-14 18:33:38 -07001452 *
Nick Pelly005b2282009-09-10 10:21:56 -07001453 * @return unmodifiable set of {@link BluetoothDevice}, or null on error
Nick Pellybd022f42009-08-14 18:33:38 -07001454 */
Tor Norbye2d497522015-04-23 17:10:21 -07001455 @RequiresPermission(Manifest.permission.BLUETOOTH)
Nick Pellybd022f42009-08-14 18:33:38 -07001456 public Set<BluetoothDevice> getBondedDevices() {
Jaikumar Ganeshfec86f42010-08-09 16:54:03 -07001457 if (getState() != STATE_ON) {
Jaikumar Ganeshe4caddb2012-01-25 16:16:48 -08001458 return toDeviceSet(new BluetoothDevice[0]);
Jaikumar Ganeshfec86f42010-08-09 16:54:03 -07001459 }
Nick Pellybd022f42009-08-14 18:33:38 -07001460 try {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001461 mServiceLock.readLock().lock();
1462 if (mService != null) return toDeviceSet(mService.getBondedDevices());
fredc0f420372012-04-12 00:02:00 -07001463 return toDeviceSet(new BluetoothDevice[0]);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001464 } catch (RemoteException e) {
1465 Log.e(TAG, "", e);
1466 } finally {
1467 mServiceLock.readLock().unlock();
1468 }
Nick Pellybd022f42009-08-14 18:33:38 -07001469 return null;
1470 }
1471
1472 /**
Bryce Leeb1301fa2016-10-09 12:54:42 -07001473 * Gets the currently supported profiles by the adapter.
1474 *
1475 *<p> This can be used to check whether a profile is supported before attempting
1476 * to connect to its respective proxy.
1477 *
1478 * @return a list of integers indicating the ids of supported profiles as defined in
1479 * {@link BluetoothProfile}.
1480 * @hide
1481 */
1482 public List<Integer> getSupportedProfiles() {
1483 final ArrayList<Integer> supportedProfiles = new ArrayList<Integer>();
1484
1485 try {
1486 synchronized (mManagerCallback) {
1487 if (mService != null) {
1488 final long supportedProfilesBitMask = mService.getSupportedProfiles();
1489
1490 for (int i = 0; i <= BluetoothProfile.MAX_PROFILE_ID; i++) {
1491 if ((supportedProfilesBitMask & (1 << i)) != 0) {
1492 supportedProfiles.add(i);
1493 }
1494 }
1495 }
1496 }
1497 } catch (RemoteException e) {Log.e(TAG, "getSupportedProfiles:", e);}
1498
1499 return supportedProfiles;
1500 }
1501
1502 /**
Jaikumar Ganeshc53cab22010-10-26 16:02:26 -07001503 * Get the current connection state of the local Bluetooth adapter.
1504 * This can be used to check whether the local Bluetooth adapter is connected
1505 * to any profile of any other remote Bluetooth Device.
1506 *
1507 * <p> Use this function along with {@link #ACTION_CONNECTION_STATE_CHANGED}
1508 * intent to get the connection state of the adapter.
1509 *
1510 * @return One of {@link #STATE_CONNECTED}, {@link #STATE_DISCONNECTED},
1511 * {@link #STATE_CONNECTING} or {@link #STATE_DISCONNECTED}
1512 *
1513 * @hide
1514 */
1515 public int getConnectionState() {
1516 if (getState() != STATE_ON) return BluetoothAdapter.STATE_DISCONNECTED;
1517 try {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001518 mServiceLock.readLock().lock();
1519 if (mService != null) return mService.getAdapterConnectionState();
1520 } catch (RemoteException e) {
1521 Log.e(TAG, "getConnectionState:", e);
1522 } finally {
1523 mServiceLock.readLock().unlock();
1524 }
Jaikumar Ganeshc53cab22010-10-26 16:02:26 -07001525 return BluetoothAdapter.STATE_DISCONNECTED;
1526 }
1527
1528 /**
Jaikumar Ganeshcb1d3542011-08-19 10:26:32 -07001529 * Get the current connection state of a profile.
1530 * This function can be used to check whether the local Bluetooth adapter
1531 * is connected to any remote device for a specific profile.
Scott Main2d68a6b2011-09-26 22:59:38 -07001532 * Profile can be one of {@link BluetoothProfile#HEALTH}, {@link BluetoothProfile#HEADSET},
Jaikumar Ganesh93547902011-08-23 12:21:55 -07001533 * {@link BluetoothProfile#A2DP}.
Jaikumar Ganeshcb1d3542011-08-19 10:26:32 -07001534 *
1535 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}.
1536 *
1537 * <p> Return value can be one of
Jaikumar Ganesh93547902011-08-23 12:21:55 -07001538 * {@link BluetoothProfile#STATE_DISCONNECTED},
1539 * {@link BluetoothProfile#STATE_CONNECTING},
1540 * {@link BluetoothProfile#STATE_CONNECTED},
1541 * {@link BluetoothProfile#STATE_DISCONNECTING}
Jaikumar Ganeshcb1d3542011-08-19 10:26:32 -07001542 */
Tor Norbye2d497522015-04-23 17:10:21 -07001543 @RequiresPermission(Manifest.permission.BLUETOOTH)
Jaikumar Ganeshcb1d3542011-08-19 10:26:32 -07001544 public int getProfileConnectionState(int profile) {
1545 if (getState() != STATE_ON) return BluetoothProfile.STATE_DISCONNECTED;
1546 try {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001547 mServiceLock.readLock().lock();
1548 if (mService != null) return mService.getProfileConnectionState(profile);
Jaikumar Ganesh93547902011-08-23 12:21:55 -07001549 } catch (RemoteException e) {
1550 Log.e(TAG, "getProfileConnectionState:", e);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001551 } finally {
1552 mServiceLock.readLock().unlock();
Jaikumar Ganesh93547902011-08-23 12:21:55 -07001553 }
Jaikumar Ganeshcb1d3542011-08-19 10:26:32 -07001554 return BluetoothProfile.STATE_DISCONNECTED;
1555 }
1556
1557 /**
Nick Pelly45e27042009-08-19 11:00:00 -07001558 * Create a listening, secure RFCOMM Bluetooth socket.
1559 * <p>A remote device connecting to this socket will be authenticated and
Nick Pellybd022f42009-08-14 18:33:38 -07001560 * communication on this socket will be encrypted.
Nick Pelly45e27042009-08-19 11:00:00 -07001561 * <p>Use {@link BluetoothServerSocket#accept} to retrieve incoming
Nick Pelly24bb9b82009-10-02 20:34:18 -07001562 * connections from a listening {@link BluetoothServerSocket}.
Nick Pelly45e27042009-08-19 11:00:00 -07001563 * <p>Valid RFCOMM channels are in range 1 to 30.
Nick Pelly24bb9b82009-10-02 20:34:18 -07001564 * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN}
Nick Pelly45e27042009-08-19 11:00:00 -07001565 * @param channel RFCOMM channel to listen on
1566 * @return a listening RFCOMM BluetoothServerSocket
1567 * @throws IOException on error, for example Bluetooth not available, or
1568 * insufficient permissions, or channel in use.
Nick Pelly24bb9b82009-10-02 20:34:18 -07001569 * @hide
Nick Pellybd022f42009-08-14 18:33:38 -07001570 */
Nick Pelly45e27042009-08-19 11:00:00 -07001571 public BluetoothServerSocket listenUsingRfcommOn(int channel) throws IOException {
Casper Bonde3b3d1fe2015-05-08 14:32:24 +02001572 return listenUsingRfcommOn(channel, false, false);
Casper Bonde23284232015-04-21 13:12:05 +02001573 }
1574
1575 /**
1576 * Create a listening, secure RFCOMM Bluetooth socket.
1577 * <p>A remote device connecting to this socket will be authenticated and
1578 * communication on this socket will be encrypted.
1579 * <p>Use {@link BluetoothServerSocket#accept} to retrieve incoming
1580 * connections from a listening {@link BluetoothServerSocket}.
1581 * <p>Valid RFCOMM channels are in range 1 to 30.
1582 * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN}
1583 * <p>To auto assign a channel without creating a SDP record use
1584 * {@link SOCKET_CHANNEL_AUTO_STATIC_NO_SDP} as channel number.
1585 * @param channel RFCOMM channel to listen on
1586 * @param mitm enforce man-in-the-middle protection for authentication.
Casper Bonde3b3d1fe2015-05-08 14:32:24 +02001587 * @param min16DigitPin enforce a pin key length og minimum 16 digit for sec mode 2 connections.
Casper Bonde23284232015-04-21 13:12:05 +02001588 * @return a listening RFCOMM BluetoothServerSocket
1589 * @throws IOException on error, for example Bluetooth not available, or
1590 * insufficient permissions, or channel in use.
1591 * @hide
1592 */
Casper Bonde3b3d1fe2015-05-08 14:32:24 +02001593 public BluetoothServerSocket listenUsingRfcommOn(int channel, boolean mitm,
1594 boolean min16DigitPin)
1595 throws IOException {
Nick Pellybd022f42009-08-14 18:33:38 -07001596 BluetoothServerSocket socket = new BluetoothServerSocket(
Casper Bonde3b3d1fe2015-05-08 14:32:24 +02001597 BluetoothSocket.TYPE_RFCOMM, true, true, channel, mitm, min16DigitPin);
Nick Pelly24bb9b82009-10-02 20:34:18 -07001598 int errno = socket.mSocket.bindListen();
Casper Bonde23284232015-04-21 13:12:05 +02001599 if (channel == SOCKET_CHANNEL_AUTO_STATIC_NO_SDP) {
Casper Bonde238e0f92015-04-09 09:24:48 +02001600 socket.setChannel(socket.mSocket.getPort());
1601 }
Nick Pelly24bb9b82009-10-02 20:34:18 -07001602 if (errno != 0) {
zzy3b147b72012-04-03 19:48:32 -07001603 //TODO(BT): Throw the same exception error code
1604 // that the previous code was using.
1605 //socket.mSocket.throwErrnoNative(errno);
1606 throw new IOException("Error: " + errno);
Nick Pellybd022f42009-08-14 18:33:38 -07001607 }
1608 return socket;
1609 }
1610
1611 /**
Nick Pelly24bb9b82009-10-02 20:34:18 -07001612 * Create a listening, secure RFCOMM Bluetooth socket with Service Record.
1613 * <p>A remote device connecting to this socket will be authenticated and
1614 * communication on this socket will be encrypted.
1615 * <p>Use {@link BluetoothServerSocket#accept} to retrieve incoming
1616 * connections from a listening {@link BluetoothServerSocket}.
1617 * <p>The system will assign an unused RFCOMM channel to listen on.
1618 * <p>The system will also register a Service Discovery
1619 * Protocol (SDP) record with the local SDP server containing the specified
1620 * UUID, service name, and auto-assigned channel. Remote Bluetooth devices
1621 * can use the same UUID to query our SDP server and discover which channel
1622 * to connect to. This SDP record will be removed when this socket is
1623 * closed, or if this application closes unexpectedly.
Nick Pelly16fb88a2009-10-07 07:44:03 +02001624 * <p>Use {@link BluetoothDevice#createRfcommSocketToServiceRecord} to
1625 * connect to this socket from another device using the same {@link UUID}.
Nick Pelly24bb9b82009-10-02 20:34:18 -07001626 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
1627 * @param name service name for SDP record
1628 * @param uuid uuid for SDP record
1629 * @return a listening RFCOMM BluetoothServerSocket
1630 * @throws IOException on error, for example Bluetooth not available, or
1631 * insufficient permissions, or channel in use.
1632 */
Tor Norbye2d497522015-04-23 17:10:21 -07001633 @RequiresPermission(Manifest.permission.BLUETOOTH)
Nick Pelly16fb88a2009-10-07 07:44:03 +02001634 public BluetoothServerSocket listenUsingRfcommWithServiceRecord(String name, UUID uuid)
Nick Pelly24bb9b82009-10-02 20:34:18 -07001635 throws IOException {
Jaikumar Ganesh6eef14a2010-12-23 12:57:02 -08001636 return createNewRfcommSocketAndRecord(name, uuid, true, true);
1637 }
1638
1639 /**
1640 * Create a listening, insecure RFCOMM Bluetooth socket with Service Record.
Mathias Jeppssone3b9dc102011-03-21 15:06:52 +01001641 * <p>The link key is not required to be authenticated, i.e the communication may be
Jaikumar Ganesh6eef14a2010-12-23 12:57:02 -08001642 * vulnerable to Man In the Middle attacks. For Bluetooth 2.1 devices,
Mathias Jeppssone3b9dc102011-03-21 15:06:52 +01001643 * the link will be encrypted, as encryption is mandartory.
1644 * For legacy devices (pre Bluetooth 2.1 devices) the link will not
Jaikumar Ganesh6eef14a2010-12-23 12:57:02 -08001645 * be encrypted. Use {@link #listenUsingRfcommWithServiceRecord}, if an
1646 * encrypted and authenticated communication channel is desired.
1647 * <p>Use {@link BluetoothServerSocket#accept} to retrieve incoming
1648 * connections from a listening {@link BluetoothServerSocket}.
1649 * <p>The system will assign an unused RFCOMM channel to listen on.
1650 * <p>The system will also register a Service Discovery
1651 * Protocol (SDP) record with the local SDP server containing the specified
1652 * UUID, service name, and auto-assigned channel. Remote Bluetooth devices
1653 * can use the same UUID to query our SDP server and discover which channel
1654 * to connect to. This SDP record will be removed when this socket is
1655 * closed, or if this application closes unexpectedly.
1656 * <p>Use {@link BluetoothDevice#createRfcommSocketToServiceRecord} to
1657 * connect to this socket from another device using the same {@link UUID}.
1658 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
1659 * @param name service name for SDP record
1660 * @param uuid uuid for SDP record
1661 * @return a listening RFCOMM BluetoothServerSocket
1662 * @throws IOException on error, for example Bluetooth not available, or
1663 * insufficient permissions, or channel in use.
1664 */
Tor Norbye2d497522015-04-23 17:10:21 -07001665 @RequiresPermission(Manifest.permission.BLUETOOTH)
Jaikumar Ganesh6eef14a2010-12-23 12:57:02 -08001666 public BluetoothServerSocket listenUsingInsecureRfcommWithServiceRecord(String name, UUID uuid)
1667 throws IOException {
1668 return createNewRfcommSocketAndRecord(name, uuid, false, false);
1669 }
1670
Mathias Jeppssone3b9dc102011-03-21 15:06:52 +01001671 /**
1672 * Create a listening, encrypted,
1673 * RFCOMM Bluetooth socket with Service Record.
1674 * <p>The link will be encrypted, but the link key is not required to be authenticated
1675 * i.e the communication is vulnerable to Man In the Middle attacks. Use
1676 * {@link #listenUsingRfcommWithServiceRecord}, to ensure an authenticated link key.
1677 * <p> Use this socket if authentication of link key is not possible.
1678 * For example, for Bluetooth 2.1 devices, if any of the devices does not have
1679 * an input and output capability or just has the ability to display a numeric key,
1680 * a secure socket connection is not possible and this socket can be used.
1681 * Use {@link #listenUsingInsecureRfcommWithServiceRecord}, if encryption is not required.
1682 * For Bluetooth 2.1 devices, the link will be encrypted, as encryption is mandartory.
1683 * For more details, refer to the Security Model section 5.2 (vol 3) of
1684 * Bluetooth Core Specification version 2.1 + EDR.
1685 * <p>Use {@link BluetoothServerSocket#accept} to retrieve incoming
1686 * connections from a listening {@link BluetoothServerSocket}.
1687 * <p>The system will assign an unused RFCOMM channel to listen on.
1688 * <p>The system will also register a Service Discovery
1689 * Protocol (SDP) record with the local SDP server containing the specified
1690 * UUID, service name, and auto-assigned channel. Remote Bluetooth devices
1691 * can use the same UUID to query our SDP server and discover which channel
1692 * to connect to. This SDP record will be removed when this socket is
1693 * closed, or if this application closes unexpectedly.
1694 * <p>Use {@link BluetoothDevice#createRfcommSocketToServiceRecord} to
1695 * connect to this socket from another device using the same {@link UUID}.
1696 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
1697 * @param name service name for SDP record
1698 * @param uuid uuid for SDP record
1699 * @return a listening RFCOMM BluetoothServerSocket
1700 * @throws IOException on error, for example Bluetooth not available, or
1701 * insufficient permissions, or channel in use.
1702 * @hide
1703 */
1704 public BluetoothServerSocket listenUsingEncryptedRfcommWithServiceRecord(
1705 String name, UUID uuid) throws IOException {
1706 return createNewRfcommSocketAndRecord(name, uuid, false, true);
1707 }
1708
zzy3b147b72012-04-03 19:48:32 -07001709
Jaikumar Ganesh6eef14a2010-12-23 12:57:02 -08001710 private BluetoothServerSocket createNewRfcommSocketAndRecord(String name, UUID uuid,
1711 boolean auth, boolean encrypt) throws IOException {
Nick Pelly24bb9b82009-10-02 20:34:18 -07001712 BluetoothServerSocket socket;
zzy3b147b72012-04-03 19:48:32 -07001713 socket = new BluetoothServerSocket(BluetoothSocket.TYPE_RFCOMM, auth,
1714 encrypt, new ParcelUuid(uuid));
1715 socket.setServiceName(name);
1716 int errno = socket.mSocket.bindListen();
1717 if (errno != 0) {
1718 //TODO(BT): Throw the same exception error code
1719 // that the previous code was using.
1720 //socket.mSocket.throwErrnoNative(errno);
1721 throw new IOException("Error: " + errno);
Nick Pelly24bb9b82009-10-02 20:34:18 -07001722 }
Nick Pelly24bb9b82009-10-02 20:34:18 -07001723 return socket;
1724 }
1725
1726 /**
Nick Pellybd022f42009-08-14 18:33:38 -07001727 * Construct an unencrypted, unauthenticated, RFCOMM server socket.
1728 * Call #accept to retrieve connections to this socket.
1729 * @return An RFCOMM BluetoothServerSocket
1730 * @throws IOException On error, for example Bluetooth not available, or
1731 * insufficient permissions.
Nick Pelly45e27042009-08-19 11:00:00 -07001732 * @hide
Nick Pellybd022f42009-08-14 18:33:38 -07001733 */
1734 public BluetoothServerSocket listenUsingInsecureRfcommOn(int port) throws IOException {
1735 BluetoothServerSocket socket = new BluetoothServerSocket(
1736 BluetoothSocket.TYPE_RFCOMM, false, false, port);
Nick Pelly24bb9b82009-10-02 20:34:18 -07001737 int errno = socket.mSocket.bindListen();
Casper Bonde238e0f92015-04-09 09:24:48 +02001738 if(port == SOCKET_CHANNEL_AUTO_STATIC_NO_SDP) {
1739 socket.setChannel(socket.mSocket.getPort());
1740 }
Nick Pelly24bb9b82009-10-02 20:34:18 -07001741 if (errno != 0) {
zzy3b147b72012-04-03 19:48:32 -07001742 //TODO(BT): Throw the same exception error code
1743 // that the previous code was using.
1744 //socket.mSocket.throwErrnoNative(errno);
1745 throw new IOException("Error: " + errno);
Nick Pellybd022f42009-08-14 18:33:38 -07001746 }
1747 return socket;
1748 }
1749
Mathias Jeppssone3b9dc102011-03-21 15:06:52 +01001750 /**
1751 * Construct an encrypted, RFCOMM server socket.
1752 * Call #accept to retrieve connections to this socket.
1753 * @return An RFCOMM BluetoothServerSocket
1754 * @throws IOException On error, for example Bluetooth not available, or
1755 * insufficient permissions.
1756 * @hide
1757 */
1758 public BluetoothServerSocket listenUsingEncryptedRfcommOn(int port)
1759 throws IOException {
1760 BluetoothServerSocket socket = new BluetoothServerSocket(
1761 BluetoothSocket.TYPE_RFCOMM, false, true, port);
1762 int errno = socket.mSocket.bindListen();
Casper Bonde238e0f92015-04-09 09:24:48 +02001763 if(port == SOCKET_CHANNEL_AUTO_STATIC_NO_SDP) {
1764 socket.setChannel(socket.mSocket.getPort());
1765 }
zzy3b147b72012-04-03 19:48:32 -07001766 if (errno < 0) {
1767 //TODO(BT): Throw the same exception error code
1768 // that the previous code was using.
1769 //socket.mSocket.throwErrnoNative(errno);
1770 throw new IOException("Error: " + errno);
Mathias Jeppssone3b9dc102011-03-21 15:06:52 +01001771 }
1772 return socket;
1773 }
1774
Nick Pellybd022f42009-08-14 18:33:38 -07001775 /**
1776 * Construct a SCO server socket.
1777 * Call #accept to retrieve connections to this socket.
1778 * @return A SCO BluetoothServerSocket
1779 * @throws IOException On error, for example Bluetooth not available, or
1780 * insufficient permissions.
Nick Pelly45e27042009-08-19 11:00:00 -07001781 * @hide
Nick Pellybd022f42009-08-14 18:33:38 -07001782 */
1783 public static BluetoothServerSocket listenUsingScoOn() throws IOException {
1784 BluetoothServerSocket socket = new BluetoothServerSocket(
1785 BluetoothSocket.TYPE_SCO, false, false, -1);
Nick Pelly24bb9b82009-10-02 20:34:18 -07001786 int errno = socket.mSocket.bindListen();
zzy3b147b72012-04-03 19:48:32 -07001787 if (errno < 0) {
1788 //TODO(BT): Throw the same exception error code
1789 // that the previous code was using.
1790 //socket.mSocket.throwErrnoNative(errno);
Nick Pellybd022f42009-08-14 18:33:38 -07001791 }
1792 return socket;
1793 }
1794
Jaikumar Ganeshcc5494c2010-09-09 15:37:57 -07001795 /**
Casper Bonde238e0f92015-04-09 09:24:48 +02001796 * Construct an encrypted, authenticated, L2CAP server socket.
1797 * Call #accept to retrieve connections to this socket.
Casper Bonde23284232015-04-21 13:12:05 +02001798 * <p>To auto assign a port without creating a SDP record use
1799 * {@link SOCKET_CHANNEL_AUTO_STATIC_NO_SDP} as port number.
1800 * @param port the PSM to listen on
1801 * @param mitm enforce man-in-the-middle protection for authentication.
Casper Bonde3b3d1fe2015-05-08 14:32:24 +02001802 * @param min16DigitPin enforce a pin key length og minimum 16 digit for sec mode 2 connections.
Casper Bonde238e0f92015-04-09 09:24:48 +02001803 * @return An L2CAP BluetoothServerSocket
1804 * @throws IOException On error, for example Bluetooth not available, or
1805 * insufficient permissions.
1806 * @hide
1807 */
Casper Bonde3b3d1fe2015-05-08 14:32:24 +02001808 public BluetoothServerSocket listenUsingL2capOn(int port, boolean mitm, boolean min16DigitPin)
1809 throws IOException {
Casper Bonde238e0f92015-04-09 09:24:48 +02001810 BluetoothServerSocket socket = new BluetoothServerSocket(
Casper Bonde3b3d1fe2015-05-08 14:32:24 +02001811 BluetoothSocket.TYPE_L2CAP, true, true, port, mitm, min16DigitPin);
Casper Bonde238e0f92015-04-09 09:24:48 +02001812 int errno = socket.mSocket.bindListen();
1813 if(port == SOCKET_CHANNEL_AUTO_STATIC_NO_SDP) {
1814 socket.setChannel(socket.mSocket.getPort());
1815 }
1816 if (errno != 0) {
1817 //TODO(BT): Throw the same exception error code
1818 // that the previous code was using.
1819 //socket.mSocket.throwErrnoNative(errno);
1820 throw new IOException("Error: " + errno);
1821 }
1822 return socket;
1823 }
1824
1825 /**
Casper Bonde23284232015-04-21 13:12:05 +02001826 * Construct an encrypted, authenticated, L2CAP server socket.
1827 * Call #accept to retrieve connections to this socket.
1828 * <p>To auto assign a port without creating a SDP record use
1829 * {@link SOCKET_CHANNEL_AUTO_STATIC_NO_SDP} as port number.
1830 * @param port the PSM to listen on
1831 * @return An L2CAP BluetoothServerSocket
1832 * @throws IOException On error, for example Bluetooth not available, or
1833 * insufficient permissions.
1834 * @hide
1835 */
1836 public BluetoothServerSocket listenUsingL2capOn(int port) throws IOException {
Casper Bonde3b3d1fe2015-05-08 14:32:24 +02001837 return listenUsingL2capOn(port, false, false);
Casper Bonde23284232015-04-21 13:12:05 +02001838 }
1839
1840 /**
Jaikumar Ganeshcc5494c2010-09-09 15:37:57 -07001841 * Read the local Out of Band Pairing Data
1842 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
1843 *
1844 * @return Pair<byte[], byte[]> of Hash and Randomizer
1845 *
1846 * @hide
1847 */
1848 public Pair<byte[], byte[]> readOutOfBandData() {
1849 if (getState() != STATE_ON) return null;
Jaikumar Ganeshe4caddb2012-01-25 16:16:48 -08001850 //TODO(BT
1851 /*
Jaikumar Ganeshcc5494c2010-09-09 15:37:57 -07001852 try {
Jake Hambyf51eada2010-09-21 13:39:53 -07001853 byte[] hash;
1854 byte[] randomizer;
Jaikumar Ganeshcc5494c2010-09-09 15:37:57 -07001855
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001856 byte[] ret = null;
1857 mServiceLock.readLock().lock();
1858 if (mService != null) mService.readOutOfBandData();
Jaikumar Ganeshcc5494c2010-09-09 15:37:57 -07001859
1860 if (ret == null || ret.length != 32) return null;
1861
1862 hash = Arrays.copyOfRange(ret, 0, 16);
1863 randomizer = Arrays.copyOfRange(ret, 16, 32);
1864
1865 if (DBG) {
1866 Log.d(TAG, "readOutOfBandData:" + Arrays.toString(hash) +
1867 ":" + Arrays.toString(randomizer));
1868 }
1869 return new Pair<byte[], byte[]>(hash, randomizer);
1870
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001871 } catch (RemoteException e) {
1872 Log.e(TAG, "", e);
1873 } finally {
1874 mServiceLock.readLock().unlock();
1875 }
1876 */
Jaikumar Ganeshcc5494c2010-09-09 15:37:57 -07001877 return null;
1878 }
1879
Scott Main299ae672011-01-19 21:13:18 -08001880 /**
Jaikumar Ganesh62c37ef2010-08-24 17:36:13 -07001881 * Get the profile proxy object associated with the profile.
1882 *
Ganesh Ganapathi Batta99081122013-02-05 15:28:33 -08001883 * <p>Profile can be one of {@link BluetoothProfile#HEALTH}, {@link BluetoothProfile#HEADSET},
Matthew Xieddf7e472013-03-01 18:41:02 -08001884 * {@link BluetoothProfile#A2DP}, {@link BluetoothProfile#GATT}, or
1885 * {@link BluetoothProfile#GATT_SERVER}. Clients must implement
Jaikumar Ganesh62c37ef2010-08-24 17:36:13 -07001886 * {@link BluetoothProfile.ServiceListener} to get notified of
1887 * the connection status and to get the proxy object.
1888 *
1889 * @param context Context of the application
1890 * @param listener The service Listener for connection callbacks.
Scott Main2d68a6b2011-09-26 22:59:38 -07001891 * @param profile The Bluetooth profile; either {@link BluetoothProfile#HEALTH},
Andre Eisenbachab258132015-05-04 13:28:04 -07001892 * {@link BluetoothProfile#HEADSET}, {@link BluetoothProfile#A2DP}.
1893 * {@link BluetoothProfile#GATT} or {@link BluetoothProfile#GATT_SERVER}.
Jaikumar Ganesh62c37ef2010-08-24 17:36:13 -07001894 * @return true on success, false on error
1895 */
1896 public boolean getProfileProxy(Context context, BluetoothProfile.ServiceListener listener,
1897 int profile) {
1898 if (context == null || listener == null) return false;
1899
1900 if (profile == BluetoothProfile.HEADSET) {
1901 BluetoothHeadset headset = new BluetoothHeadset(context, listener);
1902 return true;
1903 } else if (profile == BluetoothProfile.A2DP) {
1904 BluetoothA2dp a2dp = new BluetoothA2dp(context, listener);
1905 return true;
Mike Lockwood2263dd12014-05-14 09:51:30 -07001906 } else if (profile == BluetoothProfile.A2DP_SINK) {
1907 BluetoothA2dpSink a2dpSink = new BluetoothA2dpSink(context, listener);
1908 return true;
Mike Lockwood94b59de2014-06-02 16:20:37 -07001909 } else if (profile == BluetoothProfile.AVRCP_CONTROLLER) {
1910 BluetoothAvrcpController avrcp = new BluetoothAvrcpController(context, listener);
1911 return true;
Jaikumar Ganesh4ab0e772011-02-18 14:52:32 -08001912 } else if (profile == BluetoothProfile.INPUT_DEVICE) {
1913 BluetoothInputDevice iDev = new BluetoothInputDevice(context, listener);
1914 return true;
Jaikumar Ganesh74ef1192011-02-23 10:22:15 -08001915 } else if (profile == BluetoothProfile.PAN) {
1916 BluetoothPan pan = new BluetoothPan(context, listener);
1917 return true;
Jaikumar Ganesh2ea1e852011-04-01 16:33:09 -07001918 } else if (profile == BluetoothProfile.HEALTH) {
1919 BluetoothHealth health = new BluetoothHealth(context, listener);
1920 return true;
Kim Schulz0d376052013-08-22 11:18:02 +02001921 } else if (profile == BluetoothProfile.MAP) {
1922 BluetoothMap map = new BluetoothMap(context, listener);
1923 return true;
Mike Lockwoodcf916d32014-06-12 11:23:40 -07001924 } else if (profile == BluetoothProfile.HEADSET_CLIENT) {
1925 BluetoothHeadsetClient headsetClient = new BluetoothHeadsetClient(context, listener);
Hemant Gupta7aca90f2013-08-19 19:03:51 +05301926 return true;
Casper Bonde2a5f6082015-03-19 10:36:45 +01001927 } else if (profile == BluetoothProfile.SAP) {
1928 BluetoothSap sap = new BluetoothSap(context, listener);
1929 return true;
Joseph Pirozzocfa8a642016-03-04 13:02:54 -08001930 } else if (profile == BluetoothProfile.PBAP_CLIENT) {
1931 BluetoothPbapClient pbapClient = new BluetoothPbapClient(context, listener);
1932 return true;
Joseph Pirozzo631768d2016-09-01 14:19:28 -07001933 } else if (profile == BluetoothProfile.MAP_CLIENT) {
1934 BluetoothMapClient mapClient = new BluetoothMapClient(context, listener);
1935 return true;
Jaikumar Ganesh62c37ef2010-08-24 17:36:13 -07001936 } else {
1937 return false;
1938 }
1939 }
1940
1941 /**
1942 * Close the connection of the profile proxy to the Service.
1943 *
1944 * <p> Clients should call this when they are no longer using
1945 * the proxy obtained from {@link #getProfileProxy}.
Scott Main2d68a6b2011-09-26 22:59:38 -07001946 * Profile can be one of {@link BluetoothProfile#HEALTH}, {@link BluetoothProfile#HEADSET} or
Jaikumar Ganesh62c37ef2010-08-24 17:36:13 -07001947 * {@link BluetoothProfile#A2DP}
1948 *
1949 * @param profile
1950 * @param proxy Profile proxy object
1951 */
1952 public void closeProfileProxy(int profile, BluetoothProfile proxy) {
Jaikumar Ganesh9bb27512011-11-28 09:59:08 -08001953 if (proxy == null) return;
1954
1955 switch (profile) {
1956 case BluetoothProfile.HEADSET:
1957 BluetoothHeadset headset = (BluetoothHeadset)proxy;
Jaikumar Ganesh62c37ef2010-08-24 17:36:13 -07001958 headset.close();
Jaikumar Ganesh9bb27512011-11-28 09:59:08 -08001959 break;
1960 case BluetoothProfile.A2DP:
1961 BluetoothA2dp a2dp = (BluetoothA2dp)proxy;
1962 a2dp.close();
1963 break;
Mike Lockwood2263dd12014-05-14 09:51:30 -07001964 case BluetoothProfile.A2DP_SINK:
1965 BluetoothA2dpSink a2dpSink = (BluetoothA2dpSink)proxy;
1966 a2dpSink.close();
1967 break;
Mike Lockwood94b59de2014-06-02 16:20:37 -07001968 case BluetoothProfile.AVRCP_CONTROLLER:
1969 BluetoothAvrcpController avrcp = (BluetoothAvrcpController)proxy;
1970 avrcp.close();
1971 break;
Jaikumar Ganesh9bb27512011-11-28 09:59:08 -08001972 case BluetoothProfile.INPUT_DEVICE:
1973 BluetoothInputDevice iDev = (BluetoothInputDevice)proxy;
1974 iDev.close();
1975 break;
1976 case BluetoothProfile.PAN:
1977 BluetoothPan pan = (BluetoothPan)proxy;
1978 pan.close();
1979 break;
1980 case BluetoothProfile.HEALTH:
1981 BluetoothHealth health = (BluetoothHealth)proxy;
1982 health.close();
1983 break;
Ganesh Ganapathi Batta99081122013-02-05 15:28:33 -08001984 case BluetoothProfile.GATT:
1985 BluetoothGatt gatt = (BluetoothGatt)proxy;
1986 gatt.close();
1987 break;
1988 case BluetoothProfile.GATT_SERVER:
1989 BluetoothGattServer gattServer = (BluetoothGattServer)proxy;
1990 gattServer.close();
1991 break;
Kim Schulz0d376052013-08-22 11:18:02 +02001992 case BluetoothProfile.MAP:
1993 BluetoothMap map = (BluetoothMap)proxy;
1994 map.close();
1995 break;
Mike Lockwoodcf916d32014-06-12 11:23:40 -07001996 case BluetoothProfile.HEADSET_CLIENT:
1997 BluetoothHeadsetClient headsetClient = (BluetoothHeadsetClient)proxy;
1998 headsetClient.close();
Hemant Gupta7aca90f2013-08-19 19:03:51 +05301999 break;
Casper Bonde2a5f6082015-03-19 10:36:45 +01002000 case BluetoothProfile.SAP:
2001 BluetoothSap sap = (BluetoothSap)proxy;
2002 sap.close();
2003 break;
Joseph Pirozzocfa8a642016-03-04 13:02:54 -08002004 case BluetoothProfile.PBAP_CLIENT:
2005 BluetoothPbapClient pbapClient = (BluetoothPbapClient)proxy;
2006 pbapClient.close();
2007 break;
Joseph Pirozzo631768d2016-09-01 14:19:28 -07002008 case BluetoothProfile.MAP_CLIENT:
2009 BluetoothMapClient mapClient = (BluetoothMapClient)proxy;
2010 mapClient.close();
2011 break;
Jaikumar Ganesh62c37ef2010-08-24 17:36:13 -07002012 }
2013 }
2014
fredc0f420372012-04-12 00:02:00 -07002015 final private IBluetoothManagerCallback mManagerCallback =
2016 new IBluetoothManagerCallback.Stub() {
2017 public void onBluetoothServiceUp(IBluetooth bluetoothService) {
Marie Janssen9fa24912016-10-18 10:04:24 -07002018 if (DBG) Log.d(TAG, "onBluetoothServiceUp: " + bluetoothService);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07002019
2020 mServiceLock.writeLock().lock();
2021 mService = bluetoothService;
2022 mServiceLock.writeLock().unlock();
2023
2024 synchronized (mProxyServiceStateCallbacks) {
2025 for (IBluetoothManagerCallback cb : mProxyServiceStateCallbacks ) {
2026 try {
2027 if (cb != null) {
2028 cb.onBluetoothServiceUp(bluetoothService);
2029 } else {
2030 Log.d(TAG, "onBluetoothServiceUp: cb is null!!!");
2031 }
2032 } catch (Exception e) {
2033 Log.e(TAG,"",e);
Matthew Xie60675b22015-02-06 14:09:54 -08002034 }
fredc903ac6f2012-04-24 03:59:57 -07002035 }
fredc0f420372012-04-12 00:02:00 -07002036 }
2037 }
2038
2039 public void onBluetoothServiceDown() {
Marie Janssen9fa24912016-10-18 10:04:24 -07002040 if (DBG) Log.d(TAG, "onBluetoothServiceDown: " + mService);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07002041
Pavlin Radoslavove957a8a2016-05-24 15:28:41 -07002042 try {
2043 mServiceLock.writeLock().lock();
2044 mService = null;
2045 if (mLeScanClients != null) mLeScanClients.clear();
2046 if (sBluetoothLeAdvertiser != null) sBluetoothLeAdvertiser.cleanup();
2047 if (sBluetoothLeScanner != null) sBluetoothLeScanner.cleanup();
2048 } finally {
2049 mServiceLock.writeLock().unlock();
2050 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07002051
2052 synchronized (mProxyServiceStateCallbacks) {
2053 for (IBluetoothManagerCallback cb : mProxyServiceStateCallbacks ){
2054 try {
2055 if (cb != null) {
2056 cb.onBluetoothServiceDown();
2057 } else {
2058 Log.d(TAG, "onBluetoothServiceDown: cb is null!!!");
2059 }
2060 } catch (Exception e) {
2061 Log.e(TAG,"",e);
Matthew Xie60675b22015-02-06 14:09:54 -08002062 }
fredc903ac6f2012-04-24 03:59:57 -07002063 }
fredc0f420372012-04-12 00:02:00 -07002064 }
2065 }
Nitin Arorad055adb2015-03-02 15:03:51 -08002066
2067 public void onBrEdrDown() {
Marie Janssen9fa24912016-10-18 10:04:24 -07002068 if (DBG) Log.i(TAG, "onBrEdrDown:");
Nitin Arorad055adb2015-03-02 15:03:51 -08002069 }
fredc0f420372012-04-12 00:02:00 -07002070 };
2071
Jaikumar Ganeshef2cb7c2011-07-21 18:13:38 -07002072 /**
Martijn Coenen6c614b72012-04-18 13:01:15 -07002073 * Enable the Bluetooth Adapter, but don't auto-connect devices
2074 * and don't persist state. Only for use by system applications.
2075 * @hide
2076 */
2077 public boolean enableNoAutoConnect() {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07002078 if (isEnabled() == true){
2079 if (DBG) Log.d(TAG, "enableNoAutoConnect(): BT is already enabled..!");
2080 return true;
2081 }
2082 try {
2083 return mManagerService.enableNoAutoConnect();
2084 } catch (RemoteException e) {Log.e(TAG, "", e);}
2085 return false;
Martijn Coenen6c614b72012-04-18 13:01:15 -07002086 }
2087
2088 /**
Jaikumar Ganeshef2cb7c2011-07-21 18:13:38 -07002089 * Enable control of the Bluetooth Adapter for a single application.
2090 *
2091 * <p>Some applications need to use Bluetooth for short periods of time to
2092 * transfer data but don't want all the associated implications like
2093 * automatic connection to headsets etc.
2094 *
2095 * <p> Multiple applications can call this. This is reference counted and
2096 * Bluetooth disabled only when no one else is using it. There will be no UI
2097 * shown to the user while bluetooth is being enabled. Any user action will
2098 * override this call. For example, if user wants Bluetooth on and the last
2099 * user of this API wanted to disable Bluetooth, Bluetooth will not be
2100 * turned off.
2101 *
2102 * <p> This API is only meant to be used by internal applications. Third
2103 * party applications but use {@link #enable} and {@link #disable} APIs.
2104 *
2105 * <p> If this API returns true, it means the callback will be called.
2106 * The callback will be called with the current state of Bluetooth.
2107 * If the state is not what was requested, an internal error would be the
Jaikumar Ganeshf5fb6c82011-08-03 14:17:22 -07002108 * reason. If Bluetooth is already on and if this function is called to turn
2109 * it on, the api will return true and a callback will be called.
2110 *
2111 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
Jaikumar Ganeshef2cb7c2011-07-21 18:13:38 -07002112 *
2113 * @param on True for on, false for off.
2114 * @param callback The callback to notify changes to the state.
2115 * @hide
2116 */
2117 public boolean changeApplicationBluetoothState(boolean on,
2118 BluetoothStateChangeCallback callback) {
2119 if (callback == null) return false;
2120
Jaikumar Ganeshe4caddb2012-01-25 16:16:48 -08002121 //TODO(BT)
2122 /*
Jaikumar Ganeshef2cb7c2011-07-21 18:13:38 -07002123 try {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07002124 mServiceLock.readLock().lock();
2125 if (mService != null) {
2126 return mService.changeApplicationBluetoothState(on, new
Jaikumar Ganeshef2cb7c2011-07-21 18:13:38 -07002127 StateChangeCallbackWrapper(callback), new Binder());
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07002128 }
Jaikumar Ganeshef2cb7c2011-07-21 18:13:38 -07002129 } catch (RemoteException e) {
2130 Log.e(TAG, "changeBluetoothState", e);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07002131 } finally {
2132 mServiceLock.readLock().unlock();
2133 }
2134 */
Jaikumar Ganeshef2cb7c2011-07-21 18:13:38 -07002135 return false;
2136 }
2137
2138 /**
2139 * @hide
2140 */
2141 public interface BluetoothStateChangeCallback {
2142 public void onBluetoothStateChange(boolean on);
2143 }
2144
2145 /**
2146 * @hide
2147 */
2148 public class StateChangeCallbackWrapper extends IBluetoothStateChangeCallback.Stub {
2149 private BluetoothStateChangeCallback mCallback;
2150
2151 StateChangeCallbackWrapper(BluetoothStateChangeCallback
2152 callback) {
2153 mCallback = callback;
2154 }
2155
2156 @Override
2157 public void onBluetoothStateChange(boolean on) {
2158 mCallback.onBluetoothStateChange(on);
2159 }
2160 }
2161
Jaikumar Ganeshe4caddb2012-01-25 16:16:48 -08002162 private Set<BluetoothDevice> toDeviceSet(BluetoothDevice[] devices) {
2163 Set<BluetoothDevice> deviceSet = new HashSet<BluetoothDevice>(Arrays.asList(devices));
2164 return Collections.unmodifiableSet(deviceSet);
Nick Pellybd022f42009-08-14 18:33:38 -07002165 }
Nick Pelly005b2282009-09-10 10:21:56 -07002166
fredc0f420372012-04-12 00:02:00 -07002167 protected void finalize() throws Throwable {
2168 try {
2169 mManagerService.unregisterAdapter(mManagerCallback);
2170 } catch (RemoteException e) {
2171 Log.e(TAG, "", e);
2172 } finally {
2173 super.finalize();
2174 }
2175 }
2176
2177
Nick Pelly005b2282009-09-10 10:21:56 -07002178 /**
Nick Pelly75596b42011-12-07 15:03:55 -08002179 * Validate a String Bluetooth address, such as "00:43:A8:23:10:F0"
Nick Pelly55e66f12009-09-18 11:37:06 -07002180 * <p>Alphabetic characters must be uppercase to be valid.
Nick Pelly005b2282009-09-10 10:21:56 -07002181 *
2182 * @param address Bluetooth address as string
2183 * @return true if the address is valid, false otherwise
2184 */
2185 public static boolean checkBluetoothAddress(String address) {
2186 if (address == null || address.length() != ADDRESS_LENGTH) {
2187 return false;
2188 }
2189 for (int i = 0; i < ADDRESS_LENGTH; i++) {
2190 char c = address.charAt(i);
2191 switch (i % 3) {
2192 case 0:
2193 case 1:
Nick Pelly55e66f12009-09-18 11:37:06 -07002194 if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F')) {
2195 // hex character, OK
2196 break;
Nick Pelly005b2282009-09-10 10:21:56 -07002197 }
2198 return false;
2199 case 2:
2200 if (c == ':') {
2201 break; // OK
2202 }
2203 return false;
2204 }
2205 }
2206 return true;
2207 }
fredc0f420372012-04-12 00:02:00 -07002208
2209 /*package*/ IBluetoothManager getBluetoothManager() {
2210 return mManagerService;
2211 }
2212
Matthew Xie60675b22015-02-06 14:09:54 -08002213 final private ArrayList<IBluetoothManagerCallback> mProxyServiceStateCallbacks = new ArrayList<IBluetoothManagerCallback>();
fredcd6883532012-04-25 17:46:13 -07002214
fredc903ac6f2012-04-24 03:59:57 -07002215 /*package*/ IBluetooth getBluetoothService(IBluetoothManagerCallback cb) {
Matthew Xie60675b22015-02-06 14:09:54 -08002216 synchronized (mProxyServiceStateCallbacks) {
fredcd6883532012-04-25 17:46:13 -07002217 if (cb == null) {
fredcbf072a72012-05-09 16:52:50 -07002218 Log.w(TAG, "getBluetoothService() called with no BluetoothManagerCallback");
2219 } else if (!mProxyServiceStateCallbacks.contains(cb)) {
2220 mProxyServiceStateCallbacks.add(cb);
fredc903ac6f2012-04-24 03:59:57 -07002221 }
2222 }
2223 return mService;
2224 }
2225
2226 /*package*/ void removeServiceStateCallback(IBluetoothManagerCallback cb) {
Matthew Xie60675b22015-02-06 14:09:54 -08002227 synchronized (mProxyServiceStateCallbacks) {
fredcbf072a72012-05-09 16:52:50 -07002228 mProxyServiceStateCallbacks.remove(cb);
fredc0f420372012-04-12 00:02:00 -07002229 }
2230 }
Matthew Xieddf7e472013-03-01 18:41:02 -08002231
2232 /**
Matthew Xiecdd94e32013-04-11 16:36:26 -07002233 * Callback interface used to deliver LE scan results.
Matthew Xieddf7e472013-03-01 18:41:02 -08002234 *
Matthew Xiecdd94e32013-04-11 16:36:26 -07002235 * @see #startLeScan(LeScanCallback)
2236 * @see #startLeScan(UUID[], LeScanCallback)
Matthew Xieddf7e472013-03-01 18:41:02 -08002237 */
Matthew Xiecdd94e32013-04-11 16:36:26 -07002238 public interface LeScanCallback {
2239 /**
2240 * Callback reporting an LE device found during a device scan initiated
2241 * by the {@link BluetoothAdapter#startLeScan} function.
2242 *
2243 * @param device Identifies the remote device
2244 * @param rssi The RSSI value for the remote device as reported by the
2245 * Bluetooth hardware. 0 if no RSSI value is available.
2246 * @param scanRecord The content of the advertisement record offered by
2247 * the remote device.
2248 */
2249 public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord);
Matthew Xieddf7e472013-03-01 18:41:02 -08002250 }
2251
2252 /**
2253 * Starts a scan for Bluetooth LE devices.
2254 *
2255 * <p>Results of the scan are reported using the
Matthew Xiecdd94e32013-04-11 16:36:26 -07002256 * {@link LeScanCallback#onLeScan} callback.
Matthew Xieddf7e472013-03-01 18:41:02 -08002257 *
Matthew Xied5752332013-04-24 17:51:37 -07002258 * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN} permission.
Matthew Xieddf7e472013-03-01 18:41:02 -08002259 *
Matthew Xiecdd94e32013-04-11 16:36:26 -07002260 * @param callback the callback LE scan results are delivered
Matthew Xieddf7e472013-03-01 18:41:02 -08002261 * @return true, if the scan was started successfully
Wei Wangaf74e662014-07-09 14:03:42 -07002262 * @deprecated use {@link BluetoothLeScanner#startScan(List, ScanSettings, ScanCallback)}
2263 * instead.
Matthew Xieddf7e472013-03-01 18:41:02 -08002264 */
Wei Wangaf74e662014-07-09 14:03:42 -07002265 @Deprecated
Tor Norbye2d497522015-04-23 17:10:21 -07002266 @RequiresPermission(Manifest.permission.BLUETOOTH_ADMIN)
Matthew Xiecdd94e32013-04-11 16:36:26 -07002267 public boolean startLeScan(LeScanCallback callback) {
2268 return startLeScan(null, callback);
Matthew Xieddf7e472013-03-01 18:41:02 -08002269 }
2270
2271 /**
2272 * Starts a scan for Bluetooth LE devices, looking for devices that
2273 * advertise given services.
2274 *
2275 * <p>Devices which advertise all specified services are reported using the
Matthew Xiecdd94e32013-04-11 16:36:26 -07002276 * {@link LeScanCallback#onLeScan} callback.
Matthew Xieddf7e472013-03-01 18:41:02 -08002277 *
Matthew Xied5752332013-04-24 17:51:37 -07002278 * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN} permission.
Matthew Xieddf7e472013-03-01 18:41:02 -08002279 *
2280 * @param serviceUuids Array of services to look for
Matthew Xiecdd94e32013-04-11 16:36:26 -07002281 * @param callback the callback LE scan results are delivered
Matthew Xieddf7e472013-03-01 18:41:02 -08002282 * @return true, if the scan was started successfully
Wei Wangaf74e662014-07-09 14:03:42 -07002283 * @deprecated use {@link BluetoothLeScanner#startScan(List, ScanSettings, ScanCallback)}
2284 * instead.
Matthew Xieddf7e472013-03-01 18:41:02 -08002285 */
Wei Wangaf74e662014-07-09 14:03:42 -07002286 @Deprecated
Tor Norbye2d497522015-04-23 17:10:21 -07002287 @RequiresPermission(Manifest.permission.BLUETOOTH_ADMIN)
Wei Wangc3059cc2014-07-23 23:34:00 -07002288 public boolean startLeScan(final UUID[] serviceUuids, final LeScanCallback callback) {
Andreas Gampee6748ce2015-12-11 18:00:38 -08002289 if (DBG) Log.d(TAG, "startLeScan(): " + Arrays.toString(serviceUuids));
Matthew Xiecdd94e32013-04-11 16:36:26 -07002290 if (callback == null) {
2291 if (DBG) Log.e(TAG, "startLeScan: null callback");
Matthew Xieddf7e472013-03-01 18:41:02 -08002292 return false;
2293 }
Wei Wangc3059cc2014-07-23 23:34:00 -07002294 BluetoothLeScanner scanner = getBluetoothLeScanner();
2295 if (scanner == null) {
2296 if (DBG) Log.e(TAG, "startLeScan: cannot get BluetoothLeScanner");
2297 return false;
2298 }
Matthew Xieddf7e472013-03-01 18:41:02 -08002299
Matthew Xiecdd94e32013-04-11 16:36:26 -07002300 synchronized(mLeScanClients) {
2301 if (mLeScanClients.containsKey(callback)) {
2302 if (DBG) Log.e(TAG, "LE Scan has already started");
2303 return false;
2304 }
2305
2306 try {
2307 IBluetoothGatt iGatt = mManagerService.getBluetoothGatt();
Matthew Xie32ab77b2013-05-08 19:26:57 -07002308 if (iGatt == null) {
2309 // BLE is not supported
2310 return false;
2311 }
2312
Wei Wangc3059cc2014-07-23 23:34:00 -07002313 ScanCallback scanCallback = new ScanCallback() {
2314 @Override
2315 public void onScanResult(int callbackType, ScanResult result) {
2316 if (callbackType != ScanSettings.CALLBACK_TYPE_ALL_MATCHES) {
2317 // Should not happen.
2318 Log.e(TAG, "LE Scan has already started");
2319 return;
2320 }
2321 ScanRecord scanRecord = result.getScanRecord();
2322 if (scanRecord == null) {
2323 return;
2324 }
2325 if (serviceUuids != null) {
2326 List<ParcelUuid> uuids = new ArrayList<ParcelUuid>();
2327 for (UUID uuid : serviceUuids) {
2328 uuids.add(new ParcelUuid(uuid));
2329 }
2330 List<ParcelUuid> scanServiceUuids = scanRecord.getServiceUuids();
2331 if (scanServiceUuids == null || !scanServiceUuids.containsAll(uuids)) {
2332 if (DBG) Log.d(TAG, "uuids does not match");
2333 return;
2334 }
2335 }
2336 callback.onLeScan(result.getDevice(), result.getRssi(),
2337 scanRecord.getBytes());
2338 }
2339 };
2340 ScanSettings settings = new ScanSettings.Builder()
2341 .setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES)
2342 .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build();
2343
2344 List<ScanFilter> filters = new ArrayList<ScanFilter>();
2345 if (serviceUuids != null && serviceUuids.length > 0) {
2346 // Note scan filter does not support matching an UUID array so we put one
2347 // UUID to hardware and match the whole array in callback.
2348 ScanFilter filter = new ScanFilter.Builder().setServiceUuid(
2349 new ParcelUuid(serviceUuids[0])).build();
2350 filters.add(filter);
Matthew Xiecdd94e32013-04-11 16:36:26 -07002351 }
Wei Wangc3059cc2014-07-23 23:34:00 -07002352 scanner.startScan(filters, settings, scanCallback);
2353
2354 mLeScanClients.put(callback, scanCallback);
2355 return true;
2356
Matthew Xiecdd94e32013-04-11 16:36:26 -07002357 } catch (RemoteException e) {
2358 Log.e(TAG,"",e);
2359 }
2360 }
2361 return false;
Matthew Xieddf7e472013-03-01 18:41:02 -08002362 }
2363
2364 /**
2365 * Stops an ongoing Bluetooth LE device scan.
2366 *
Matthew Xied5752332013-04-24 17:51:37 -07002367 * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN} permission.
Matthew Xiecdd94e32013-04-11 16:36:26 -07002368 *
2369 * @param callback used to identify which scan to stop
2370 * must be the same handle used to start the scan
Wei Wangaf74e662014-07-09 14:03:42 -07002371 * @deprecated Use {@link BluetoothLeScanner#stopScan(ScanCallback)} instead.
Matthew Xieddf7e472013-03-01 18:41:02 -08002372 */
Wei Wangaf74e662014-07-09 14:03:42 -07002373 @Deprecated
Tor Norbye2d497522015-04-23 17:10:21 -07002374 @RequiresPermission(Manifest.permission.BLUETOOTH_ADMIN)
Matthew Xiecdd94e32013-04-11 16:36:26 -07002375 public void stopLeScan(LeScanCallback callback) {
2376 if (DBG) Log.d(TAG, "stopLeScan()");
Wei Wangc3059cc2014-07-23 23:34:00 -07002377 BluetoothLeScanner scanner = getBluetoothLeScanner();
2378 if (scanner == null) {
2379 return;
Matthew Xieddf7e472013-03-01 18:41:02 -08002380 }
Wei Wangc3059cc2014-07-23 23:34:00 -07002381 synchronized (mLeScanClients) {
2382 ScanCallback scanCallback = mLeScanClients.remove(callback);
2383 if (scanCallback == null) {
2384 if (DBG) Log.d(TAG, "scan not started yet");
2385 return;
Matthew Xieddf7e472013-03-01 18:41:02 -08002386 }
Wei Wangc3059cc2014-07-23 23:34:00 -07002387 scanner.stopScan(scanCallback);
Prerepa Viswanadham8f2e74c2014-07-09 12:51:59 -07002388 }
Matthew Xiecdd94e32013-04-11 16:36:26 -07002389 }
Nick Pellybd022f42009-08-14 18:33:38 -07002390}