blob: 5564af789e13eed062334b9315a78cd308826d7f [file] [log] [blame]
Nick Pellybd022f42009-08-14 18:33:38 -07001/*
Hemant Gupta7aca90f2013-08-19 19:03:51 +05302 * Copyright (C) 2009-2014 The Android Open Source Project
Nick Pellybd022f42009-08-14 18:33:38 -07003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.bluetooth;
18
Nick Pellyde893f52009-09-08 13:15:33 -070019import android.annotation.SdkConstant;
20import android.annotation.SdkConstant.SdkConstantType;
Wei Wang6d811182014-05-22 12:10:25 -070021import android.bluetooth.le.BluetoothLeAdvertiser;
22import android.bluetooth.le.BluetoothLeScanner;
Wei Wangaf74e662014-07-09 14:03:42 -070023import android.bluetooth.le.ScanCallback;
Wei Wangc3059cc2014-07-23 23:34:00 -070024import android.bluetooth.le.ScanFilter;
25import android.bluetooth.le.ScanRecord;
Wei Wang9fb17912014-07-01 15:10:06 -070026import android.bluetooth.le.ScanResult;
Wei Wangaf74e662014-07-09 14:03:42 -070027import android.bluetooth.le.ScanSettings;
Jaikumar Ganesh62c37ef2010-08-24 17:36:13 -070028import android.content.Context;
Wei Wangf3055892014-03-11 22:22:41 -070029import android.os.Handler;
Nick Pellyf242b7b2009-10-08 00:12:45 +020030import android.os.IBinder;
Wei Wangf3055892014-03-11 22:22:41 -070031import android.os.Looper;
Nick Pellyaef439e2009-09-28 12:33:17 -070032import android.os.ParcelUuid;
Nick Pellybd022f42009-08-14 18:33:38 -070033import android.os.RemoteException;
Nick Pellyf242b7b2009-10-08 00:12:45 +020034import android.os.ServiceManager;
Nick Pellybd022f42009-08-14 18:33:38 -070035import android.util.Log;
Jaikumar Ganeshcc5494c2010-09-09 15:37:57 -070036import android.util.Pair;
Wei Wang18c76932013-10-29 21:05:37 -070037
Nick Pellybd022f42009-08-14 18:33:38 -070038import java.io.IOException;
Matthew Xiecdd94e32013-04-11 16:36:26 -070039import java.lang.ref.WeakReference;
fredc903ac6f2012-04-24 03:59:57 -070040import java.util.ArrayList;
Jaikumar Ganeshcc5494c2010-09-09 15:37:57 -070041import java.util.Arrays;
Nick Pellybd022f42009-08-14 18:33:38 -070042import java.util.Collections;
Matthew Xiecdd94e32013-04-11 16:36:26 -070043import java.util.HashMap;
Wei Wang18c76932013-10-29 21:05:37 -070044import java.util.HashSet;
Wei Wang9fb17912014-07-01 15:10:06 -070045import java.util.List;
Jeff Sharkeyfea17de2013-06-11 14:13:09 -070046import java.util.Locale;
Matthew Xiecdd94e32013-04-11 16:36:26 -070047import java.util.Map;
Nick Pelly24bb9b82009-10-02 20:34:18 -070048import java.util.Set;
Nick Pelly16fb88a2009-10-07 07:44:03 +020049import java.util.UUID;
Nick Pellybd022f42009-08-14 18:33:38 -070050
51/**
Scott Main9fab0ae2009-11-03 18:17:59 -080052 * Represents the local device Bluetooth adapter. The {@link BluetoothAdapter}
53 * lets you perform fundamental Bluetooth tasks, such as initiate
54 * device discovery, query a list of bonded (paired) devices,
55 * instantiate a {@link BluetoothDevice} using a known MAC address, and create
56 * a {@link BluetoothServerSocket} to listen for connection requests from other
Matthew Xieb30f91e2013-05-29 10:19:06 -070057 * devices, and start a scan for Bluetooth LE devices.
Scott Main9fab0ae2009-11-03 18:17:59 -080058 *
59 * <p>To get a {@link BluetoothAdapter} representing the local Bluetooth
Kim Schulz0d376052013-08-22 11:18:02 +020060 * adapter, when running on JELLY_BEAN_MR1 and below, call the
Matthew Xieb30f91e2013-05-29 10:19:06 -070061 * static {@link #getDefaultAdapter} method; when running on JELLY_BEAN_MR2 and
62 * higher, retrieve it through
63 * {@link android.content.Context#getSystemService} with
64 * {@link android.content.Context#BLUETOOTH_SERVICE}.
Scott Main9fab0ae2009-11-03 18:17:59 -080065 * Fundamentally, this is your starting point for all
66 * Bluetooth actions. Once you have the local adapter, you can get a set of
67 * {@link BluetoothDevice} objects representing all paired devices with
68 * {@link #getBondedDevices()}; start device discovery with
69 * {@link #startDiscovery()}; or create a {@link BluetoothServerSocket} to
70 * listen for incoming connection requests with
Matthew Xieb30f91e2013-05-29 10:19:06 -070071 * {@link #listenUsingRfcommWithServiceRecord(String,UUID)}; or start a scan for
72 * Bluetooth LE devices with {@link #startLeScan(LeScanCallback callback)}.
Scott Main9fab0ae2009-11-03 18:17:59 -080073 *
74 * <p class="note"><strong>Note:</strong>
75 * Most methods require the {@link android.Manifest.permission#BLUETOOTH}
76 * permission and some also require the
77 * {@link android.Manifest.permission#BLUETOOTH_ADMIN} permission.
78 *
Joe Fernandez3aef8e12011-12-20 10:38:34 -080079 * <div class="special reference">
80 * <h3>Developer Guides</h3>
81 * <p>For more information about using Bluetooth, read the
82 * <a href="{@docRoot}guide/topics/wireless/bluetooth.html">Bluetooth</a> developer guide.</p>
83 * </div>
84 *
Scott Main9fab0ae2009-11-03 18:17:59 -080085 * {@see BluetoothDevice}
86 * {@see BluetoothServerSocket}
Nick Pellybd022f42009-08-14 18:33:38 -070087 */
88public final class BluetoothAdapter {
89 private static final String TAG = "BluetoothAdapter";
fredc0f420372012-04-12 00:02:00 -070090 private static final boolean DBG = true;
Matthew Xie3b6214f2012-08-29 00:12:29 -070091 private static final boolean VDBG = false;
Nick Pellybd022f42009-08-14 18:33:38 -070092
Nick Pellyde893f52009-09-08 13:15:33 -070093 /**
Nick Pellyb24e11b2009-09-08 17:40:43 -070094 * Sentinel error value for this class. Guaranteed to not equal any other
95 * integer constant in this class. Provided as a convenience for functions
96 * that require a sentinel error value, for example:
97 * <p><code>Intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
98 * BluetoothAdapter.ERROR)</code>
99 */
Nick Pelly005b2282009-09-10 10:21:56 -0700100 public static final int ERROR = Integer.MIN_VALUE;
Nick Pellyb24e11b2009-09-08 17:40:43 -0700101
102 /**
Nick Pellyde893f52009-09-08 13:15:33 -0700103 * Broadcast Action: The state of the local Bluetooth adapter has been
104 * changed.
105 * <p>For example, Bluetooth has been turned on or off.
Nick Pelly005b2282009-09-10 10:21:56 -0700106 * <p>Always contains the extra fields {@link #EXTRA_STATE} and {@link
Nick Pellyde893f52009-09-08 13:15:33 -0700107 * #EXTRA_PREVIOUS_STATE} containing the new and old states
108 * respectively.
109 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} to receive.
110 */
111 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
112 public static final String ACTION_STATE_CHANGED =
Nick Pelly005b2282009-09-10 10:21:56 -0700113 "android.bluetooth.adapter.action.STATE_CHANGED";
Nick Pellybd022f42009-08-14 18:33:38 -0700114
Nick Pellyde893f52009-09-08 13:15:33 -0700115 /**
116 * Used as an int extra field in {@link #ACTION_STATE_CHANGED}
117 * intents to request the current power state. Possible values are:
118 * {@link #STATE_OFF},
119 * {@link #STATE_TURNING_ON},
120 * {@link #STATE_ON},
121 * {@link #STATE_TURNING_OFF},
122 */
123 public static final String EXTRA_STATE =
Nick Pelly005b2282009-09-10 10:21:56 -0700124 "android.bluetooth.adapter.extra.STATE";
Nick Pellyde893f52009-09-08 13:15:33 -0700125 /**
126 * Used as an int extra field in {@link #ACTION_STATE_CHANGED}
127 * intents to request the previous power state. Possible values are:
128 * {@link #STATE_OFF},
129 * {@link #STATE_TURNING_ON},
130 * {@link #STATE_ON},
131 * {@link #STATE_TURNING_OFF},
132 */
133 public static final String EXTRA_PREVIOUS_STATE =
Nick Pelly005b2282009-09-10 10:21:56 -0700134 "android.bluetooth.adapter.extra.PREVIOUS_STATE";
Nick Pellybd022f42009-08-14 18:33:38 -0700135
Nick Pellyde893f52009-09-08 13:15:33 -0700136 /**
137 * Indicates the local Bluetooth adapter is off.
138 */
Nick Pelly005b2282009-09-10 10:21:56 -0700139 public static final int STATE_OFF = 10;
Nick Pellyde893f52009-09-08 13:15:33 -0700140 /**
141 * Indicates the local Bluetooth adapter is turning on. However local
142 * clients should wait for {@link #STATE_ON} before attempting to
143 * use the adapter.
144 */
Nick Pelly005b2282009-09-10 10:21:56 -0700145 public static final int STATE_TURNING_ON = 11;
Nick Pellyde893f52009-09-08 13:15:33 -0700146 /**
147 * Indicates the local Bluetooth adapter is on, and ready for use.
148 */
Nick Pelly005b2282009-09-10 10:21:56 -0700149 public static final int STATE_ON = 12;
Nick Pellyde893f52009-09-08 13:15:33 -0700150 /**
151 * Indicates the local Bluetooth adapter is turning off. Local clients
152 * should immediately attempt graceful disconnection of any remote links.
153 */
Nick Pelly005b2282009-09-10 10:21:56 -0700154 public static final int STATE_TURNING_OFF = 13;
Nick Pellyde893f52009-09-08 13:15:33 -0700155
156 /**
Nick Pelly18b1e792009-09-24 11:14:15 -0700157 * Activity Action: Show a system activity that requests discoverable mode.
Scott Main6d95fc02009-11-19 17:00:19 -0800158 * This activity will also request the user to turn on Bluetooth if it
Nick Pelly1acdcc12009-09-28 10:33:55 -0700159 * is not currently enabled.
Nick Pelly18b1e792009-09-24 11:14:15 -0700160 * <p>Discoverable mode is equivalent to {@link
161 * #SCAN_MODE_CONNECTABLE_DISCOVERABLE}. It allows remote devices to see
162 * this Bluetooth adapter when they perform a discovery.
Scott Main6d95fc02009-11-19 17:00:19 -0800163 * <p>For privacy, Android is not discoverable by default.
164 * <p>The sender of this Intent can optionally use extra field {@link
Nick Pelly18b1e792009-09-24 11:14:15 -0700165 * #EXTRA_DISCOVERABLE_DURATION} to request the duration of
166 * discoverability. Currently the default duration is 120 seconds, and
167 * maximum duration is capped at 300 seconds for each request.
168 * <p>Notification of the result of this activity is posted using the
169 * {@link android.app.Activity#onActivityResult} callback. The
170 * <code>resultCode</code>
Michael Chancdd28642009-11-05 18:29:01 -0800171 * will be the duration (in seconds) of discoverability or
172 * {@link android.app.Activity#RESULT_CANCELED} if the user rejected
173 * discoverability or an error has occurred.
Nick Pelly18b1e792009-09-24 11:14:15 -0700174 * <p>Applications can also listen for {@link #ACTION_SCAN_MODE_CHANGED}
Scott Main6d95fc02009-11-19 17:00:19 -0800175 * for global notification whenever the scan mode changes. For example, an
176 * application can be notified when the device has ended discoverability.
Nick Pelly1acdcc12009-09-28 10:33:55 -0700177 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
Nick Pelly18b1e792009-09-24 11:14:15 -0700178 */
179 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
180 public static final String ACTION_REQUEST_DISCOVERABLE =
181 "android.bluetooth.adapter.action.REQUEST_DISCOVERABLE";
182
183 /**
184 * Used as an optional int extra field in {@link
185 * #ACTION_REQUEST_DISCOVERABLE} intents to request a specific duration
186 * for discoverability in seconds. The current default is 120 seconds, and
187 * requests over 300 seconds will be capped. These values could change.
188 */
189 public static final String EXTRA_DISCOVERABLE_DURATION =
190 "android.bluetooth.adapter.extra.DISCOVERABLE_DURATION";
191
192 /**
Nick Pelly1acdcc12009-09-28 10:33:55 -0700193 * Activity Action: Show a system activity that allows the user to turn on
194 * Bluetooth.
195 * <p>This system activity will return once Bluetooth has completed turning
196 * on, or the user has decided not to turn Bluetooth on.
197 * <p>Notification of the result of this activity is posted using the
198 * {@link android.app.Activity#onActivityResult} callback. The
199 * <code>resultCode</code>
Michael Chancdd28642009-11-05 18:29:01 -0800200 * will be {@link android.app.Activity#RESULT_OK} if Bluetooth has been
201 * turned on or {@link android.app.Activity#RESULT_CANCELED} if the user
202 * has rejected the request or an error has occurred.
Nick Pelly1acdcc12009-09-28 10:33:55 -0700203 * <p>Applications can also listen for {@link #ACTION_STATE_CHANGED}
204 * for global notification whenever Bluetooth is turned on or off.
205 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
206 */
207 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
208 public static final String ACTION_REQUEST_ENABLE =
209 "android.bluetooth.adapter.action.REQUEST_ENABLE";
210
211 /**
Nick Pellyde893f52009-09-08 13:15:33 -0700212 * Broadcast Action: Indicates the Bluetooth scan mode of the local Adapter
213 * has changed.
Nick Pelly005b2282009-09-10 10:21:56 -0700214 * <p>Always contains the extra fields {@link #EXTRA_SCAN_MODE} and {@link
Nick Pellyde893f52009-09-08 13:15:33 -0700215 * #EXTRA_PREVIOUS_SCAN_MODE} containing the new and old scan modes
216 * respectively.
217 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
218 */
219 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
220 public static final String ACTION_SCAN_MODE_CHANGED =
Nick Pelly005b2282009-09-10 10:21:56 -0700221 "android.bluetooth.adapter.action.SCAN_MODE_CHANGED";
Nick Pellyde893f52009-09-08 13:15:33 -0700222
223 /**
224 * Used as an int extra field in {@link #ACTION_SCAN_MODE_CHANGED}
225 * intents to request the current scan mode. Possible values are:
226 * {@link #SCAN_MODE_NONE},
227 * {@link #SCAN_MODE_CONNECTABLE},
228 * {@link #SCAN_MODE_CONNECTABLE_DISCOVERABLE},
229 */
Nick Pelly005b2282009-09-10 10:21:56 -0700230 public static final String EXTRA_SCAN_MODE = "android.bluetooth.adapter.extra.SCAN_MODE";
Nick Pellyde893f52009-09-08 13:15:33 -0700231 /**
232 * Used as an int extra field in {@link #ACTION_SCAN_MODE_CHANGED}
233 * intents to request the previous scan mode. Possible values are:
234 * {@link #SCAN_MODE_NONE},
235 * {@link #SCAN_MODE_CONNECTABLE},
236 * {@link #SCAN_MODE_CONNECTABLE_DISCOVERABLE},
237 */
238 public static final String EXTRA_PREVIOUS_SCAN_MODE =
Nick Pelly005b2282009-09-10 10:21:56 -0700239 "android.bluetooth.adapter.extra.PREVIOUS_SCAN_MODE";
Nick Pellyde893f52009-09-08 13:15:33 -0700240
241 /**
242 * Indicates that both inquiry scan and page scan are disabled on the local
243 * Bluetooth adapter. Therefore this device is neither discoverable
244 * nor connectable from remote Bluetooth devices.
245 */
Nick Pelly005b2282009-09-10 10:21:56 -0700246 public static final int SCAN_MODE_NONE = 20;
Nick Pellyde893f52009-09-08 13:15:33 -0700247 /**
248 * Indicates that inquiry scan is disabled, but page scan is enabled on the
249 * local Bluetooth adapter. Therefore this device is not discoverable from
250 * remote Bluetooth devices, but is connectable from remote devices that
251 * have previously discovered this device.
252 */
Nick Pelly005b2282009-09-10 10:21:56 -0700253 public static final int SCAN_MODE_CONNECTABLE = 21;
Nick Pellyde893f52009-09-08 13:15:33 -0700254 /**
255 * Indicates that both inquiry scan and page scan are enabled on the local
256 * Bluetooth adapter. Therefore this device is both discoverable and
257 * connectable from remote Bluetooth devices.
258 */
Nick Pelly005b2282009-09-10 10:21:56 -0700259 public static final int SCAN_MODE_CONNECTABLE_DISCOVERABLE = 23;
Nick Pellybd022f42009-08-14 18:33:38 -0700260
Nick Pelly005b2282009-09-10 10:21:56 -0700261 /**
262 * Broadcast Action: The local Bluetooth adapter has started the remote
263 * device discovery process.
264 * <p>This usually involves an inquiry scan of about 12 seconds, followed
265 * by a page scan of each new device to retrieve its Bluetooth name.
266 * <p>Register for {@link BluetoothDevice#ACTION_FOUND} to be notified as
267 * remote Bluetooth devices are found.
268 * <p>Device discovery is a heavyweight procedure. New connections to
269 * remote Bluetooth devices should not be attempted while discovery is in
270 * progress, and existing connections will experience limited bandwidth
271 * and high latency. Use {@link #cancelDiscovery()} to cancel an ongoing
272 * discovery.
273 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} to receive.
274 */
275 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
276 public static final String ACTION_DISCOVERY_STARTED =
277 "android.bluetooth.adapter.action.DISCOVERY_STARTED";
278 /**
279 * Broadcast Action: The local Bluetooth adapter has finished the device
280 * discovery process.
281 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} to receive.
282 */
283 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
284 public static final String ACTION_DISCOVERY_FINISHED =
285 "android.bluetooth.adapter.action.DISCOVERY_FINISHED";
286
287 /**
288 * Broadcast Action: The local Bluetooth adapter has changed its friendly
289 * Bluetooth name.
290 * <p>This name is visible to remote Bluetooth devices.
291 * <p>Always contains the extra field {@link #EXTRA_LOCAL_NAME} containing
292 * the name.
293 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} to receive.
294 */
295 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
296 public static final String ACTION_LOCAL_NAME_CHANGED =
297 "android.bluetooth.adapter.action.LOCAL_NAME_CHANGED";
298 /**
299 * Used as a String extra field in {@link #ACTION_LOCAL_NAME_CHANGED}
300 * intents to request the local Bluetooth name.
301 */
302 public static final String EXTRA_LOCAL_NAME = "android.bluetooth.adapter.extra.LOCAL_NAME";
303
Jaikumar Ganesh62c37ef2010-08-24 17:36:13 -0700304 /**
305 * Intent used to broadcast the change in connection state of the local
306 * Bluetooth adapter to a profile of the remote device. When the adapter is
307 * not connected to any profiles of any remote devices and it attempts a
308 * connection to a profile this intent will sent. Once connected, this intent
309 * will not be sent for any more connection attempts to any profiles of any
310 * remote device. When the adapter disconnects from the last profile its
311 * connected to of any remote device, this intent will be sent.
312 *
313 * <p> This intent is useful for applications that are only concerned about
314 * whether the local adapter is connected to any profile of any device and
315 * are not really concerned about which profile. For example, an application
316 * which displays an icon to display whether Bluetooth is connected or not
317 * can use this intent.
318 *
319 * <p>This intent will have 3 extras:
Jaikumar Ganesh0b5b35f2011-02-01 16:47:11 -0800320 * {@link #EXTRA_CONNECTION_STATE} - The current connection state.
321 * {@link #EXTRA_PREVIOUS_CONNECTION_STATE}- The previous connection state.
Jaikumar Ganesh62c37ef2010-08-24 17:36:13 -0700322 * {@link BluetoothDevice#EXTRA_DEVICE} - The remote device.
323 *
Jaikumar Ganesh0b5b35f2011-02-01 16:47:11 -0800324 * {@link #EXTRA_CONNECTION_STATE} or {@link #EXTRA_PREVIOUS_CONNECTION_STATE}
325 * can be any of {@link #STATE_DISCONNECTED}, {@link #STATE_CONNECTING},
Jaikumar Ganesh62c37ef2010-08-24 17:36:13 -0700326 * {@link #STATE_CONNECTED}, {@link #STATE_DISCONNECTING}.
327 *
328 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} to receive.
329 */
330 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
331 public static final String ACTION_CONNECTION_STATE_CHANGED =
332 "android.bluetooth.adapter.action.CONNECTION_STATE_CHANGED";
333
334 /**
335 * Extra used by {@link #ACTION_CONNECTION_STATE_CHANGED}
336 *
337 * This extra represents the current connection state.
338 */
339 public static final String EXTRA_CONNECTION_STATE =
340 "android.bluetooth.adapter.extra.CONNECTION_STATE";
341
342 /**
343 * Extra used by {@link #ACTION_CONNECTION_STATE_CHANGED}
344 *
345 * This extra represents the previous connection state.
346 */
347 public static final String EXTRA_PREVIOUS_CONNECTION_STATE =
348 "android.bluetooth.adapter.extra.PREVIOUS_CONNECTION_STATE";
349
350 /** The profile is in disconnected state */
351 public static final int STATE_DISCONNECTED = 0;
352 /** The profile is in connecting state */
353 public static final int STATE_CONNECTING = 1;
354 /** The profile is in connected state */
355 public static final int STATE_CONNECTED = 2;
356 /** The profile is in disconnecting state */
357 public static final int STATE_DISCONNECTING = 3;
358
Nick Pellyf242b7b2009-10-08 00:12:45 +0200359 /** @hide */
fredc0f420372012-04-12 00:02:00 -0700360 public static final String BLUETOOTH_MANAGER_SERVICE = "bluetooth_manager";
Nick Pellyf242b7b2009-10-08 00:12:45 +0200361
Nick Pelly005b2282009-09-10 10:21:56 -0700362 private static final int ADDRESS_LENGTH = 17;
Nick Pellybd022f42009-08-14 18:33:38 -0700363
Prerepa Viswanadham8caac742014-07-22 17:00:09 -0700364 private static final int CONTROLLER_ENERGY_UPDATE_TIMEOUT_MILLIS = 30;
365 /** @hide */
366 public static final int ACTIVITY_ENERGY_INFO_CACHED = 0;
367 /** @hide */
368 public static final int ACTIVITY_ENERGY_INFO_REFRESHED = 1;
369
Nick Pellyf242b7b2009-10-08 00:12:45 +0200370 /**
Jake Hambyf51eada2010-09-21 13:39:53 -0700371 * Lazily initialized singleton. Guaranteed final after first object
Nick Pellyf242b7b2009-10-08 00:12:45 +0200372 * constructed.
373 */
374 private static BluetoothAdapter sAdapter;
375
Wei Wangc3059cc2014-07-23 23:34:00 -0700376 private static BluetoothLeScanner sBluetoothLeScanner;
377 private static BluetoothLeAdvertiser sBluetoothLeAdvertiser;
378
fredc0f420372012-04-12 00:02:00 -0700379 private final IBluetoothManager mManagerService;
380 private IBluetooth mService;
Nick Pellybd022f42009-08-14 18:33:38 -0700381
Wei Wangf3055892014-03-11 22:22:41 -0700382 private final Object mLock = new Object();
Wei Wangc3059cc2014-07-23 23:34:00 -0700383 private final Map<LeScanCallback, ScanCallback> mLeScanClients;
Matthew Xie484867a2011-08-25 16:45:58 -0700384
Nick Pellybd022f42009-08-14 18:33:38 -0700385 /**
Nick Pellyf242b7b2009-10-08 00:12:45 +0200386 * Get a handle to the default local Bluetooth adapter.
387 * <p>Currently Android only supports one Bluetooth adapter, but the API
388 * could be extended to support more. This will always return the default
389 * adapter.
390 * @return the default local adapter, or null if Bluetooth is not supported
391 * on this hardware platform
392 */
393 public static synchronized BluetoothAdapter getDefaultAdapter() {
394 if (sAdapter == null) {
fredc0f420372012-04-12 00:02:00 -0700395 IBinder b = ServiceManager.getService(BLUETOOTH_MANAGER_SERVICE);
Nick Pellyf242b7b2009-10-08 00:12:45 +0200396 if (b != null) {
fredc0f420372012-04-12 00:02:00 -0700397 IBluetoothManager managerService = IBluetoothManager.Stub.asInterface(b);
398 sAdapter = new BluetoothAdapter(managerService);
Jaikumar Ganeshe4caddb2012-01-25 16:16:48 -0800399 } else {
400 Log.e(TAG, "Bluetooth binder is null");
Nick Pellyf242b7b2009-10-08 00:12:45 +0200401 }
402 }
403 return sAdapter;
404 }
405
406 /**
407 * Use {@link #getDefaultAdapter} to get the BluetoothAdapter instance.
Nick Pellybd022f42009-08-14 18:33:38 -0700408 */
fredc0f420372012-04-12 00:02:00 -0700409 BluetoothAdapter(IBluetoothManager managerService) {
410
411 if (managerService == null) {
412 throw new IllegalArgumentException("bluetooth manager service is null");
Nick Pellybd022f42009-08-14 18:33:38 -0700413 }
fredc0f420372012-04-12 00:02:00 -0700414 try {
415 mService = managerService.registerAdapter(mManagerCallback);
416 } catch (RemoteException e) {Log.e(TAG, "", e);}
417 mManagerService = managerService;
Wei Wangc3059cc2014-07-23 23:34:00 -0700418 mLeScanClients = new HashMap<LeScanCallback, ScanCallback>();
Nick Pellybd022f42009-08-14 18:33:38 -0700419 }
420
421 /**
Nick Pelly45e27042009-08-19 11:00:00 -0700422 * Get a {@link BluetoothDevice} object for the given Bluetooth hardware
423 * address.
424 * <p>Valid Bluetooth hardware addresses must be upper case, in a format
Nick Pelly005b2282009-09-10 10:21:56 -0700425 * such as "00:11:22:33:AA:BB". The helper {@link #checkBluetoothAddress} is
426 * available to validate a Bluetooth address.
Nick Pelly45e27042009-08-19 11:00:00 -0700427 * <p>A {@link BluetoothDevice} will always be returned for a valid
428 * hardware address, even if this adapter has never seen that device.
Nick Pellyde893f52009-09-08 13:15:33 -0700429 *
Nick Pellybd022f42009-08-14 18:33:38 -0700430 * @param address valid Bluetooth MAC address
Nick Pelly45e27042009-08-19 11:00:00 -0700431 * @throws IllegalArgumentException if address is invalid
Nick Pellybd022f42009-08-14 18:33:38 -0700432 */
433 public BluetoothDevice getRemoteDevice(String address) {
434 return new BluetoothDevice(address);
435 }
436
437 /**
Nick Pelly75596b42011-12-07 15:03:55 -0800438 * Get a {@link BluetoothDevice} object for the given Bluetooth hardware
439 * address.
440 * <p>Valid Bluetooth hardware addresses must be 6 bytes. This method
441 * expects the address in network byte order (MSB first).
442 * <p>A {@link BluetoothDevice} will always be returned for a valid
443 * hardware address, even if this adapter has never seen that device.
444 *
445 * @param address Bluetooth MAC address (6 bytes)
446 * @throws IllegalArgumentException if address is invalid
447 */
448 public BluetoothDevice getRemoteDevice(byte[] address) {
449 if (address == null || address.length != 6) {
450 throw new IllegalArgumentException("Bluetooth address must have 6 bytes");
451 }
Jeff Sharkeyfea17de2013-06-11 14:13:09 -0700452 return new BluetoothDevice(String.format(Locale.US, "%02X:%02X:%02X:%02X:%02X:%02X",
Nick Pelly75596b42011-12-07 15:03:55 -0800453 address[0], address[1], address[2], address[3], address[4], address[5]));
454 }
455
456 /**
Prerepa Viswanadham248edc32014-10-15 16:36:01 -0700457 * Returns a {@link BluetoothLeAdvertiser} object for Bluetooth LE Advertising operations.
458 * Will return null if Bluetooth is turned off or if Bluetooth LE Advertising is not
459 * supported on this device.
Wei Wangc3059cc2014-07-23 23:34:00 -0700460 * <p>
461 * Use {@link #isMultipleAdvertisementSupported()} to check whether LE Advertising is supported
462 * on this device before calling this method.
Wei Wangadf6aff2014-05-20 06:30:20 +0000463 */
464 public BluetoothLeAdvertiser getBluetoothLeAdvertiser() {
Wei Wangc3059cc2014-07-23 23:34:00 -0700465 if (getState() != STATE_ON) {
466 return null;
467 }
468 if (!isMultipleAdvertisementSupported()) {
469 return null;
470 }
471 synchronized(mLock) {
472 if (sBluetoothLeAdvertiser == null) {
473 sBluetoothLeAdvertiser = new BluetoothLeAdvertiser(mManagerService);
474 }
475 }
476 return sBluetoothLeAdvertiser;
Wei Wangadf6aff2014-05-20 06:30:20 +0000477 }
478
479 /**
480 * Returns a {@link BluetoothLeScanner} object for Bluetooth LE scan operations.
481 */
482 public BluetoothLeScanner getBluetoothLeScanner() {
Wei Wangc3059cc2014-07-23 23:34:00 -0700483 if (getState() != STATE_ON) {
484 return null;
485 }
486 synchronized(mLock) {
487 if (sBluetoothLeScanner == null) {
488 sBluetoothLeScanner = new BluetoothLeScanner(mManagerService);
489 }
490 }
491 return sBluetoothLeScanner;
Wei Wangadf6aff2014-05-20 06:30:20 +0000492 }
493
494 /**
Nick Pellyde893f52009-09-08 13:15:33 -0700495 * Return true if Bluetooth is currently enabled and ready for use.
496 * <p>Equivalent to:
497 * <code>getBluetoothState() == STATE_ON</code>
498 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
Nick Pellybd022f42009-08-14 18:33:38 -0700499 *
Nick Pellyde893f52009-09-08 13:15:33 -0700500 * @return true if the local adapter is turned on
Nick Pellybd022f42009-08-14 18:33:38 -0700501 */
502 public boolean isEnabled() {
fredc0f420372012-04-12 00:02:00 -0700503
Nick Pellybd022f42009-08-14 18:33:38 -0700504 try {
fredc0f420372012-04-12 00:02:00 -0700505 synchronized(mManagerCallback) {
506 if (mService != null) return mService.isEnabled();
507 }
Nick Pellybd022f42009-08-14 18:33:38 -0700508 } catch (RemoteException e) {Log.e(TAG, "", e);}
509 return false;
510 }
511
512 /**
Nick Pellyde893f52009-09-08 13:15:33 -0700513 * Get the current state of the local Bluetooth adapter.
514 * <p>Possible return values are
515 * {@link #STATE_OFF},
516 * {@link #STATE_TURNING_ON},
517 * {@link #STATE_ON},
518 * {@link #STATE_TURNING_OFF}.
519 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
Nick Pellybd022f42009-08-14 18:33:38 -0700520 *
Nick Pellyde893f52009-09-08 13:15:33 -0700521 * @return current state of Bluetooth adapter
Nick Pellybd022f42009-08-14 18:33:38 -0700522 */
Nick Pellyde893f52009-09-08 13:15:33 -0700523 public int getState() {
Nick Pellybd022f42009-08-14 18:33:38 -0700524 try {
fredc0f420372012-04-12 00:02:00 -0700525 synchronized(mManagerCallback) {
526 if (mService != null)
527 {
fredcbf072a72012-05-09 16:52:50 -0700528 int state= mService.getState();
Matthew Xie3b6214f2012-08-29 00:12:29 -0700529 if (VDBG) Log.d(TAG, "" + hashCode() + ": getState(). Returning " + state);
fredcbf072a72012-05-09 16:52:50 -0700530 return state;
fredc0f420372012-04-12 00:02:00 -0700531 }
532 // TODO(BT) there might be a small gap during STATE_TURNING_ON that
533 // mService is null, handle that case
534 }
Nick Pellybd022f42009-08-14 18:33:38 -0700535 } catch (RemoteException e) {Log.e(TAG, "", e);}
fredcbf072a72012-05-09 16:52:50 -0700536 if (DBG) Log.d(TAG, "" + hashCode() + ": getState() : mService = null. Returning STATE_OFF");
Nick Pellyde893f52009-09-08 13:15:33 -0700537 return STATE_OFF;
Nick Pellybd022f42009-08-14 18:33:38 -0700538 }
539
540 /**
Scott Mained2a70d2009-12-09 16:07:39 -0800541 * Turn on the local Bluetooth adapter&mdash;do not use without explicit
542 * user action to turn on Bluetooth.
Nick Pellyde893f52009-09-08 13:15:33 -0700543 * <p>This powers on the underlying Bluetooth hardware, and starts all
544 * Bluetooth system services.
Scott Mained2a70d2009-12-09 16:07:39 -0800545 * <p class="caution"><strong>Bluetooth should never be enabled without
546 * direct user consent</strong>. If you want to turn on Bluetooth in order
547 * to create a wireless connection, you should use the {@link
548 * #ACTION_REQUEST_ENABLE} Intent, which will raise a dialog that requests
549 * user permission to turn on Bluetooth. The {@link #enable()} method is
550 * provided only for applications that include a user interface for changing
551 * system settings, such as a "power manager" app.</p>
Brad Fitzpatrick3219ab42009-09-25 16:31:39 +0400552 * <p>This is an asynchronous call: it will return immediately, and
Nick Pellyde893f52009-09-08 13:15:33 -0700553 * clients should listen for {@link #ACTION_STATE_CHANGED}
554 * to be notified of subsequent adapter state changes. If this call returns
555 * true, then the adapter state will immediately transition from {@link
556 * #STATE_OFF} to {@link #STATE_TURNING_ON}, and some time
557 * later transition to either {@link #STATE_OFF} or {@link
558 * #STATE_ON}. If this call returns false then there was an
559 * immediate problem that will prevent the adapter from being turned on -
560 * such as Airplane mode, or the adapter is already turned on.
Scott Mained2a70d2009-12-09 16:07:39 -0800561 * <p>Requires the {@link android.Manifest.permission#BLUETOOTH_ADMIN}
562 * permission
Nick Pellyde893f52009-09-08 13:15:33 -0700563 *
564 * @return true to indicate adapter startup has begun, or false on
565 * immediate error
Nick Pellybd022f42009-08-14 18:33:38 -0700566 */
567 public boolean enable() {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700568 if (isEnabled() == true){
569 if (DBG) Log.d(TAG, "enable(): BT is already enabled..!");
570 return true;
571 }
Nick Pellybd022f42009-08-14 18:33:38 -0700572 try {
Kausik Sinnaswamya097f512012-04-16 16:38:27 +0530573 return mManagerService.enable();
Nick Pellybd022f42009-08-14 18:33:38 -0700574 } catch (RemoteException e) {Log.e(TAG, "", e);}
575 return false;
576 }
577
578 /**
Scott Mained2a70d2009-12-09 16:07:39 -0800579 * Turn off the local Bluetooth adapter&mdash;do not use without explicit
580 * user action to turn off Bluetooth.
Nick Pellyde893f52009-09-08 13:15:33 -0700581 * <p>This gracefully shuts down all Bluetooth connections, stops Bluetooth
582 * system services, and powers down the underlying Bluetooth hardware.
Jake Hambyf51eada2010-09-21 13:39:53 -0700583 * <p class="caution"><strong>Bluetooth should never be disabled without
Scott Mained2a70d2009-12-09 16:07:39 -0800584 * direct user consent</strong>. The {@link #disable()} method is
585 * provided only for applications that include a user interface for changing
586 * system settings, such as a "power manager" app.</p>
Brad Fitzpatrick3219ab42009-09-25 16:31:39 +0400587 * <p>This is an asynchronous call: it will return immediately, and
Nick Pellyde893f52009-09-08 13:15:33 -0700588 * clients should listen for {@link #ACTION_STATE_CHANGED}
589 * to be notified of subsequent adapter state changes. If this call returns
590 * true, then the adapter state will immediately transition from {@link
591 * #STATE_ON} to {@link #STATE_TURNING_OFF}, and some time
592 * later transition to either {@link #STATE_OFF} or {@link
593 * #STATE_ON}. If this call returns false then there was an
594 * immediate problem that will prevent the adapter from being turned off -
595 * such as the adapter already being turned off.
Scott Mained2a70d2009-12-09 16:07:39 -0800596 * <p>Requires the {@link android.Manifest.permission#BLUETOOTH_ADMIN}
597 * permission
Nick Pellybd022f42009-08-14 18:33:38 -0700598 *
Nick Pellyde893f52009-09-08 13:15:33 -0700599 * @return true to indicate adapter shutdown has begun, or false on
600 * immediate error
Nick Pellybd022f42009-08-14 18:33:38 -0700601 */
602 public boolean disable() {
603 try {
fredc0f420372012-04-12 00:02:00 -0700604 return mManagerService.disable(true);
Jaikumar Ganeshe21a4ac2012-03-06 17:15:16 -0800605 } catch (RemoteException e) {Log.e(TAG, "", e);}
606 return false;
607 }
608
609 /**
610 * Turn off the local Bluetooth adapter and don't persist the setting.
611 *
612 * <p>Requires the {@link android.Manifest.permission#BLUETOOTH_ADMIN}
613 * permission
614 *
615 * @return true to indicate adapter shutdown has begun, or false on
616 * immediate error
617 * @hide
618 */
619 public boolean disable(boolean persist) {
fredc0f420372012-04-12 00:02:00 -0700620
Jaikumar Ganeshe21a4ac2012-03-06 17:15:16 -0800621 try {
fredc0f420372012-04-12 00:02:00 -0700622 return mManagerService.disable(persist);
Nick Pellybd022f42009-08-14 18:33:38 -0700623 } catch (RemoteException e) {Log.e(TAG, "", e);}
624 return false;
625 }
626
Nick Pellyde893f52009-09-08 13:15:33 -0700627 /**
628 * Returns the hardware address of the local Bluetooth adapter.
629 * <p>For example, "00:11:22:AA:BB:CC".
630 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
631 *
632 * @return Bluetooth hardware address as string
633 */
Nick Pellybd022f42009-08-14 18:33:38 -0700634 public String getAddress() {
635 try {
fredc0f420372012-04-12 00:02:00 -0700636 return mManagerService.getAddress();
Nick Pellybd022f42009-08-14 18:33:38 -0700637 } catch (RemoteException e) {Log.e(TAG, "", e);}
638 return null;
639 }
640
641 /**
Nick Pellyde893f52009-09-08 13:15:33 -0700642 * Get the friendly Bluetooth name of the local Bluetooth adapter.
643 * <p>This name is visible to remote Bluetooth devices.
644 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
Nick Pellybd022f42009-08-14 18:33:38 -0700645 *
Nick Pellyde893f52009-09-08 13:15:33 -0700646 * @return the Bluetooth name, or null on error
Nick Pellybd022f42009-08-14 18:33:38 -0700647 */
648 public String getName() {
649 try {
fredc116d1d42012-04-20 14:47:08 -0700650 return mManagerService.getName();
Nick Pellybd022f42009-08-14 18:33:38 -0700651 } catch (RemoteException e) {Log.e(TAG, "", e);}
652 return null;
653 }
654
655 /**
Zhihai Xuaf5971e2013-06-10 20:28:31 -0700656 * enable or disable Bluetooth HCI snoop log.
657 *
658 * <p>Requires the {@link android.Manifest.permission#BLUETOOTH_ADMIN}
659 * permission
660 *
661 * @return true to indicate configure HCI log successfully, or false on
662 * immediate error
663 * @hide
664 */
665 public boolean configHciSnoopLog(boolean enable) {
666 try {
667 synchronized(mManagerCallback) {
668 if (mService != null) return mService.configHciSnoopLog(enable);
669 }
670 } catch (RemoteException e) {Log.e(TAG, "", e);}
671 return false;
672 }
673
674 /**
Jaikumar Ganesh58b93c32010-11-23 20:03:10 -0800675 * Get the UUIDs supported by the local Bluetooth adapter.
676 *
677 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
678 *
679 * @return the UUIDs supported by the local Bluetooth Adapter.
680 * @hide
681 */
682 public ParcelUuid[] getUuids() {
Matthew Xie44b58ab2011-11-16 12:27:57 -0800683 if (getState() != STATE_ON) return null;
Jaikumar Ganesh58b93c32010-11-23 20:03:10 -0800684 try {
fredc0f420372012-04-12 00:02:00 -0700685 synchronized(mManagerCallback) {
686 if (mService != null) return mService.getUuids();
687 }
Jaikumar Ganesh58b93c32010-11-23 20:03:10 -0800688 } catch (RemoteException e) {Log.e(TAG, "", e);}
689 return null;
690 }
691
692 /**
Jake Hamby0f584302010-09-16 18:12:51 -0700693 * Set the friendly Bluetooth name of the local Bluetooth adapter.
Nick Pellyde893f52009-09-08 13:15:33 -0700694 * <p>This name is visible to remote Bluetooth devices.
Jake Hamby0f584302010-09-16 18:12:51 -0700695 * <p>Valid Bluetooth names are a maximum of 248 bytes using UTF-8
696 * encoding, although many remote devices can only display the first
697 * 40 characters, and some may be limited to just 20.
Jaikumar Ganeshfec86f42010-08-09 16:54:03 -0700698 * <p>If Bluetooth state is not {@link #STATE_ON}, this API
699 * will return false. After turning on Bluetooth,
700 * wait for {@link #ACTION_STATE_CHANGED} with {@link #STATE_ON}
701 * to get the updated value.
Nick Pellyde893f52009-09-08 13:15:33 -0700702 * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN}
Nick Pellybd022f42009-08-14 18:33:38 -0700703 *
Nick Pellyde893f52009-09-08 13:15:33 -0700704 * @param name a valid Bluetooth name
705 * @return true if the name was set, false otherwise
Nick Pellybd022f42009-08-14 18:33:38 -0700706 */
707 public boolean setName(String name) {
Jaikumar Ganeshf5ff1702010-08-06 19:03:13 -0700708 if (getState() != STATE_ON) return false;
Nick Pellybd022f42009-08-14 18:33:38 -0700709 try {
fredc0f420372012-04-12 00:02:00 -0700710 synchronized(mManagerCallback) {
711 if (mService != null) return mService.setName(name);
712 }
Nick Pellybd022f42009-08-14 18:33:38 -0700713 } catch (RemoteException e) {Log.e(TAG, "", e);}
714 return false;
715 }
716
717 /**
Jake Hamby0f584302010-09-16 18:12:51 -0700718 * Get the current Bluetooth scan mode of the local Bluetooth adapter.
Nick Pellyde893f52009-09-08 13:15:33 -0700719 * <p>The Bluetooth scan mode determines if the local adapter is
720 * connectable and/or discoverable from remote Bluetooth devices.
721 * <p>Possible values are:
722 * {@link #SCAN_MODE_NONE},
723 * {@link #SCAN_MODE_CONNECTABLE},
724 * {@link #SCAN_MODE_CONNECTABLE_DISCOVERABLE}.
Jaikumar Ganeshfec86f42010-08-09 16:54:03 -0700725 * <p>If Bluetooth state is not {@link #STATE_ON}, this API
726 * will return {@link #SCAN_MODE_NONE}. After turning on Bluetooth,
727 * wait for {@link #ACTION_STATE_CHANGED} with {@link #STATE_ON}
728 * to get the updated value.
Nick Pellyde893f52009-09-08 13:15:33 -0700729 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
730 *
731 * @return scan mode
Nick Pellybd022f42009-08-14 18:33:38 -0700732 */
733 public int getScanMode() {
Jaikumar Ganeshf5ff1702010-08-06 19:03:13 -0700734 if (getState() != STATE_ON) return SCAN_MODE_NONE;
Nick Pellybd022f42009-08-14 18:33:38 -0700735 try {
fredc0f420372012-04-12 00:02:00 -0700736 synchronized(mManagerCallback) {
737 if (mService != null) return mService.getScanMode();
738 }
Nick Pellybd022f42009-08-14 18:33:38 -0700739 } catch (RemoteException e) {Log.e(TAG, "", e);}
Nick Pellyde893f52009-09-08 13:15:33 -0700740 return SCAN_MODE_NONE;
Nick Pellybd022f42009-08-14 18:33:38 -0700741 }
742
743 /**
Nick Pellyde893f52009-09-08 13:15:33 -0700744 * Set the Bluetooth scan mode of the local Bluetooth adapter.
745 * <p>The Bluetooth scan mode determines if the local adapter is
746 * connectable and/or discoverable from remote Bluetooth devices.
Nick Pelly12835472009-09-25 15:00:29 -0700747 * <p>For privacy reasons, discoverable mode is automatically turned off
748 * after <code>duration</code> seconds. For example, 120 seconds should be
749 * enough for a remote device to initiate and complete its discovery
750 * process.
Nick Pellyde893f52009-09-08 13:15:33 -0700751 * <p>Valid scan mode values are:
752 * {@link #SCAN_MODE_NONE},
753 * {@link #SCAN_MODE_CONNECTABLE},
754 * {@link #SCAN_MODE_CONNECTABLE_DISCOVERABLE}.
Jaikumar Ganeshfec86f42010-08-09 16:54:03 -0700755 * <p>If Bluetooth state is not {@link #STATE_ON}, this API
756 * will return false. After turning on Bluetooth,
757 * wait for {@link #ACTION_STATE_CHANGED} with {@link #STATE_ON}
758 * to get the updated value.
Nick Pelly18b1e792009-09-24 11:14:15 -0700759 * <p>Requires {@link android.Manifest.permission#WRITE_SECURE_SETTINGS}
760 * <p>Applications cannot set the scan mode. They should use
761 * <code>startActivityForResult(
762 * BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE})
763 * </code>instead.
Nick Pellyde893f52009-09-08 13:15:33 -0700764 *
765 * @param mode valid scan mode
Nick Pelly12835472009-09-25 15:00:29 -0700766 * @param duration time in seconds to apply scan mode, only used for
767 * {@link #SCAN_MODE_CONNECTABLE_DISCOVERABLE}
Nick Pellyde893f52009-09-08 13:15:33 -0700768 * @return true if the scan mode was set, false otherwise
Nick Pelly18b1e792009-09-24 11:14:15 -0700769 * @hide
Nick Pellybd022f42009-08-14 18:33:38 -0700770 */
Nick Pelly12835472009-09-25 15:00:29 -0700771 public boolean setScanMode(int mode, int duration) {
Jaikumar Ganeshf5ff1702010-08-06 19:03:13 -0700772 if (getState() != STATE_ON) return false;
Nick Pellybd022f42009-08-14 18:33:38 -0700773 try {
fredc0f420372012-04-12 00:02:00 -0700774 synchronized(mManagerCallback) {
775 if (mService != null) return mService.setScanMode(mode, duration);
776 }
Nick Pellybd022f42009-08-14 18:33:38 -0700777 } catch (RemoteException e) {Log.e(TAG, "", e);}
Nick Pellyde893f52009-09-08 13:15:33 -0700778 return false;
Nick Pellybd022f42009-08-14 18:33:38 -0700779 }
780
Nick Pelly45e27042009-08-19 11:00:00 -0700781 /** @hide */
Nick Pelly12835472009-09-25 15:00:29 -0700782 public boolean setScanMode(int mode) {
Jaikumar Ganeshf5ff1702010-08-06 19:03:13 -0700783 if (getState() != STATE_ON) return false;
Srikanth Uppala827de2d2012-04-04 03:33:26 -0700784 /* getDiscoverableTimeout() to use the latest from NV than use 0 */
785 return setScanMode(mode, getDiscoverableTimeout());
Nick Pelly12835472009-09-25 15:00:29 -0700786 }
787
788 /** @hide */
Nick Pellybd022f42009-08-14 18:33:38 -0700789 public int getDiscoverableTimeout() {
Jaikumar Ganeshf5ff1702010-08-06 19:03:13 -0700790 if (getState() != STATE_ON) return -1;
Nick Pellybd022f42009-08-14 18:33:38 -0700791 try {
fredc0f420372012-04-12 00:02:00 -0700792 synchronized(mManagerCallback) {
793 if (mService != null) return mService.getDiscoverableTimeout();
794 }
Nick Pellybd022f42009-08-14 18:33:38 -0700795 } catch (RemoteException e) {Log.e(TAG, "", e);}
796 return -1;
797 }
798
Nick Pelly45e27042009-08-19 11:00:00 -0700799 /** @hide */
Nick Pellybd022f42009-08-14 18:33:38 -0700800 public void setDiscoverableTimeout(int timeout) {
Jaikumar Ganeshf5ff1702010-08-06 19:03:13 -0700801 if (getState() != STATE_ON) return;
Nick Pellybd022f42009-08-14 18:33:38 -0700802 try {
fredc0f420372012-04-12 00:02:00 -0700803 synchronized(mManagerCallback) {
804 if (mService != null) mService.setDiscoverableTimeout(timeout);
805 }
Nick Pellybd022f42009-08-14 18:33:38 -0700806 } catch (RemoteException e) {Log.e(TAG, "", e);}
807 }
808
Nick Pelly005b2282009-09-10 10:21:56 -0700809 /**
810 * Start the remote device discovery process.
811 * <p>The discovery process usually involves an inquiry scan of about 12
812 * seconds, followed by a page scan of each new device to retrieve its
813 * Bluetooth name.
814 * <p>This is an asynchronous call, it will return immediately. Register
815 * for {@link #ACTION_DISCOVERY_STARTED} and {@link
816 * #ACTION_DISCOVERY_FINISHED} intents to determine exactly when the
817 * discovery starts and completes. Register for {@link
818 * BluetoothDevice#ACTION_FOUND} to be notified as remote Bluetooth devices
819 * are found.
820 * <p>Device discovery is a heavyweight procedure. New connections to
821 * remote Bluetooth devices should not be attempted while discovery is in
822 * progress, and existing connections will experience limited bandwidth
823 * and high latency. Use {@link #cancelDiscovery()} to cancel an ongoing
Scott Main6d95fc02009-11-19 17:00:19 -0800824 * discovery. Discovery is not managed by the Activity,
825 * but is run as a system service, so an application should always call
826 * {@link BluetoothAdapter#cancelDiscovery()} even if it
827 * did not directly request a discovery, just to be sure.
Nick Pelly005b2282009-09-10 10:21:56 -0700828 * <p>Device discovery will only find remote devices that are currently
829 * <i>discoverable</i> (inquiry scan enabled). Many Bluetooth devices are
830 * not discoverable by default, and need to be entered into a special mode.
Jaikumar Ganeshfec86f42010-08-09 16:54:03 -0700831 * <p>If Bluetooth state is not {@link #STATE_ON}, this API
832 * will return false. After turning on Bluetooth,
833 * wait for {@link #ACTION_STATE_CHANGED} with {@link #STATE_ON}
834 * to get the updated value.
Nick Pelly005b2282009-09-10 10:21:56 -0700835 * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN}.
836 *
837 * @return true on success, false on error
838 */
Nick Pellybd022f42009-08-14 18:33:38 -0700839 public boolean startDiscovery() {
Jaikumar Ganeshf5ff1702010-08-06 19:03:13 -0700840 if (getState() != STATE_ON) return false;
Nick Pellybd022f42009-08-14 18:33:38 -0700841 try {
fredc0f420372012-04-12 00:02:00 -0700842 synchronized(mManagerCallback) {
843 if (mService != null) return mService.startDiscovery();
844 }
Nick Pellybd022f42009-08-14 18:33:38 -0700845 } catch (RemoteException e) {Log.e(TAG, "", e);}
846 return false;
847 }
848
Nick Pelly005b2282009-09-10 10:21:56 -0700849 /**
850 * Cancel the current device discovery process.
851 * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN}.
Jake Hamby0f584302010-09-16 18:12:51 -0700852 * <p>Because discovery is a heavyweight procedure for the Bluetooth
Scott Main6d95fc02009-11-19 17:00:19 -0800853 * adapter, this method should always be called before attempting to connect
854 * to a remote device with {@link
855 * android.bluetooth.BluetoothSocket#connect()}. Discovery is not managed by
856 * the Activity, but is run as a system service, so an application should
857 * always call cancel discovery even if it did not directly request a
858 * discovery, just to be sure.
Jaikumar Ganeshfec86f42010-08-09 16:54:03 -0700859 * <p>If Bluetooth state is not {@link #STATE_ON}, this API
860 * will return false. After turning on Bluetooth,
861 * wait for {@link #ACTION_STATE_CHANGED} with {@link #STATE_ON}
862 * to get the updated value.
Nick Pelly005b2282009-09-10 10:21:56 -0700863 *
864 * @return true on success, false on error
865 */
866 public boolean cancelDiscovery() {
Jaikumar Ganeshf5ff1702010-08-06 19:03:13 -0700867 if (getState() != STATE_ON) return false;
Nick Pellybd022f42009-08-14 18:33:38 -0700868 try {
fredc0f420372012-04-12 00:02:00 -0700869 synchronized(mManagerCallback) {
870 if (mService != null) return mService.cancelDiscovery();
871 }
Nick Pellybd022f42009-08-14 18:33:38 -0700872 } catch (RemoteException e) {Log.e(TAG, "", e);}
Nick Pelly005b2282009-09-10 10:21:56 -0700873 return false;
Nick Pellybd022f42009-08-14 18:33:38 -0700874 }
875
Nick Pelly005b2282009-09-10 10:21:56 -0700876 /**
877 * Return true if the local Bluetooth adapter is currently in the device
878 * discovery process.
879 * <p>Device discovery is a heavyweight procedure. New connections to
880 * remote Bluetooth devices should not be attempted while discovery is in
881 * progress, and existing connections will experience limited bandwidth
882 * and high latency. Use {@link #cancelDiscovery()} to cancel an ongoing
883 * discovery.
884 * <p>Applications can also register for {@link #ACTION_DISCOVERY_STARTED}
885 * or {@link #ACTION_DISCOVERY_FINISHED} to be notified when discovery
886 * starts or completes.
Jaikumar Ganeshfec86f42010-08-09 16:54:03 -0700887 * <p>If Bluetooth state is not {@link #STATE_ON}, this API
888 * will return false. After turning on Bluetooth,
889 * wait for {@link #ACTION_STATE_CHANGED} with {@link #STATE_ON}
890 * to get the updated value.
Nick Pellye6ee3be2009-10-08 23:27:28 +0200891 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}.
Nick Pelly005b2282009-09-10 10:21:56 -0700892 *
893 * @return true if discovering
894 */
Nick Pellybd022f42009-08-14 18:33:38 -0700895 public boolean isDiscovering() {
Jaikumar Ganeshf5ff1702010-08-06 19:03:13 -0700896 if (getState() != STATE_ON) return false;
Nick Pellybd022f42009-08-14 18:33:38 -0700897 try {
fredc0f420372012-04-12 00:02:00 -0700898 synchronized(mManagerCallback) {
899 if (mService != null ) return mService.isDiscovering();
900 }
Nick Pellybd022f42009-08-14 18:33:38 -0700901 } catch (RemoteException e) {Log.e(TAG, "", e);}
902 return false;
903 }
904
905 /**
Prerepa Viswanadham0c116e12014-07-02 12:30:38 -0700906 * Return true if the multi advertisement is supported by the chipset
907 *
Prerepa Viswanadham0c116e12014-07-02 12:30:38 -0700908 * @return true if Multiple Advertisement feature is supported
909 */
910 public boolean isMultipleAdvertisementSupported() {
911 if (getState() != STATE_ON) return false;
912 try {
913 return mService.isMultiAdvertisementSupported();
914 } catch (RemoteException e) {
915 Log.e(TAG, "failed to get isMultipleAdvertisementSupported, error: ", e);
916 }
917 return false;
918 }
919
920 /**
921 * Return true if offloaded filters are supported
922 *
Prerepa Viswanadham0c116e12014-07-02 12:30:38 -0700923 * @return true if chipset supports on-chip filtering
924 */
925 public boolean isOffloadedFilteringSupported() {
926 if (getState() != STATE_ON) return false;
927 try {
928 return mService.isOffloadedFilteringSupported();
929 } catch (RemoteException e) {
930 Log.e(TAG, "failed to get isOffloadedFilteringSupported, error: ", e);
931 }
932 return false;
933 }
934
935 /**
936 * Return true if offloaded scan batching is supported
937 *
Prerepa Viswanadham0c116e12014-07-02 12:30:38 -0700938 * @return true if chipset supports on-chip scan batching
939 */
940 public boolean isOffloadedScanBatchingSupported() {
941 if (getState() != STATE_ON) return false;
942 try {
943 return mService.isOffloadedScanBatchingSupported();
944 } catch (RemoteException e) {
945 Log.e(TAG, "failed to get isOffloadedScanBatchingSupported, error: ", e);
946 }
947 return false;
948 }
949
950 /**
Prerepa Viswanadham8caac742014-07-22 17:00:09 -0700951 * Return the record of {@link BluetoothActivityEnergyInfo} object that
952 * has the activity and energy info. This can be used to ascertain what
953 * the controller has been up to, since the last sample.
954 * @param updateType Type of info, cached vs refreshed.
955 *
956 * @return a record with {@link BluetoothActivityEnergyInfo} or null if
957 * report is unavailable or unsupported
958 * @hide
959 */
960 public BluetoothActivityEnergyInfo getControllerActivityEnergyInfo(int updateType) {
961 if (getState() != STATE_ON) return null;
962 try {
963 BluetoothActivityEnergyInfo record;
964 if (!mService.isActivityAndEnergyReportingSupported()) {
965 return null;
966 }
967 synchronized(this) {
968 if (updateType == ACTIVITY_ENERGY_INFO_REFRESHED) {
969 mService.getActivityEnergyInfoFromController();
970 wait(CONTROLLER_ENERGY_UPDATE_TIMEOUT_MILLIS);
971 }
972 record = mService.reportActivityInfo();
973 if (record.isValid()) {
974 return record;
975 } else {
976 return null;
977 }
978 }
979 } catch (InterruptedException e) {
980 Log.e(TAG, "getControllerActivityEnergyInfoCallback wait interrupted: " + e);
981 } catch (RemoteException e) {
982 Log.e(TAG, "getControllerActivityEnergyInfoCallback: " + e);
983 }
984 return null;
985 }
986
987 /**
Nick Pelly005b2282009-09-10 10:21:56 -0700988 * Return the set of {@link BluetoothDevice} objects that are bonded
989 * (paired) to the local adapter.
Jaikumar Ganeshfec86f42010-08-09 16:54:03 -0700990 * <p>If Bluetooth state is not {@link #STATE_ON}, this API
991 * will return an empty set. After turning on Bluetooth,
992 * wait for {@link #ACTION_STATE_CHANGED} with {@link #STATE_ON}
993 * to get the updated value.
Nick Pellye6ee3be2009-10-08 23:27:28 +0200994 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}.
Nick Pellybd022f42009-08-14 18:33:38 -0700995 *
Nick Pelly005b2282009-09-10 10:21:56 -0700996 * @return unmodifiable set of {@link BluetoothDevice}, or null on error
Nick Pellybd022f42009-08-14 18:33:38 -0700997 */
998 public Set<BluetoothDevice> getBondedDevices() {
Jaikumar Ganeshfec86f42010-08-09 16:54:03 -0700999 if (getState() != STATE_ON) {
Jaikumar Ganeshe4caddb2012-01-25 16:16:48 -08001000 return toDeviceSet(new BluetoothDevice[0]);
Jaikumar Ganeshfec86f42010-08-09 16:54:03 -07001001 }
Nick Pellybd022f42009-08-14 18:33:38 -07001002 try {
fredc0f420372012-04-12 00:02:00 -07001003 synchronized(mManagerCallback) {
1004 if (mService != null) return toDeviceSet(mService.getBondedDevices());
1005 }
1006 return toDeviceSet(new BluetoothDevice[0]);
Nick Pellybd022f42009-08-14 18:33:38 -07001007 } catch (RemoteException e) {Log.e(TAG, "", e);}
1008 return null;
1009 }
1010
1011 /**
Jaikumar Ganeshc53cab22010-10-26 16:02:26 -07001012 * Get the current connection state of the local Bluetooth adapter.
1013 * This can be used to check whether the local Bluetooth adapter is connected
1014 * to any profile of any other remote Bluetooth Device.
1015 *
1016 * <p> Use this function along with {@link #ACTION_CONNECTION_STATE_CHANGED}
1017 * intent to get the connection state of the adapter.
1018 *
1019 * @return One of {@link #STATE_CONNECTED}, {@link #STATE_DISCONNECTED},
1020 * {@link #STATE_CONNECTING} or {@link #STATE_DISCONNECTED}
1021 *
1022 * @hide
1023 */
1024 public int getConnectionState() {
1025 if (getState() != STATE_ON) return BluetoothAdapter.STATE_DISCONNECTED;
1026 try {
fredc0f420372012-04-12 00:02:00 -07001027 synchronized(mManagerCallback) {
1028 if (mService != null) return mService.getAdapterConnectionState();
1029 }
Jaikumar Ganeshc53cab22010-10-26 16:02:26 -07001030 } catch (RemoteException e) {Log.e(TAG, "getConnectionState:", e);}
1031 return BluetoothAdapter.STATE_DISCONNECTED;
1032 }
1033
1034 /**
Jaikumar Ganeshcb1d3542011-08-19 10:26:32 -07001035 * Get the current connection state of a profile.
1036 * This function can be used to check whether the local Bluetooth adapter
1037 * is connected to any remote device for a specific profile.
Scott Main2d68a6b2011-09-26 22:59:38 -07001038 * Profile can be one of {@link BluetoothProfile#HEALTH}, {@link BluetoothProfile#HEADSET},
Jaikumar Ganesh93547902011-08-23 12:21:55 -07001039 * {@link BluetoothProfile#A2DP}.
Jaikumar Ganeshcb1d3542011-08-19 10:26:32 -07001040 *
1041 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}.
1042 *
1043 * <p> Return value can be one of
Jaikumar Ganesh93547902011-08-23 12:21:55 -07001044 * {@link BluetoothProfile#STATE_DISCONNECTED},
1045 * {@link BluetoothProfile#STATE_CONNECTING},
1046 * {@link BluetoothProfile#STATE_CONNECTED},
1047 * {@link BluetoothProfile#STATE_DISCONNECTING}
Jaikumar Ganeshcb1d3542011-08-19 10:26:32 -07001048 */
1049 public int getProfileConnectionState(int profile) {
1050 if (getState() != STATE_ON) return BluetoothProfile.STATE_DISCONNECTED;
1051 try {
fredc0f420372012-04-12 00:02:00 -07001052 synchronized(mManagerCallback) {
1053 if (mService != null) return mService.getProfileConnectionState(profile);
1054 }
Jaikumar Ganesh93547902011-08-23 12:21:55 -07001055 } catch (RemoteException e) {
1056 Log.e(TAG, "getProfileConnectionState:", e);
1057 }
Jaikumar Ganeshcb1d3542011-08-19 10:26:32 -07001058 return BluetoothProfile.STATE_DISCONNECTED;
1059 }
1060
1061 /**
Nick Pelly45e27042009-08-19 11:00:00 -07001062 * Create a listening, secure RFCOMM Bluetooth socket.
1063 * <p>A remote device connecting to this socket will be authenticated and
Nick Pellybd022f42009-08-14 18:33:38 -07001064 * communication on this socket will be encrypted.
Nick Pelly45e27042009-08-19 11:00:00 -07001065 * <p>Use {@link BluetoothServerSocket#accept} to retrieve incoming
Nick Pelly24bb9b82009-10-02 20:34:18 -07001066 * connections from a listening {@link BluetoothServerSocket}.
Nick Pelly45e27042009-08-19 11:00:00 -07001067 * <p>Valid RFCOMM channels are in range 1 to 30.
Nick Pelly24bb9b82009-10-02 20:34:18 -07001068 * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN}
Nick Pelly45e27042009-08-19 11:00:00 -07001069 * @param channel RFCOMM channel to listen on
1070 * @return a listening RFCOMM BluetoothServerSocket
1071 * @throws IOException on error, for example Bluetooth not available, or
1072 * insufficient permissions, or channel in use.
Nick Pelly24bb9b82009-10-02 20:34:18 -07001073 * @hide
Nick Pellybd022f42009-08-14 18:33:38 -07001074 */
Nick Pelly45e27042009-08-19 11:00:00 -07001075 public BluetoothServerSocket listenUsingRfcommOn(int channel) throws IOException {
Nick Pellybd022f42009-08-14 18:33:38 -07001076 BluetoothServerSocket socket = new BluetoothServerSocket(
Nick Pelly45e27042009-08-19 11:00:00 -07001077 BluetoothSocket.TYPE_RFCOMM, true, true, channel);
Nick Pelly24bb9b82009-10-02 20:34:18 -07001078 int errno = socket.mSocket.bindListen();
1079 if (errno != 0) {
zzy3b147b72012-04-03 19:48:32 -07001080 //TODO(BT): Throw the same exception error code
1081 // that the previous code was using.
1082 //socket.mSocket.throwErrnoNative(errno);
1083 throw new IOException("Error: " + errno);
Nick Pellybd022f42009-08-14 18:33:38 -07001084 }
1085 return socket;
1086 }
1087
1088 /**
Nick Pelly24bb9b82009-10-02 20:34:18 -07001089 * Create a listening, secure RFCOMM Bluetooth socket with Service Record.
1090 * <p>A remote device connecting to this socket will be authenticated and
1091 * communication on this socket will be encrypted.
1092 * <p>Use {@link BluetoothServerSocket#accept} to retrieve incoming
1093 * connections from a listening {@link BluetoothServerSocket}.
1094 * <p>The system will assign an unused RFCOMM channel to listen on.
1095 * <p>The system will also register a Service Discovery
1096 * Protocol (SDP) record with the local SDP server containing the specified
1097 * UUID, service name, and auto-assigned channel. Remote Bluetooth devices
1098 * can use the same UUID to query our SDP server and discover which channel
1099 * to connect to. This SDP record will be removed when this socket is
1100 * closed, or if this application closes unexpectedly.
Nick Pelly16fb88a2009-10-07 07:44:03 +02001101 * <p>Use {@link BluetoothDevice#createRfcommSocketToServiceRecord} to
1102 * connect to this socket from another device using the same {@link UUID}.
Nick Pelly24bb9b82009-10-02 20:34:18 -07001103 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
1104 * @param name service name for SDP record
1105 * @param uuid uuid for SDP record
1106 * @return a listening RFCOMM BluetoothServerSocket
1107 * @throws IOException on error, for example Bluetooth not available, or
1108 * insufficient permissions, or channel in use.
1109 */
Nick Pelly16fb88a2009-10-07 07:44:03 +02001110 public BluetoothServerSocket listenUsingRfcommWithServiceRecord(String name, UUID uuid)
Nick Pelly24bb9b82009-10-02 20:34:18 -07001111 throws IOException {
Jaikumar Ganesh6eef14a2010-12-23 12:57:02 -08001112 return createNewRfcommSocketAndRecord(name, uuid, true, true);
1113 }
1114
1115 /**
1116 * Create a listening, insecure RFCOMM Bluetooth socket with Service Record.
Mathias Jeppssone3b9dc12011-03-21 15:06:52 +01001117 * <p>The link key is not required to be authenticated, i.e the communication may be
Jaikumar Ganesh6eef14a2010-12-23 12:57:02 -08001118 * vulnerable to Man In the Middle attacks. For Bluetooth 2.1 devices,
Mathias Jeppssone3b9dc12011-03-21 15:06:52 +01001119 * the link will be encrypted, as encryption is mandartory.
1120 * For legacy devices (pre Bluetooth 2.1 devices) the link will not
Jaikumar Ganesh6eef14a2010-12-23 12:57:02 -08001121 * be encrypted. Use {@link #listenUsingRfcommWithServiceRecord}, if an
1122 * encrypted and authenticated communication channel is desired.
1123 * <p>Use {@link BluetoothServerSocket#accept} to retrieve incoming
1124 * connections from a listening {@link BluetoothServerSocket}.
1125 * <p>The system will assign an unused RFCOMM channel to listen on.
1126 * <p>The system will also register a Service Discovery
1127 * Protocol (SDP) record with the local SDP server containing the specified
1128 * UUID, service name, and auto-assigned channel. Remote Bluetooth devices
1129 * can use the same UUID to query our SDP server and discover which channel
1130 * to connect to. This SDP record will be removed when this socket is
1131 * closed, or if this application closes unexpectedly.
1132 * <p>Use {@link BluetoothDevice#createRfcommSocketToServiceRecord} to
1133 * connect to this socket from another device using the same {@link UUID}.
1134 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
1135 * @param name service name for SDP record
1136 * @param uuid uuid for SDP record
1137 * @return a listening RFCOMM BluetoothServerSocket
1138 * @throws IOException on error, for example Bluetooth not available, or
1139 * insufficient permissions, or channel in use.
1140 */
1141 public BluetoothServerSocket listenUsingInsecureRfcommWithServiceRecord(String name, UUID uuid)
1142 throws IOException {
1143 return createNewRfcommSocketAndRecord(name, uuid, false, false);
1144 }
1145
Mathias Jeppssone3b9dc12011-03-21 15:06:52 +01001146 /**
1147 * Create a listening, encrypted,
1148 * RFCOMM Bluetooth socket with Service Record.
1149 * <p>The link will be encrypted, but the link key is not required to be authenticated
1150 * i.e the communication is vulnerable to Man In the Middle attacks. Use
1151 * {@link #listenUsingRfcommWithServiceRecord}, to ensure an authenticated link key.
1152 * <p> Use this socket if authentication of link key is not possible.
1153 * For example, for Bluetooth 2.1 devices, if any of the devices does not have
1154 * an input and output capability or just has the ability to display a numeric key,
1155 * a secure socket connection is not possible and this socket can be used.
1156 * Use {@link #listenUsingInsecureRfcommWithServiceRecord}, if encryption is not required.
1157 * For Bluetooth 2.1 devices, the link will be encrypted, as encryption is mandartory.
1158 * For more details, refer to the Security Model section 5.2 (vol 3) of
1159 * Bluetooth Core Specification version 2.1 + EDR.
1160 * <p>Use {@link BluetoothServerSocket#accept} to retrieve incoming
1161 * connections from a listening {@link BluetoothServerSocket}.
1162 * <p>The system will assign an unused RFCOMM channel to listen on.
1163 * <p>The system will also register a Service Discovery
1164 * Protocol (SDP) record with the local SDP server containing the specified
1165 * UUID, service name, and auto-assigned channel. Remote Bluetooth devices
1166 * can use the same UUID to query our SDP server and discover which channel
1167 * to connect to. This SDP record will be removed when this socket is
1168 * closed, or if this application closes unexpectedly.
1169 * <p>Use {@link BluetoothDevice#createRfcommSocketToServiceRecord} to
1170 * connect to this socket from another device using the same {@link UUID}.
1171 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
1172 * @param name service name for SDP record
1173 * @param uuid uuid for SDP record
1174 * @return a listening RFCOMM BluetoothServerSocket
1175 * @throws IOException on error, for example Bluetooth not available, or
1176 * insufficient permissions, or channel in use.
1177 * @hide
1178 */
1179 public BluetoothServerSocket listenUsingEncryptedRfcommWithServiceRecord(
1180 String name, UUID uuid) throws IOException {
1181 return createNewRfcommSocketAndRecord(name, uuid, false, true);
1182 }
1183
zzy3b147b72012-04-03 19:48:32 -07001184
Jaikumar Ganesh6eef14a2010-12-23 12:57:02 -08001185 private BluetoothServerSocket createNewRfcommSocketAndRecord(String name, UUID uuid,
1186 boolean auth, boolean encrypt) throws IOException {
Nick Pelly24bb9b82009-10-02 20:34:18 -07001187 BluetoothServerSocket socket;
zzy3b147b72012-04-03 19:48:32 -07001188 socket = new BluetoothServerSocket(BluetoothSocket.TYPE_RFCOMM, auth,
1189 encrypt, new ParcelUuid(uuid));
1190 socket.setServiceName(name);
1191 int errno = socket.mSocket.bindListen();
1192 if (errno != 0) {
1193 //TODO(BT): Throw the same exception error code
1194 // that the previous code was using.
1195 //socket.mSocket.throwErrnoNative(errno);
1196 throw new IOException("Error: " + errno);
Nick Pelly24bb9b82009-10-02 20:34:18 -07001197 }
Nick Pelly24bb9b82009-10-02 20:34:18 -07001198 return socket;
1199 }
1200
1201 /**
Nick Pellybd022f42009-08-14 18:33:38 -07001202 * Construct an unencrypted, unauthenticated, RFCOMM server socket.
1203 * Call #accept to retrieve connections to this socket.
1204 * @return An RFCOMM BluetoothServerSocket
1205 * @throws IOException On error, for example Bluetooth not available, or
1206 * insufficient permissions.
Nick Pelly45e27042009-08-19 11:00:00 -07001207 * @hide
Nick Pellybd022f42009-08-14 18:33:38 -07001208 */
1209 public BluetoothServerSocket listenUsingInsecureRfcommOn(int port) throws IOException {
1210 BluetoothServerSocket socket = new BluetoothServerSocket(
1211 BluetoothSocket.TYPE_RFCOMM, false, false, port);
Nick Pelly24bb9b82009-10-02 20:34:18 -07001212 int errno = socket.mSocket.bindListen();
1213 if (errno != 0) {
zzy3b147b72012-04-03 19:48:32 -07001214 //TODO(BT): Throw the same exception error code
1215 // that the previous code was using.
1216 //socket.mSocket.throwErrnoNative(errno);
1217 throw new IOException("Error: " + errno);
Nick Pellybd022f42009-08-14 18:33:38 -07001218 }
1219 return socket;
1220 }
1221
Mathias Jeppssone3b9dc12011-03-21 15:06:52 +01001222 /**
1223 * Construct an encrypted, RFCOMM server socket.
1224 * Call #accept to retrieve connections to this socket.
1225 * @return An RFCOMM BluetoothServerSocket
1226 * @throws IOException On error, for example Bluetooth not available, or
1227 * insufficient permissions.
1228 * @hide
1229 */
1230 public BluetoothServerSocket listenUsingEncryptedRfcommOn(int port)
1231 throws IOException {
1232 BluetoothServerSocket socket = new BluetoothServerSocket(
1233 BluetoothSocket.TYPE_RFCOMM, false, true, port);
1234 int errno = socket.mSocket.bindListen();
zzy3b147b72012-04-03 19:48:32 -07001235 if (errno < 0) {
1236 //TODO(BT): Throw the same exception error code
1237 // that the previous code was using.
1238 //socket.mSocket.throwErrnoNative(errno);
1239 throw new IOException("Error: " + errno);
Mathias Jeppssone3b9dc12011-03-21 15:06:52 +01001240 }
1241 return socket;
1242 }
1243
Nick Pellybd022f42009-08-14 18:33:38 -07001244 /**
1245 * Construct a SCO server socket.
1246 * Call #accept to retrieve connections to this socket.
1247 * @return A SCO BluetoothServerSocket
1248 * @throws IOException On error, for example Bluetooth not available, or
1249 * insufficient permissions.
Nick Pelly45e27042009-08-19 11:00:00 -07001250 * @hide
Nick Pellybd022f42009-08-14 18:33:38 -07001251 */
1252 public static BluetoothServerSocket listenUsingScoOn() throws IOException {
1253 BluetoothServerSocket socket = new BluetoothServerSocket(
1254 BluetoothSocket.TYPE_SCO, false, false, -1);
Nick Pelly24bb9b82009-10-02 20:34:18 -07001255 int errno = socket.mSocket.bindListen();
zzy3b147b72012-04-03 19:48:32 -07001256 if (errno < 0) {
1257 //TODO(BT): Throw the same exception error code
1258 // that the previous code was using.
1259 //socket.mSocket.throwErrnoNative(errno);
Nick Pellybd022f42009-08-14 18:33:38 -07001260 }
1261 return socket;
1262 }
1263
Jaikumar Ganeshcc5494c2010-09-09 15:37:57 -07001264 /**
1265 * Read the local Out of Band Pairing Data
1266 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
1267 *
1268 * @return Pair<byte[], byte[]> of Hash and Randomizer
1269 *
1270 * @hide
1271 */
1272 public Pair<byte[], byte[]> readOutOfBandData() {
1273 if (getState() != STATE_ON) return null;
Jaikumar Ganeshe4caddb2012-01-25 16:16:48 -08001274 //TODO(BT
1275 /*
Jaikumar Ganeshcc5494c2010-09-09 15:37:57 -07001276 try {
Jake Hambyf51eada2010-09-21 13:39:53 -07001277 byte[] hash;
1278 byte[] randomizer;
Jaikumar Ganeshcc5494c2010-09-09 15:37:57 -07001279
1280 byte[] ret = mService.readOutOfBandData();
1281
1282 if (ret == null || ret.length != 32) return null;
1283
1284 hash = Arrays.copyOfRange(ret, 0, 16);
1285 randomizer = Arrays.copyOfRange(ret, 16, 32);
1286
1287 if (DBG) {
1288 Log.d(TAG, "readOutOfBandData:" + Arrays.toString(hash) +
1289 ":" + Arrays.toString(randomizer));
1290 }
1291 return new Pair<byte[], byte[]>(hash, randomizer);
1292
Jaikumar Ganeshe4caddb2012-01-25 16:16:48 -08001293 } catch (RemoteException e) {Log.e(TAG, "", e);}*/
Jaikumar Ganeshcc5494c2010-09-09 15:37:57 -07001294 return null;
1295 }
1296
Scott Main299ae672011-01-19 21:13:18 -08001297 /**
Jaikumar Ganesh62c37ef2010-08-24 17:36:13 -07001298 * Get the profile proxy object associated with the profile.
1299 *
Ganesh Ganapathi Batta99081122013-02-05 15:28:33 -08001300 * <p>Profile can be one of {@link BluetoothProfile#HEALTH}, {@link BluetoothProfile#HEADSET},
Matthew Xieddf7e472013-03-01 18:41:02 -08001301 * {@link BluetoothProfile#A2DP}, {@link BluetoothProfile#GATT}, or
1302 * {@link BluetoothProfile#GATT_SERVER}. Clients must implement
Jaikumar Ganesh62c37ef2010-08-24 17:36:13 -07001303 * {@link BluetoothProfile.ServiceListener} to get notified of
1304 * the connection status and to get the proxy object.
1305 *
1306 * @param context Context of the application
1307 * @param listener The service Listener for connection callbacks.
Scott Main2d68a6b2011-09-26 22:59:38 -07001308 * @param profile The Bluetooth profile; either {@link BluetoothProfile#HEALTH},
1309 * {@link BluetoothProfile#HEADSET} or {@link BluetoothProfile#A2DP}.
Jaikumar Ganesh62c37ef2010-08-24 17:36:13 -07001310 * @return true on success, false on error
1311 */
1312 public boolean getProfileProxy(Context context, BluetoothProfile.ServiceListener listener,
1313 int profile) {
1314 if (context == null || listener == null) return false;
1315
1316 if (profile == BluetoothProfile.HEADSET) {
1317 BluetoothHeadset headset = new BluetoothHeadset(context, listener);
1318 return true;
1319 } else if (profile == BluetoothProfile.A2DP) {
1320 BluetoothA2dp a2dp = new BluetoothA2dp(context, listener);
1321 return true;
Mike Lockwood2263dd12014-05-14 09:51:30 -07001322 } else if (profile == BluetoothProfile.A2DP_SINK) {
1323 BluetoothA2dpSink a2dpSink = new BluetoothA2dpSink(context, listener);
1324 return true;
Mike Lockwood94b59de2014-06-02 16:20:37 -07001325 } else if (profile == BluetoothProfile.AVRCP_CONTROLLER) {
1326 BluetoothAvrcpController avrcp = new BluetoothAvrcpController(context, listener);
1327 return true;
Jaikumar Ganesh4ab0e772011-02-18 14:52:32 -08001328 } else if (profile == BluetoothProfile.INPUT_DEVICE) {
1329 BluetoothInputDevice iDev = new BluetoothInputDevice(context, listener);
1330 return true;
Jaikumar Ganesh74ef1192011-02-23 10:22:15 -08001331 } else if (profile == BluetoothProfile.PAN) {
1332 BluetoothPan pan = new BluetoothPan(context, listener);
1333 return true;
Jaikumar Ganesh2ea1e852011-04-01 16:33:09 -07001334 } else if (profile == BluetoothProfile.HEALTH) {
1335 BluetoothHealth health = new BluetoothHealth(context, listener);
1336 return true;
Kim Schulz0d376052013-08-22 11:18:02 +02001337 } else if (profile == BluetoothProfile.MAP) {
1338 BluetoothMap map = new BluetoothMap(context, listener);
1339 return true;
Mike Lockwoodcf916d32014-06-12 11:23:40 -07001340 } else if (profile == BluetoothProfile.HEADSET_CLIENT) {
1341 BluetoothHeadsetClient headsetClient = new BluetoothHeadsetClient(context, listener);
Hemant Gupta7aca90f2013-08-19 19:03:51 +05301342 return true;
Jaikumar Ganesh62c37ef2010-08-24 17:36:13 -07001343 } else {
1344 return false;
1345 }
1346 }
1347
1348 /**
1349 * Close the connection of the profile proxy to the Service.
1350 *
1351 * <p> Clients should call this when they are no longer using
1352 * the proxy obtained from {@link #getProfileProxy}.
Scott Main2d68a6b2011-09-26 22:59:38 -07001353 * Profile can be one of {@link BluetoothProfile#HEALTH}, {@link BluetoothProfile#HEADSET} or
Jaikumar Ganesh62c37ef2010-08-24 17:36:13 -07001354 * {@link BluetoothProfile#A2DP}
1355 *
1356 * @param profile
1357 * @param proxy Profile proxy object
1358 */
1359 public void closeProfileProxy(int profile, BluetoothProfile proxy) {
Jaikumar Ganesh9bb27512011-11-28 09:59:08 -08001360 if (proxy == null) return;
1361
1362 switch (profile) {
1363 case BluetoothProfile.HEADSET:
1364 BluetoothHeadset headset = (BluetoothHeadset)proxy;
Jaikumar Ganesh62c37ef2010-08-24 17:36:13 -07001365 headset.close();
Jaikumar Ganesh9bb27512011-11-28 09:59:08 -08001366 break;
1367 case BluetoothProfile.A2DP:
1368 BluetoothA2dp a2dp = (BluetoothA2dp)proxy;
1369 a2dp.close();
1370 break;
Mike Lockwood2263dd12014-05-14 09:51:30 -07001371 case BluetoothProfile.A2DP_SINK:
1372 BluetoothA2dpSink a2dpSink = (BluetoothA2dpSink)proxy;
1373 a2dpSink.close();
1374 break;
Mike Lockwood94b59de2014-06-02 16:20:37 -07001375 case BluetoothProfile.AVRCP_CONTROLLER:
1376 BluetoothAvrcpController avrcp = (BluetoothAvrcpController)proxy;
1377 avrcp.close();
1378 break;
Jaikumar Ganesh9bb27512011-11-28 09:59:08 -08001379 case BluetoothProfile.INPUT_DEVICE:
1380 BluetoothInputDevice iDev = (BluetoothInputDevice)proxy;
1381 iDev.close();
1382 break;
1383 case BluetoothProfile.PAN:
1384 BluetoothPan pan = (BluetoothPan)proxy;
1385 pan.close();
1386 break;
1387 case BluetoothProfile.HEALTH:
1388 BluetoothHealth health = (BluetoothHealth)proxy;
1389 health.close();
1390 break;
Ganesh Ganapathi Batta99081122013-02-05 15:28:33 -08001391 case BluetoothProfile.GATT:
1392 BluetoothGatt gatt = (BluetoothGatt)proxy;
1393 gatt.close();
1394 break;
1395 case BluetoothProfile.GATT_SERVER:
1396 BluetoothGattServer gattServer = (BluetoothGattServer)proxy;
1397 gattServer.close();
1398 break;
Kim Schulz0d376052013-08-22 11:18:02 +02001399 case BluetoothProfile.MAP:
1400 BluetoothMap map = (BluetoothMap)proxy;
1401 map.close();
1402 break;
Mike Lockwoodcf916d32014-06-12 11:23:40 -07001403 case BluetoothProfile.HEADSET_CLIENT:
1404 BluetoothHeadsetClient headsetClient = (BluetoothHeadsetClient)proxy;
1405 headsetClient.close();
Hemant Gupta7aca90f2013-08-19 19:03:51 +05301406 break;
Jaikumar Ganesh62c37ef2010-08-24 17:36:13 -07001407 }
1408 }
1409
fredc0f420372012-04-12 00:02:00 -07001410 final private IBluetoothManagerCallback mManagerCallback =
1411 new IBluetoothManagerCallback.Stub() {
1412 public void onBluetoothServiceUp(IBluetooth bluetoothService) {
Matthew Xied77982e2012-11-29 20:26:19 -08001413 if (VDBG) Log.d(TAG, "onBluetoothServiceUp: " + bluetoothService);
fredc0f420372012-04-12 00:02:00 -07001414 synchronized (mManagerCallback) {
1415 mService = bluetoothService;
fredcbf072a72012-05-09 16:52:50 -07001416 for (IBluetoothManagerCallback cb : mProxyServiceStateCallbacks ){
fredc903ac6f2012-04-24 03:59:57 -07001417 try {
fredcd6883532012-04-25 17:46:13 -07001418 if (cb != null) {
1419 cb.onBluetoothServiceUp(bluetoothService);
1420 } else {
1421 Log.d(TAG, "onBluetoothServiceUp: cb is null!!!");
1422 }
fredc903ac6f2012-04-24 03:59:57 -07001423 } catch (Exception e) { Log.e(TAG,"",e);}
1424 }
fredc0f420372012-04-12 00:02:00 -07001425 }
1426 }
1427
1428 public void onBluetoothServiceDown() {
Matthew Xied77982e2012-11-29 20:26:19 -08001429 if (VDBG) Log.d(TAG, "onBluetoothServiceDown: " + mService);
fredc0f420372012-04-12 00:02:00 -07001430 synchronized (mManagerCallback) {
1431 mService = null;
Wei Wangee809222014-08-12 22:16:32 -07001432 mLeScanClients.clear();
1433 if (sBluetoothLeAdvertiser != null) sBluetoothLeAdvertiser.cleanup();
1434 if (sBluetoothLeScanner != null) sBluetoothLeScanner.cleanup();
fredcbf072a72012-05-09 16:52:50 -07001435 for (IBluetoothManagerCallback cb : mProxyServiceStateCallbacks ){
fredc903ac6f2012-04-24 03:59:57 -07001436 try {
fredcd6883532012-04-25 17:46:13 -07001437 if (cb != null) {
1438 cb.onBluetoothServiceDown();
1439 } else {
1440 Log.d(TAG, "onBluetoothServiceDown: cb is null!!!");
1441 }
fredc903ac6f2012-04-24 03:59:57 -07001442 } catch (Exception e) { Log.e(TAG,"",e);}
1443 }
fredc0f420372012-04-12 00:02:00 -07001444 }
1445 }
1446 };
1447
Jaikumar Ganeshef2cb7c2011-07-21 18:13:38 -07001448 /**
Martijn Coenen6c614b72012-04-18 13:01:15 -07001449 * Enable the Bluetooth Adapter, but don't auto-connect devices
1450 * and don't persist state. Only for use by system applications.
1451 * @hide
1452 */
1453 public boolean enableNoAutoConnect() {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001454 if (isEnabled() == true){
1455 if (DBG) Log.d(TAG, "enableNoAutoConnect(): BT is already enabled..!");
1456 return true;
1457 }
1458 try {
1459 return mManagerService.enableNoAutoConnect();
1460 } catch (RemoteException e) {Log.e(TAG, "", e);}
1461 return false;
Martijn Coenen6c614b72012-04-18 13:01:15 -07001462 }
1463
1464 /**
Jaikumar Ganeshef2cb7c2011-07-21 18:13:38 -07001465 * Enable control of the Bluetooth Adapter for a single application.
1466 *
1467 * <p>Some applications need to use Bluetooth for short periods of time to
1468 * transfer data but don't want all the associated implications like
1469 * automatic connection to headsets etc.
1470 *
1471 * <p> Multiple applications can call this. This is reference counted and
1472 * Bluetooth disabled only when no one else is using it. There will be no UI
1473 * shown to the user while bluetooth is being enabled. Any user action will
1474 * override this call. For example, if user wants Bluetooth on and the last
1475 * user of this API wanted to disable Bluetooth, Bluetooth will not be
1476 * turned off.
1477 *
1478 * <p> This API is only meant to be used by internal applications. Third
1479 * party applications but use {@link #enable} and {@link #disable} APIs.
1480 *
1481 * <p> If this API returns true, it means the callback will be called.
1482 * The callback will be called with the current state of Bluetooth.
1483 * If the state is not what was requested, an internal error would be the
Jaikumar Ganeshf5fb6c82011-08-03 14:17:22 -07001484 * reason. If Bluetooth is already on and if this function is called to turn
1485 * it on, the api will return true and a callback will be called.
1486 *
1487 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
Jaikumar Ganeshef2cb7c2011-07-21 18:13:38 -07001488 *
1489 * @param on True for on, false for off.
1490 * @param callback The callback to notify changes to the state.
1491 * @hide
1492 */
1493 public boolean changeApplicationBluetoothState(boolean on,
1494 BluetoothStateChangeCallback callback) {
1495 if (callback == null) return false;
1496
Jaikumar Ganeshe4caddb2012-01-25 16:16:48 -08001497 //TODO(BT)
1498 /*
Jaikumar Ganeshef2cb7c2011-07-21 18:13:38 -07001499 try {
1500 return mService.changeApplicationBluetoothState(on, new
1501 StateChangeCallbackWrapper(callback), new Binder());
1502 } catch (RemoteException e) {
1503 Log.e(TAG, "changeBluetoothState", e);
Jaikumar Ganeshe4caddb2012-01-25 16:16:48 -08001504 }*/
Jaikumar Ganeshef2cb7c2011-07-21 18:13:38 -07001505 return false;
1506 }
1507
1508 /**
1509 * @hide
1510 */
1511 public interface BluetoothStateChangeCallback {
1512 public void onBluetoothStateChange(boolean on);
1513 }
1514
1515 /**
1516 * @hide
1517 */
1518 public class StateChangeCallbackWrapper extends IBluetoothStateChangeCallback.Stub {
1519 private BluetoothStateChangeCallback mCallback;
1520
1521 StateChangeCallbackWrapper(BluetoothStateChangeCallback
1522 callback) {
1523 mCallback = callback;
1524 }
1525
1526 @Override
1527 public void onBluetoothStateChange(boolean on) {
1528 mCallback.onBluetoothStateChange(on);
1529 }
1530 }
1531
Jaikumar Ganeshe4caddb2012-01-25 16:16:48 -08001532 private Set<BluetoothDevice> toDeviceSet(BluetoothDevice[] devices) {
1533 Set<BluetoothDevice> deviceSet = new HashSet<BluetoothDevice>(Arrays.asList(devices));
1534 return Collections.unmodifiableSet(deviceSet);
Nick Pellybd022f42009-08-14 18:33:38 -07001535 }
Nick Pelly005b2282009-09-10 10:21:56 -07001536
fredc0f420372012-04-12 00:02:00 -07001537 protected void finalize() throws Throwable {
1538 try {
1539 mManagerService.unregisterAdapter(mManagerCallback);
1540 } catch (RemoteException e) {
1541 Log.e(TAG, "", e);
1542 } finally {
1543 super.finalize();
1544 }
1545 }
1546
1547
Nick Pelly005b2282009-09-10 10:21:56 -07001548 /**
Nick Pelly75596b42011-12-07 15:03:55 -08001549 * Validate a String Bluetooth address, such as "00:43:A8:23:10:F0"
Nick Pelly55e66f12009-09-18 11:37:06 -07001550 * <p>Alphabetic characters must be uppercase to be valid.
Nick Pelly005b2282009-09-10 10:21:56 -07001551 *
1552 * @param address Bluetooth address as string
1553 * @return true if the address is valid, false otherwise
1554 */
1555 public static boolean checkBluetoothAddress(String address) {
1556 if (address == null || address.length() != ADDRESS_LENGTH) {
1557 return false;
1558 }
1559 for (int i = 0; i < ADDRESS_LENGTH; i++) {
1560 char c = address.charAt(i);
1561 switch (i % 3) {
1562 case 0:
1563 case 1:
Nick Pelly55e66f12009-09-18 11:37:06 -07001564 if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F')) {
1565 // hex character, OK
1566 break;
Nick Pelly005b2282009-09-10 10:21:56 -07001567 }
1568 return false;
1569 case 2:
1570 if (c == ':') {
1571 break; // OK
1572 }
1573 return false;
1574 }
1575 }
1576 return true;
1577 }
fredc0f420372012-04-12 00:02:00 -07001578
1579 /*package*/ IBluetoothManager getBluetoothManager() {
1580 return mManagerService;
1581 }
1582
fredcbf072a72012-05-09 16:52:50 -07001583 private ArrayList<IBluetoothManagerCallback> mProxyServiceStateCallbacks = new ArrayList<IBluetoothManagerCallback>();
fredcd6883532012-04-25 17:46:13 -07001584
fredc903ac6f2012-04-24 03:59:57 -07001585 /*package*/ IBluetooth getBluetoothService(IBluetoothManagerCallback cb) {
fredc0f420372012-04-12 00:02:00 -07001586 synchronized (mManagerCallback) {
fredcd6883532012-04-25 17:46:13 -07001587 if (cb == null) {
fredcbf072a72012-05-09 16:52:50 -07001588 Log.w(TAG, "getBluetoothService() called with no BluetoothManagerCallback");
1589 } else if (!mProxyServiceStateCallbacks.contains(cb)) {
1590 mProxyServiceStateCallbacks.add(cb);
fredc903ac6f2012-04-24 03:59:57 -07001591 }
1592 }
1593 return mService;
1594 }
1595
1596 /*package*/ void removeServiceStateCallback(IBluetoothManagerCallback cb) {
1597 synchronized (mManagerCallback) {
fredcbf072a72012-05-09 16:52:50 -07001598 mProxyServiceStateCallbacks.remove(cb);
fredc0f420372012-04-12 00:02:00 -07001599 }
1600 }
Matthew Xieddf7e472013-03-01 18:41:02 -08001601
1602 /**
Matthew Xiecdd94e32013-04-11 16:36:26 -07001603 * Callback interface used to deliver LE scan results.
Matthew Xieddf7e472013-03-01 18:41:02 -08001604 *
Matthew Xiecdd94e32013-04-11 16:36:26 -07001605 * @see #startLeScan(LeScanCallback)
1606 * @see #startLeScan(UUID[], LeScanCallback)
Matthew Xieddf7e472013-03-01 18:41:02 -08001607 */
Matthew Xiecdd94e32013-04-11 16:36:26 -07001608 public interface LeScanCallback {
1609 /**
1610 * Callback reporting an LE device found during a device scan initiated
1611 * by the {@link BluetoothAdapter#startLeScan} function.
1612 *
1613 * @param device Identifies the remote device
1614 * @param rssi The RSSI value for the remote device as reported by the
1615 * Bluetooth hardware. 0 if no RSSI value is available.
1616 * @param scanRecord The content of the advertisement record offered by
1617 * the remote device.
1618 */
1619 public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord);
Matthew Xieddf7e472013-03-01 18:41:02 -08001620 }
1621
1622 /**
1623 * Starts a scan for Bluetooth LE devices.
1624 *
1625 * <p>Results of the scan are reported using the
Matthew Xiecdd94e32013-04-11 16:36:26 -07001626 * {@link LeScanCallback#onLeScan} callback.
Matthew Xieddf7e472013-03-01 18:41:02 -08001627 *
Matthew Xied5752332013-04-24 17:51:37 -07001628 * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN} permission.
Matthew Xieddf7e472013-03-01 18:41:02 -08001629 *
Matthew Xiecdd94e32013-04-11 16:36:26 -07001630 * @param callback the callback LE scan results are delivered
Matthew Xieddf7e472013-03-01 18:41:02 -08001631 * @return true, if the scan was started successfully
Wei Wangaf74e662014-07-09 14:03:42 -07001632 * @deprecated use {@link BluetoothLeScanner#startScan(List, ScanSettings, ScanCallback)}
1633 * instead.
Matthew Xieddf7e472013-03-01 18:41:02 -08001634 */
Wei Wangaf74e662014-07-09 14:03:42 -07001635 @Deprecated
Matthew Xiecdd94e32013-04-11 16:36:26 -07001636 public boolean startLeScan(LeScanCallback callback) {
1637 return startLeScan(null, callback);
Matthew Xieddf7e472013-03-01 18:41:02 -08001638 }
1639
1640 /**
1641 * Starts a scan for Bluetooth LE devices, looking for devices that
1642 * advertise given services.
1643 *
1644 * <p>Devices which advertise all specified services are reported using the
Matthew Xiecdd94e32013-04-11 16:36:26 -07001645 * {@link LeScanCallback#onLeScan} callback.
Matthew Xieddf7e472013-03-01 18:41:02 -08001646 *
Matthew Xied5752332013-04-24 17:51:37 -07001647 * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN} permission.
Matthew Xieddf7e472013-03-01 18:41:02 -08001648 *
1649 * @param serviceUuids Array of services to look for
Matthew Xiecdd94e32013-04-11 16:36:26 -07001650 * @param callback the callback LE scan results are delivered
Matthew Xieddf7e472013-03-01 18:41:02 -08001651 * @return true, if the scan was started successfully
Wei Wangaf74e662014-07-09 14:03:42 -07001652 * @deprecated use {@link BluetoothLeScanner#startScan(List, ScanSettings, ScanCallback)}
1653 * instead.
Matthew Xieddf7e472013-03-01 18:41:02 -08001654 */
Wei Wangaf74e662014-07-09 14:03:42 -07001655 @Deprecated
Wei Wangc3059cc2014-07-23 23:34:00 -07001656 public boolean startLeScan(final UUID[] serviceUuids, final LeScanCallback callback) {
Matthew Xiecdd94e32013-04-11 16:36:26 -07001657 if (DBG) Log.d(TAG, "startLeScan(): " + serviceUuids);
Matthew Xiecdd94e32013-04-11 16:36:26 -07001658 if (callback == null) {
1659 if (DBG) Log.e(TAG, "startLeScan: null callback");
Matthew Xieddf7e472013-03-01 18:41:02 -08001660 return false;
1661 }
Wei Wangc3059cc2014-07-23 23:34:00 -07001662 BluetoothLeScanner scanner = getBluetoothLeScanner();
1663 if (scanner == null) {
1664 if (DBG) Log.e(TAG, "startLeScan: cannot get BluetoothLeScanner");
1665 return false;
1666 }
Matthew Xieddf7e472013-03-01 18:41:02 -08001667
Matthew Xiecdd94e32013-04-11 16:36:26 -07001668 synchronized(mLeScanClients) {
1669 if (mLeScanClients.containsKey(callback)) {
1670 if (DBG) Log.e(TAG, "LE Scan has already started");
1671 return false;
1672 }
1673
1674 try {
1675 IBluetoothGatt iGatt = mManagerService.getBluetoothGatt();
Matthew Xie32ab77b2013-05-08 19:26:57 -07001676 if (iGatt == null) {
1677 // BLE is not supported
1678 return false;
1679 }
1680
Wei Wangc3059cc2014-07-23 23:34:00 -07001681 ScanCallback scanCallback = new ScanCallback() {
1682 @Override
1683 public void onScanResult(int callbackType, ScanResult result) {
1684 if (callbackType != ScanSettings.CALLBACK_TYPE_ALL_MATCHES) {
1685 // Should not happen.
1686 Log.e(TAG, "LE Scan has already started");
1687 return;
1688 }
1689 ScanRecord scanRecord = result.getScanRecord();
1690 if (scanRecord == null) {
1691 return;
1692 }
1693 if (serviceUuids != null) {
1694 List<ParcelUuid> uuids = new ArrayList<ParcelUuid>();
1695 for (UUID uuid : serviceUuids) {
1696 uuids.add(new ParcelUuid(uuid));
1697 }
1698 List<ParcelUuid> scanServiceUuids = scanRecord.getServiceUuids();
1699 if (scanServiceUuids == null || !scanServiceUuids.containsAll(uuids)) {
1700 if (DBG) Log.d(TAG, "uuids does not match");
1701 return;
1702 }
1703 }
1704 callback.onLeScan(result.getDevice(), result.getRssi(),
1705 scanRecord.getBytes());
1706 }
1707 };
1708 ScanSettings settings = new ScanSettings.Builder()
1709 .setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES)
1710 .setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build();
1711
1712 List<ScanFilter> filters = new ArrayList<ScanFilter>();
1713 if (serviceUuids != null && serviceUuids.length > 0) {
1714 // Note scan filter does not support matching an UUID array so we put one
1715 // UUID to hardware and match the whole array in callback.
1716 ScanFilter filter = new ScanFilter.Builder().setServiceUuid(
1717 new ParcelUuid(serviceUuids[0])).build();
1718 filters.add(filter);
Matthew Xiecdd94e32013-04-11 16:36:26 -07001719 }
Wei Wangc3059cc2014-07-23 23:34:00 -07001720 scanner.startScan(filters, settings, scanCallback);
1721
1722 mLeScanClients.put(callback, scanCallback);
1723 return true;
1724
Matthew Xiecdd94e32013-04-11 16:36:26 -07001725 } catch (RemoteException e) {
1726 Log.e(TAG,"",e);
1727 }
1728 }
1729 return false;
Matthew Xieddf7e472013-03-01 18:41:02 -08001730 }
1731
1732 /**
1733 * Stops an ongoing Bluetooth LE device scan.
1734 *
Matthew Xied5752332013-04-24 17:51:37 -07001735 * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN} permission.
Matthew Xiecdd94e32013-04-11 16:36:26 -07001736 *
1737 * @param callback used to identify which scan to stop
1738 * must be the same handle used to start the scan
Wei Wangaf74e662014-07-09 14:03:42 -07001739 * @deprecated Use {@link BluetoothLeScanner#stopScan(ScanCallback)} instead.
Matthew Xieddf7e472013-03-01 18:41:02 -08001740 */
Wei Wangaf74e662014-07-09 14:03:42 -07001741 @Deprecated
Matthew Xiecdd94e32013-04-11 16:36:26 -07001742 public void stopLeScan(LeScanCallback callback) {
1743 if (DBG) Log.d(TAG, "stopLeScan()");
Wei Wangc3059cc2014-07-23 23:34:00 -07001744 BluetoothLeScanner scanner = getBluetoothLeScanner();
1745 if (scanner == null) {
1746 return;
Matthew Xieddf7e472013-03-01 18:41:02 -08001747 }
Wei Wangc3059cc2014-07-23 23:34:00 -07001748 synchronized (mLeScanClients) {
1749 ScanCallback scanCallback = mLeScanClients.remove(callback);
1750 if (scanCallback == null) {
1751 if (DBG) Log.d(TAG, "scan not started yet");
1752 return;
Matthew Xieddf7e472013-03-01 18:41:02 -08001753 }
Wei Wangc3059cc2014-07-23 23:34:00 -07001754 scanner.stopScan(scanCallback);
Prerepa Viswanadham8f2e74c2014-07-09 12:51:59 -07001755 }
Matthew Xiecdd94e32013-04-11 16:36:26 -07001756 }
Nick Pellybd022f42009-08-14 18:33:38 -07001757}