blob: 38a71aaa25f99464f5e57d1132f88029fb453ae2 [file] [log] [blame]
Nick Pellybd022f42009-08-14 18:33:38 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package android.bluetooth;
18
Nick Pellyde893f52009-09-08 13:15:33 -070019import android.annotation.SdkConstant;
20import android.annotation.SdkConstant.SdkConstantType;
Jaikumar Ganesh62c37ef2010-08-24 17:36:13 -070021import android.content.Context;
Nick Pellyf242b7b2009-10-08 00:12:45 +020022import android.os.IBinder;
Nick Pellyaef439e2009-09-28 12:33:17 -070023import android.os.ParcelUuid;
Nick Pellybd022f42009-08-14 18:33:38 -070024import android.os.RemoteException;
Nick Pellyf242b7b2009-10-08 00:12:45 +020025import android.os.ServiceManager;
Nick Pellybd022f42009-08-14 18:33:38 -070026import android.util.Log;
Jaikumar Ganeshcc5494c2010-09-09 15:37:57 -070027import android.util.Pair;
Wei Wang18c76932013-10-29 21:05:37 -070028
Nick Pellybd022f42009-08-14 18:33:38 -070029import java.io.IOException;
Matthew Xiecdd94e32013-04-11 16:36:26 -070030import java.lang.ref.WeakReference;
fredc903ac6f2012-04-24 03:59:57 -070031import java.util.ArrayList;
Jaikumar Ganeshcc5494c2010-09-09 15:37:57 -070032import java.util.Arrays;
Nick Pellybd022f42009-08-14 18:33:38 -070033import java.util.Collections;
Matthew Xiecdd94e32013-04-11 16:36:26 -070034import java.util.HashMap;
Wei Wang18c76932013-10-29 21:05:37 -070035import java.util.HashSet;
Jeff Sharkeyfea17de2013-06-11 14:13:09 -070036import java.util.Locale;
Matthew Xiecdd94e32013-04-11 16:36:26 -070037import java.util.Map;
Nick Pelly24bb9b82009-10-02 20:34:18 -070038import java.util.Set;
Nick Pelly16fb88a2009-10-07 07:44:03 +020039import java.util.UUID;
Nick Pellybd022f42009-08-14 18:33:38 -070040
41/**
Scott Main9fab0ae2009-11-03 18:17:59 -080042 * Represents the local device Bluetooth adapter. The {@link BluetoothAdapter}
43 * lets you perform fundamental Bluetooth tasks, such as initiate
44 * device discovery, query a list of bonded (paired) devices,
45 * instantiate a {@link BluetoothDevice} using a known MAC address, and create
46 * a {@link BluetoothServerSocket} to listen for connection requests from other
Matthew Xieb30f91e2013-05-29 10:19:06 -070047 * devices, and start a scan for Bluetooth LE devices.
Scott Main9fab0ae2009-11-03 18:17:59 -080048 *
49 * <p>To get a {@link BluetoothAdapter} representing the local Bluetooth
Kim Schulz0d376052013-08-22 11:18:02 +020050 * adapter, when running on JELLY_BEAN_MR1 and below, call the
Matthew Xieb30f91e2013-05-29 10:19:06 -070051 * static {@link #getDefaultAdapter} method; when running on JELLY_BEAN_MR2 and
52 * higher, retrieve it through
53 * {@link android.content.Context#getSystemService} with
54 * {@link android.content.Context#BLUETOOTH_SERVICE}.
Scott Main9fab0ae2009-11-03 18:17:59 -080055 * Fundamentally, this is your starting point for all
56 * Bluetooth actions. Once you have the local adapter, you can get a set of
57 * {@link BluetoothDevice} objects representing all paired devices with
58 * {@link #getBondedDevices()}; start device discovery with
59 * {@link #startDiscovery()}; or create a {@link BluetoothServerSocket} to
60 * listen for incoming connection requests with
Matthew Xieb30f91e2013-05-29 10:19:06 -070061 * {@link #listenUsingRfcommWithServiceRecord(String,UUID)}; or start a scan for
62 * Bluetooth LE devices with {@link #startLeScan(LeScanCallback callback)}.
Scott Main9fab0ae2009-11-03 18:17:59 -080063 *
64 * <p class="note"><strong>Note:</strong>
65 * Most methods require the {@link android.Manifest.permission#BLUETOOTH}
66 * permission and some also require the
67 * {@link android.Manifest.permission#BLUETOOTH_ADMIN} permission.
68 *
Joe Fernandez3aef8e1d2011-12-20 10:38:34 -080069 * <div class="special reference">
70 * <h3>Developer Guides</h3>
71 * <p>For more information about using Bluetooth, read the
72 * <a href="{@docRoot}guide/topics/wireless/bluetooth.html">Bluetooth</a> developer guide.</p>
73 * </div>
74 *
Scott Main9fab0ae2009-11-03 18:17:59 -080075 * {@see BluetoothDevice}
76 * {@see BluetoothServerSocket}
Nick Pellybd022f42009-08-14 18:33:38 -070077 */
78public final class BluetoothAdapter {
79 private static final String TAG = "BluetoothAdapter";
fredc0f420372012-04-12 00:02:00 -070080 private static final boolean DBG = true;
Matthew Xie3b6214f2012-08-29 00:12:29 -070081 private static final boolean VDBG = false;
Nick Pellybd022f42009-08-14 18:33:38 -070082
Nick Pellyde893f52009-09-08 13:15:33 -070083 /**
Nick Pellyb24e11b2009-09-08 17:40:43 -070084 * Sentinel error value for this class. Guaranteed to not equal any other
85 * integer constant in this class. Provided as a convenience for functions
86 * that require a sentinel error value, for example:
87 * <p><code>Intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
88 * BluetoothAdapter.ERROR)</code>
89 */
Nick Pelly005b2282009-09-10 10:21:56 -070090 public static final int ERROR = Integer.MIN_VALUE;
Nick Pellyb24e11b2009-09-08 17:40:43 -070091
92 /**
Nick Pellyde893f52009-09-08 13:15:33 -070093 * Broadcast Action: The state of the local Bluetooth adapter has been
94 * changed.
95 * <p>For example, Bluetooth has been turned on or off.
Nick Pelly005b2282009-09-10 10:21:56 -070096 * <p>Always contains the extra fields {@link #EXTRA_STATE} and {@link
Nick Pellyde893f52009-09-08 13:15:33 -070097 * #EXTRA_PREVIOUS_STATE} containing the new and old states
98 * respectively.
99 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} to receive.
100 */
101 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
102 public static final String ACTION_STATE_CHANGED =
Nick Pelly005b2282009-09-10 10:21:56 -0700103 "android.bluetooth.adapter.action.STATE_CHANGED";
Nick Pellybd022f42009-08-14 18:33:38 -0700104
Nick Pellyde893f52009-09-08 13:15:33 -0700105 /**
106 * Used as an int extra field in {@link #ACTION_STATE_CHANGED}
107 * intents to request the current power state. Possible values are:
108 * {@link #STATE_OFF},
109 * {@link #STATE_TURNING_ON},
110 * {@link #STATE_ON},
111 * {@link #STATE_TURNING_OFF},
112 */
113 public static final String EXTRA_STATE =
Nick Pelly005b2282009-09-10 10:21:56 -0700114 "android.bluetooth.adapter.extra.STATE";
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 previous 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_PREVIOUS_STATE =
Nick Pelly005b2282009-09-10 10:21:56 -0700124 "android.bluetooth.adapter.extra.PREVIOUS_STATE";
Nick Pellybd022f42009-08-14 18:33:38 -0700125
Nick Pellyde893f52009-09-08 13:15:33 -0700126 /**
127 * Indicates the local Bluetooth adapter is off.
128 */
Nick Pelly005b2282009-09-10 10:21:56 -0700129 public static final int STATE_OFF = 10;
Nick Pellyde893f52009-09-08 13:15:33 -0700130 /**
131 * Indicates the local Bluetooth adapter is turning on. However local
132 * clients should wait for {@link #STATE_ON} before attempting to
133 * use the adapter.
134 */
Nick Pelly005b2282009-09-10 10:21:56 -0700135 public static final int STATE_TURNING_ON = 11;
Nick Pellyde893f52009-09-08 13:15:33 -0700136 /**
137 * Indicates the local Bluetooth adapter is on, and ready for use.
138 */
Nick Pelly005b2282009-09-10 10:21:56 -0700139 public static final int STATE_ON = 12;
Nick Pellyde893f52009-09-08 13:15:33 -0700140 /**
141 * Indicates the local Bluetooth adapter is turning off. Local clients
142 * should immediately attempt graceful disconnection of any remote links.
143 */
Nick Pelly005b2282009-09-10 10:21:56 -0700144 public static final int STATE_TURNING_OFF = 13;
Nick Pellyde893f52009-09-08 13:15:33 -0700145
146 /**
Nick Pelly18b1e792009-09-24 11:14:15 -0700147 * Activity Action: Show a system activity that requests discoverable mode.
Scott Main6d95fc02009-11-19 17:00:19 -0800148 * This activity will also request the user to turn on Bluetooth if it
Nick Pelly1acdcc12009-09-28 10:33:55 -0700149 * is not currently enabled.
Nick Pelly18b1e792009-09-24 11:14:15 -0700150 * <p>Discoverable mode is equivalent to {@link
151 * #SCAN_MODE_CONNECTABLE_DISCOVERABLE}. It allows remote devices to see
152 * this Bluetooth adapter when they perform a discovery.
Scott Main6d95fc02009-11-19 17:00:19 -0800153 * <p>For privacy, Android is not discoverable by default.
154 * <p>The sender of this Intent can optionally use extra field {@link
Nick Pelly18b1e792009-09-24 11:14:15 -0700155 * #EXTRA_DISCOVERABLE_DURATION} to request the duration of
156 * discoverability. Currently the default duration is 120 seconds, and
157 * maximum duration is capped at 300 seconds for each request.
158 * <p>Notification of the result of this activity is posted using the
159 * {@link android.app.Activity#onActivityResult} callback. The
160 * <code>resultCode</code>
Michael Chancdd28642009-11-05 18:29:01 -0800161 * will be the duration (in seconds) of discoverability or
162 * {@link android.app.Activity#RESULT_CANCELED} if the user rejected
163 * discoverability or an error has occurred.
Nick Pelly18b1e792009-09-24 11:14:15 -0700164 * <p>Applications can also listen for {@link #ACTION_SCAN_MODE_CHANGED}
Scott Main6d95fc02009-11-19 17:00:19 -0800165 * for global notification whenever the scan mode changes. For example, an
166 * application can be notified when the device has ended discoverability.
Nick Pelly1acdcc12009-09-28 10:33:55 -0700167 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
Nick Pelly18b1e792009-09-24 11:14:15 -0700168 */
169 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
170 public static final String ACTION_REQUEST_DISCOVERABLE =
171 "android.bluetooth.adapter.action.REQUEST_DISCOVERABLE";
172
173 /**
174 * Used as an optional int extra field in {@link
175 * #ACTION_REQUEST_DISCOVERABLE} intents to request a specific duration
176 * for discoverability in seconds. The current default is 120 seconds, and
177 * requests over 300 seconds will be capped. These values could change.
178 */
179 public static final String EXTRA_DISCOVERABLE_DURATION =
180 "android.bluetooth.adapter.extra.DISCOVERABLE_DURATION";
181
182 /**
Wei Wang18c76932013-10-29 21:05:37 -0700183 * Activity Action: Show a system activity to request BLE advertising.<br>
184 * If the device is not doing BLE advertising, this activity will start BLE advertising for the
185 * device, otherwise it will continue BLE advertising using the current
186 * {@link BluetoothAdvScanData}. <br>
187 * Note this activity will also request the user to turn on Bluetooth if it's not currently
188 * enabled.
189 * @hide
190 */
191 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
192 public static final String ACTION_START_ADVERTISING =
193 "android.bluetooth.adapter.action.START_ADVERTISING";
194
195 /**
196 * Activity Action: Stop the current BLE advertising.
197 * @hide
198 */
199 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
200 public static final String ACTION_STOP_ADVERTISING =
201 "android.bluetooth.adapter.action.STOP_ADVERTISING";
202
203 /**
204 * Broadcast Action: Indicate BLE Advertising is started.
205 * @hide
206 */
207 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
208 public static final String ACTION_BLUETOOTH_ADVERTISING_STARTED =
209 "android.bluetooth.adapter.action.ADVERTISING_STARTED";
210
211 /**
212 * Broadcast Action: Indicated BLE Advertising is stopped.
213 * @hide
214 */
215 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
216 public static final String ACTION_BLUETOOTH_ADVERTISING_STOPPED =
217 "android.bluetooth.adapter.action.ADVERTISING_STOPPED";
218
219 /**
Nick Pelly1acdcc12009-09-28 10:33:55 -0700220 * Activity Action: Show a system activity that allows the user to turn on
221 * Bluetooth.
222 * <p>This system activity will return once Bluetooth has completed turning
223 * on, or the user has decided not to turn Bluetooth on.
224 * <p>Notification of the result of this activity is posted using the
225 * {@link android.app.Activity#onActivityResult} callback. The
226 * <code>resultCode</code>
Michael Chancdd28642009-11-05 18:29:01 -0800227 * will be {@link android.app.Activity#RESULT_OK} if Bluetooth has been
228 * turned on or {@link android.app.Activity#RESULT_CANCELED} if the user
229 * has rejected the request or an error has occurred.
Nick Pelly1acdcc12009-09-28 10:33:55 -0700230 * <p>Applications can also listen for {@link #ACTION_STATE_CHANGED}
231 * for global notification whenever Bluetooth is turned on or off.
232 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
233 */
234 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
235 public static final String ACTION_REQUEST_ENABLE =
236 "android.bluetooth.adapter.action.REQUEST_ENABLE";
237
238 /**
Nick Pellyde893f52009-09-08 13:15:33 -0700239 * Broadcast Action: Indicates the Bluetooth scan mode of the local Adapter
240 * has changed.
Nick Pelly005b2282009-09-10 10:21:56 -0700241 * <p>Always contains the extra fields {@link #EXTRA_SCAN_MODE} and {@link
Nick Pellyde893f52009-09-08 13:15:33 -0700242 * #EXTRA_PREVIOUS_SCAN_MODE} containing the new and old scan modes
243 * respectively.
244 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
245 */
246 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
247 public static final String ACTION_SCAN_MODE_CHANGED =
Nick Pelly005b2282009-09-10 10:21:56 -0700248 "android.bluetooth.adapter.action.SCAN_MODE_CHANGED";
Nick Pellyde893f52009-09-08 13:15:33 -0700249
250 /**
251 * Used as an int extra field in {@link #ACTION_SCAN_MODE_CHANGED}
252 * intents to request the current scan mode. Possible values are:
253 * {@link #SCAN_MODE_NONE},
254 * {@link #SCAN_MODE_CONNECTABLE},
255 * {@link #SCAN_MODE_CONNECTABLE_DISCOVERABLE},
256 */
Nick Pelly005b2282009-09-10 10:21:56 -0700257 public static final String EXTRA_SCAN_MODE = "android.bluetooth.adapter.extra.SCAN_MODE";
Nick Pellyde893f52009-09-08 13:15:33 -0700258 /**
259 * Used as an int extra field in {@link #ACTION_SCAN_MODE_CHANGED}
260 * intents to request the previous scan mode. Possible values are:
261 * {@link #SCAN_MODE_NONE},
262 * {@link #SCAN_MODE_CONNECTABLE},
263 * {@link #SCAN_MODE_CONNECTABLE_DISCOVERABLE},
264 */
265 public static final String EXTRA_PREVIOUS_SCAN_MODE =
Nick Pelly005b2282009-09-10 10:21:56 -0700266 "android.bluetooth.adapter.extra.PREVIOUS_SCAN_MODE";
Nick Pellyde893f52009-09-08 13:15:33 -0700267
268 /**
269 * Indicates that both inquiry scan and page scan are disabled on the local
270 * Bluetooth adapter. Therefore this device is neither discoverable
271 * nor connectable from remote Bluetooth devices.
272 */
Nick Pelly005b2282009-09-10 10:21:56 -0700273 public static final int SCAN_MODE_NONE = 20;
Nick Pellyde893f52009-09-08 13:15:33 -0700274 /**
275 * Indicates that inquiry scan is disabled, but page scan is enabled on the
276 * local Bluetooth adapter. Therefore this device is not discoverable from
277 * remote Bluetooth devices, but is connectable from remote devices that
278 * have previously discovered this device.
279 */
Nick Pelly005b2282009-09-10 10:21:56 -0700280 public static final int SCAN_MODE_CONNECTABLE = 21;
Nick Pellyde893f52009-09-08 13:15:33 -0700281 /**
282 * Indicates that both inquiry scan and page scan are enabled on the local
283 * Bluetooth adapter. Therefore this device is both discoverable and
284 * connectable from remote Bluetooth devices.
285 */
Nick Pelly005b2282009-09-10 10:21:56 -0700286 public static final int SCAN_MODE_CONNECTABLE_DISCOVERABLE = 23;
Nick Pellybd022f42009-08-14 18:33:38 -0700287
Nick Pelly005b2282009-09-10 10:21:56 -0700288 /**
289 * Broadcast Action: The local Bluetooth adapter has started the remote
290 * device discovery process.
291 * <p>This usually involves an inquiry scan of about 12 seconds, followed
292 * by a page scan of each new device to retrieve its Bluetooth name.
293 * <p>Register for {@link BluetoothDevice#ACTION_FOUND} to be notified as
294 * remote Bluetooth devices are found.
295 * <p>Device discovery is a heavyweight procedure. New connections to
296 * remote Bluetooth devices should not be attempted while discovery is in
297 * progress, and existing connections will experience limited bandwidth
298 * and high latency. Use {@link #cancelDiscovery()} to cancel an ongoing
299 * discovery.
300 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} to receive.
301 */
302 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
303 public static final String ACTION_DISCOVERY_STARTED =
304 "android.bluetooth.adapter.action.DISCOVERY_STARTED";
305 /**
306 * Broadcast Action: The local Bluetooth adapter has finished the device
307 * discovery process.
308 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} to receive.
309 */
310 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
311 public static final String ACTION_DISCOVERY_FINISHED =
312 "android.bluetooth.adapter.action.DISCOVERY_FINISHED";
313
314 /**
315 * Broadcast Action: The local Bluetooth adapter has changed its friendly
316 * Bluetooth name.
317 * <p>This name is visible to remote Bluetooth devices.
318 * <p>Always contains the extra field {@link #EXTRA_LOCAL_NAME} containing
319 * the name.
320 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} to receive.
321 */
322 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
323 public static final String ACTION_LOCAL_NAME_CHANGED =
324 "android.bluetooth.adapter.action.LOCAL_NAME_CHANGED";
325 /**
326 * Used as a String extra field in {@link #ACTION_LOCAL_NAME_CHANGED}
327 * intents to request the local Bluetooth name.
328 */
329 public static final String EXTRA_LOCAL_NAME = "android.bluetooth.adapter.extra.LOCAL_NAME";
330
Jaikumar Ganesh62c37ef2010-08-24 17:36:13 -0700331 /**
332 * Intent used to broadcast the change in connection state of the local
333 * Bluetooth adapter to a profile of the remote device. When the adapter is
334 * not connected to any profiles of any remote devices and it attempts a
335 * connection to a profile this intent will sent. Once connected, this intent
336 * will not be sent for any more connection attempts to any profiles of any
337 * remote device. When the adapter disconnects from the last profile its
338 * connected to of any remote device, this intent will be sent.
339 *
340 * <p> This intent is useful for applications that are only concerned about
341 * whether the local adapter is connected to any profile of any device and
342 * are not really concerned about which profile. For example, an application
343 * which displays an icon to display whether Bluetooth is connected or not
344 * can use this intent.
345 *
346 * <p>This intent will have 3 extras:
Jaikumar Ganesh0b5b35f2011-02-01 16:47:11 -0800347 * {@link #EXTRA_CONNECTION_STATE} - The current connection state.
348 * {@link #EXTRA_PREVIOUS_CONNECTION_STATE}- The previous connection state.
Jaikumar Ganesh62c37ef2010-08-24 17:36:13 -0700349 * {@link BluetoothDevice#EXTRA_DEVICE} - The remote device.
350 *
Jaikumar Ganesh0b5b35f2011-02-01 16:47:11 -0800351 * {@link #EXTRA_CONNECTION_STATE} or {@link #EXTRA_PREVIOUS_CONNECTION_STATE}
352 * can be any of {@link #STATE_DISCONNECTED}, {@link #STATE_CONNECTING},
Jaikumar Ganesh62c37ef2010-08-24 17:36:13 -0700353 * {@link #STATE_CONNECTED}, {@link #STATE_DISCONNECTING}.
354 *
355 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} to receive.
356 */
357 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
358 public static final String ACTION_CONNECTION_STATE_CHANGED =
359 "android.bluetooth.adapter.action.CONNECTION_STATE_CHANGED";
360
361 /**
362 * Extra used by {@link #ACTION_CONNECTION_STATE_CHANGED}
363 *
364 * This extra represents the current connection state.
365 */
366 public static final String EXTRA_CONNECTION_STATE =
367 "android.bluetooth.adapter.extra.CONNECTION_STATE";
368
369 /**
370 * Extra used by {@link #ACTION_CONNECTION_STATE_CHANGED}
371 *
372 * This extra represents the previous connection state.
373 */
374 public static final String EXTRA_PREVIOUS_CONNECTION_STATE =
375 "android.bluetooth.adapter.extra.PREVIOUS_CONNECTION_STATE";
376
377 /** The profile is in disconnected state */
378 public static final int STATE_DISCONNECTED = 0;
379 /** The profile is in connecting state */
380 public static final int STATE_CONNECTING = 1;
381 /** The profile is in connected state */
382 public static final int STATE_CONNECTED = 2;
383 /** The profile is in disconnecting state */
384 public static final int STATE_DISCONNECTING = 3;
385
Nick Pellyf242b7b2009-10-08 00:12:45 +0200386 /** @hide */
fredc0f420372012-04-12 00:02:00 -0700387 public static final String BLUETOOTH_MANAGER_SERVICE = "bluetooth_manager";
Nick Pellyf242b7b2009-10-08 00:12:45 +0200388
Nick Pelly005b2282009-09-10 10:21:56 -0700389 private static final int ADDRESS_LENGTH = 17;
Nick Pellybd022f42009-08-14 18:33:38 -0700390
Nick Pellyf242b7b2009-10-08 00:12:45 +0200391 /**
Jake Hambyf51eada2010-09-21 13:39:53 -0700392 * Lazily initialized singleton. Guaranteed final after first object
Nick Pellyf242b7b2009-10-08 00:12:45 +0200393 * constructed.
394 */
395 private static BluetoothAdapter sAdapter;
396
fredc0f420372012-04-12 00:02:00 -0700397 private final IBluetoothManager mManagerService;
398 private IBluetooth mService;
Nick Pellybd022f42009-08-14 18:33:38 -0700399
Matthew Xiecdd94e32013-04-11 16:36:26 -0700400 private final Map<LeScanCallback, GattCallbackWrapper> mLeScanClients;
Wei Wang18c76932013-10-29 21:05:37 -0700401 private BluetoothAdvScanData mBluetoothAdvScanData = null;
402 private GattCallbackWrapper mAdvertisingCallback;
Matthew Xie484867a2011-08-25 16:45:58 -0700403
Nick Pellybd022f42009-08-14 18:33:38 -0700404 /**
Nick Pellyf242b7b2009-10-08 00:12:45 +0200405 * Get a handle to the default local Bluetooth adapter.
406 * <p>Currently Android only supports one Bluetooth adapter, but the API
407 * could be extended to support more. This will always return the default
408 * adapter.
409 * @return the default local adapter, or null if Bluetooth is not supported
410 * on this hardware platform
411 */
412 public static synchronized BluetoothAdapter getDefaultAdapter() {
413 if (sAdapter == null) {
fredc0f420372012-04-12 00:02:00 -0700414 IBinder b = ServiceManager.getService(BLUETOOTH_MANAGER_SERVICE);
Nick Pellyf242b7b2009-10-08 00:12:45 +0200415 if (b != null) {
fredc0f420372012-04-12 00:02:00 -0700416 IBluetoothManager managerService = IBluetoothManager.Stub.asInterface(b);
417 sAdapter = new BluetoothAdapter(managerService);
Jaikumar Ganeshe4caddb2012-01-25 16:16:48 -0800418 } else {
419 Log.e(TAG, "Bluetooth binder is null");
Nick Pellyf242b7b2009-10-08 00:12:45 +0200420 }
421 }
422 return sAdapter;
423 }
424
425 /**
426 * Use {@link #getDefaultAdapter} to get the BluetoothAdapter instance.
Nick Pellybd022f42009-08-14 18:33:38 -0700427 */
fredc0f420372012-04-12 00:02:00 -0700428 BluetoothAdapter(IBluetoothManager managerService) {
429
430 if (managerService == null) {
431 throw new IllegalArgumentException("bluetooth manager service is null");
Nick Pellybd022f42009-08-14 18:33:38 -0700432 }
fredc0f420372012-04-12 00:02:00 -0700433 try {
434 mService = managerService.registerAdapter(mManagerCallback);
435 } catch (RemoteException e) {Log.e(TAG, "", e);}
436 mManagerService = managerService;
Matthew Xiecdd94e32013-04-11 16:36:26 -0700437 mLeScanClients = new HashMap<LeScanCallback, GattCallbackWrapper>();
Nick Pellybd022f42009-08-14 18:33:38 -0700438 }
439
440 /**
Nick Pelly45e27042009-08-19 11:00:00 -0700441 * Get a {@link BluetoothDevice} object for the given Bluetooth hardware
442 * address.
443 * <p>Valid Bluetooth hardware addresses must be upper case, in a format
Nick Pelly005b2282009-09-10 10:21:56 -0700444 * such as "00:11:22:33:AA:BB". The helper {@link #checkBluetoothAddress} is
445 * available to validate a Bluetooth address.
Nick Pelly45e27042009-08-19 11:00:00 -0700446 * <p>A {@link BluetoothDevice} will always be returned for a valid
447 * hardware address, even if this adapter has never seen that device.
Nick Pellyde893f52009-09-08 13:15:33 -0700448 *
Nick Pellybd022f42009-08-14 18:33:38 -0700449 * @param address valid Bluetooth MAC address
Nick Pelly45e27042009-08-19 11:00:00 -0700450 * @throws IllegalArgumentException if address is invalid
Nick Pellybd022f42009-08-14 18:33:38 -0700451 */
452 public BluetoothDevice getRemoteDevice(String address) {
453 return new BluetoothDevice(address);
454 }
455
456 /**
Nick Pelly75596b42011-12-07 15:03:55 -0800457 * Get a {@link BluetoothDevice} object for the given Bluetooth hardware
458 * address.
459 * <p>Valid Bluetooth hardware addresses must be 6 bytes. This method
460 * expects the address in network byte order (MSB first).
461 * <p>A {@link BluetoothDevice} will always be returned for a valid
462 * hardware address, even if this adapter has never seen that device.
463 *
464 * @param address Bluetooth MAC address (6 bytes)
465 * @throws IllegalArgumentException if address is invalid
466 */
467 public BluetoothDevice getRemoteDevice(byte[] address) {
468 if (address == null || address.length != 6) {
469 throw new IllegalArgumentException("Bluetooth address must have 6 bytes");
470 }
Jeff Sharkeyfea17de2013-06-11 14:13:09 -0700471 return new BluetoothDevice(String.format(Locale.US, "%02X:%02X:%02X:%02X:%02X:%02X",
Nick Pelly75596b42011-12-07 15:03:55 -0800472 address[0], address[1], address[2], address[3], address[4], address[5]));
473 }
474
475 /**
Wei Wang18c76932013-10-29 21:05:37 -0700476 * Returns a {@link BluetoothAdvScanData} object representing advertising data.
477 * @hide
478 */
479 public BluetoothAdvScanData getAdvScanData() {
480 try {
481 IBluetoothGatt iGatt = mManagerService.getBluetoothGatt();
482 if (iGatt == null) {
483 // BLE is not supported
484 Log.e(TAG, "failed to start, iGatt null");
485 return null;
486 }
487 if (mBluetoothAdvScanData == null) {
488 mBluetoothAdvScanData = new BluetoothAdvScanData(iGatt, BluetoothAdvScanData.AD);
489 }
490 return mBluetoothAdvScanData;
491 } catch (RemoteException e) {
492 Log.e(TAG, "failed to get advScanData, error: " + e);
493 return null;
494 }
495 }
496
497
498 /**
499 * Start BLE advertising using current {@link BluetoothAdvScanData}.
500 * An app should start advertising by requesting
501 * {@link BluetoothAdapter#ACTION_START_ADVERTISING} instead of calling this method directly.
502 * <p>Requires {@link android.Manifest.permission#BLUETOOTH_PRIVILEGED}
503 *
504 * @return true if BLE avertising succeeds, false otherwise.
505 * @hide
506 */
507 public boolean startAdvertising() {
508 if (getState() != STATE_ON) return false;
509
510 try {
511 IBluetoothGatt iGatt = mManagerService.getBluetoothGatt();
512 if (iGatt == null) {
513 // BLE is not supported.
514 return false;
515 }
516 // Restart/reset advertising packets if advertising is in progress.
517 if (isAdvertising()) {
518 // Invalid advertising callback.
519 if (mAdvertisingCallback == null || mAdvertisingCallback.mLeHandle == -1) {
520 Log.e(TAG, "failed to restart advertising, invalid callback");
521 return false;
522 }
523 iGatt.startAdvertising(mAdvertisingCallback.mLeHandle);
524 return true;
525 }
526 UUID uuid = UUID.randomUUID();
527 GattCallbackWrapper wrapper =
528 new GattCallbackWrapper(this, null, null, GattCallbackWrapper.CALLBACK_TYPE_ADV);
529 iGatt.registerClient(new ParcelUuid(uuid), wrapper);
530 mAdvertisingCallback = wrapper;
531 return true;
532 } catch (RemoteException e) {
533 Log.e(TAG, "", e);
534 return false;
535 }
536 }
537
538 /**
539 * Stop BLE advertising.
540 * An app should stop advertising by requesting
541 * {@link BluetoothAdapter#ACTION_STOP_ADVERTISING} instead of calling this method directly.
542 * <p>Requires {@link android.Manifest.permission#BLUETOOTH_PRIVILEGED}
543 * @return true if BLE advertising stops, false otherwise.
544 * @hide
545 */
546 public boolean stopAdvertisting() {
547 try {
548 IBluetoothGatt iGatt = mManagerService.getBluetoothGatt();
549 if (iGatt == null) {
550 // BLE is not supported
551 return false;
552 }
553 if (mAdvertisingCallback == null) {
554 // no callback.
555 return false;
556 }
557 mAdvertisingCallback.stopAdvertising();
558 mAdvertisingCallback = null;
559 return true;
560 } catch (RemoteException e) {
561 Log.e(TAG, "", e);
562 return false;
563 }
564 }
565
566 /**
Nick Pellyde893f52009-09-08 13:15:33 -0700567 * Return true if Bluetooth is currently enabled and ready for use.
568 * <p>Equivalent to:
569 * <code>getBluetoothState() == STATE_ON</code>
570 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
Nick Pellybd022f42009-08-14 18:33:38 -0700571 *
Nick Pellyde893f52009-09-08 13:15:33 -0700572 * @return true if the local adapter is turned on
Nick Pellybd022f42009-08-14 18:33:38 -0700573 */
574 public boolean isEnabled() {
fredc0f420372012-04-12 00:02:00 -0700575
Nick Pellybd022f42009-08-14 18:33:38 -0700576 try {
fredc0f420372012-04-12 00:02:00 -0700577 synchronized(mManagerCallback) {
578 if (mService != null) return mService.isEnabled();
579 }
Nick Pellybd022f42009-08-14 18:33:38 -0700580 } catch (RemoteException e) {Log.e(TAG, "", e);}
581 return false;
582 }
583
584 /**
Nick Pellyde893f52009-09-08 13:15:33 -0700585 * Get the current state of the local Bluetooth adapter.
586 * <p>Possible return values are
587 * {@link #STATE_OFF},
588 * {@link #STATE_TURNING_ON},
589 * {@link #STATE_ON},
590 * {@link #STATE_TURNING_OFF}.
591 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
Nick Pellybd022f42009-08-14 18:33:38 -0700592 *
Nick Pellyde893f52009-09-08 13:15:33 -0700593 * @return current state of Bluetooth adapter
Nick Pellybd022f42009-08-14 18:33:38 -0700594 */
Nick Pellyde893f52009-09-08 13:15:33 -0700595 public int getState() {
Nick Pellybd022f42009-08-14 18:33:38 -0700596 try {
fredc0f420372012-04-12 00:02:00 -0700597 synchronized(mManagerCallback) {
598 if (mService != null)
599 {
fredcbf072a72012-05-09 16:52:50 -0700600 int state= mService.getState();
Matthew Xie3b6214f2012-08-29 00:12:29 -0700601 if (VDBG) Log.d(TAG, "" + hashCode() + ": getState(). Returning " + state);
fredcbf072a72012-05-09 16:52:50 -0700602 return state;
fredc0f420372012-04-12 00:02:00 -0700603 }
604 // TODO(BT) there might be a small gap during STATE_TURNING_ON that
605 // mService is null, handle that case
606 }
Nick Pellybd022f42009-08-14 18:33:38 -0700607 } catch (RemoteException e) {Log.e(TAG, "", e);}
fredcbf072a72012-05-09 16:52:50 -0700608 if (DBG) Log.d(TAG, "" + hashCode() + ": getState() : mService = null. Returning STATE_OFF");
Nick Pellyde893f52009-09-08 13:15:33 -0700609 return STATE_OFF;
Nick Pellybd022f42009-08-14 18:33:38 -0700610 }
611
612 /**
Scott Mained2a70d2009-12-09 16:07:39 -0800613 * Turn on the local Bluetooth adapter&mdash;do not use without explicit
614 * user action to turn on Bluetooth.
Nick Pellyde893f52009-09-08 13:15:33 -0700615 * <p>This powers on the underlying Bluetooth hardware, and starts all
616 * Bluetooth system services.
Scott Mained2a70d2009-12-09 16:07:39 -0800617 * <p class="caution"><strong>Bluetooth should never be enabled without
618 * direct user consent</strong>. If you want to turn on Bluetooth in order
619 * to create a wireless connection, you should use the {@link
620 * #ACTION_REQUEST_ENABLE} Intent, which will raise a dialog that requests
621 * user permission to turn on Bluetooth. The {@link #enable()} method is
622 * provided only for applications that include a user interface for changing
623 * system settings, such as a "power manager" app.</p>
Brad Fitzpatrick3219ab42009-09-25 16:31:39 +0400624 * <p>This is an asynchronous call: it will return immediately, and
Nick Pellyde893f52009-09-08 13:15:33 -0700625 * clients should listen for {@link #ACTION_STATE_CHANGED}
626 * to be notified of subsequent adapter state changes. If this call returns
627 * true, then the adapter state will immediately transition from {@link
628 * #STATE_OFF} to {@link #STATE_TURNING_ON}, and some time
629 * later transition to either {@link #STATE_OFF} or {@link
630 * #STATE_ON}. If this call returns false then there was an
631 * immediate problem that will prevent the adapter from being turned on -
632 * such as Airplane mode, or the adapter is already turned on.
Scott Mained2a70d2009-12-09 16:07:39 -0800633 * <p>Requires the {@link android.Manifest.permission#BLUETOOTH_ADMIN}
634 * permission
Nick Pellyde893f52009-09-08 13:15:33 -0700635 *
636 * @return true to indicate adapter startup has begun, or false on
637 * immediate error
Nick Pellybd022f42009-08-14 18:33:38 -0700638 */
639 public boolean enable() {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700640 if (isEnabled() == true){
641 if (DBG) Log.d(TAG, "enable(): BT is already enabled..!");
642 return true;
643 }
Nick Pellybd022f42009-08-14 18:33:38 -0700644 try {
Kausik Sinnaswamya097f512012-04-16 16:38:27 +0530645 return mManagerService.enable();
Nick Pellybd022f42009-08-14 18:33:38 -0700646 } catch (RemoteException e) {Log.e(TAG, "", e);}
647 return false;
648 }
649
650 /**
Scott Mained2a70d2009-12-09 16:07:39 -0800651 * Turn off the local Bluetooth adapter&mdash;do not use without explicit
652 * user action to turn off Bluetooth.
Nick Pellyde893f52009-09-08 13:15:33 -0700653 * <p>This gracefully shuts down all Bluetooth connections, stops Bluetooth
654 * system services, and powers down the underlying Bluetooth hardware.
Jake Hambyf51eada2010-09-21 13:39:53 -0700655 * <p class="caution"><strong>Bluetooth should never be disabled without
Scott Mained2a70d2009-12-09 16:07:39 -0800656 * direct user consent</strong>. The {@link #disable()} method is
657 * provided only for applications that include a user interface for changing
658 * system settings, such as a "power manager" app.</p>
Brad Fitzpatrick3219ab42009-09-25 16:31:39 +0400659 * <p>This is an asynchronous call: it will return immediately, and
Nick Pellyde893f52009-09-08 13:15:33 -0700660 * clients should listen for {@link #ACTION_STATE_CHANGED}
661 * to be notified of subsequent adapter state changes. If this call returns
662 * true, then the adapter state will immediately transition from {@link
663 * #STATE_ON} to {@link #STATE_TURNING_OFF}, and some time
664 * later transition to either {@link #STATE_OFF} or {@link
665 * #STATE_ON}. If this call returns false then there was an
666 * immediate problem that will prevent the adapter from being turned off -
667 * such as the adapter already being turned off.
Scott Mained2a70d2009-12-09 16:07:39 -0800668 * <p>Requires the {@link android.Manifest.permission#BLUETOOTH_ADMIN}
669 * permission
Nick Pellybd022f42009-08-14 18:33:38 -0700670 *
Nick Pellyde893f52009-09-08 13:15:33 -0700671 * @return true to indicate adapter shutdown has begun, or false on
672 * immediate error
Nick Pellybd022f42009-08-14 18:33:38 -0700673 */
674 public boolean disable() {
675 try {
fredc0f420372012-04-12 00:02:00 -0700676 return mManagerService.disable(true);
Jaikumar Ganeshe21a4ac2012-03-06 17:15:16 -0800677 } catch (RemoteException e) {Log.e(TAG, "", e);}
678 return false;
679 }
680
681 /**
682 * Turn off the local Bluetooth adapter and don't persist the setting.
683 *
684 * <p>Requires the {@link android.Manifest.permission#BLUETOOTH_ADMIN}
685 * permission
686 *
687 * @return true to indicate adapter shutdown has begun, or false on
688 * immediate error
689 * @hide
690 */
691 public boolean disable(boolean persist) {
fredc0f420372012-04-12 00:02:00 -0700692
Jaikumar Ganeshe21a4ac2012-03-06 17:15:16 -0800693 try {
fredc0f420372012-04-12 00:02:00 -0700694 return mManagerService.disable(persist);
Nick Pellybd022f42009-08-14 18:33:38 -0700695 } catch (RemoteException e) {Log.e(TAG, "", e);}
696 return false;
697 }
698
Nick Pellyde893f52009-09-08 13:15:33 -0700699 /**
700 * Returns the hardware address of the local Bluetooth adapter.
701 * <p>For example, "00:11:22:AA:BB:CC".
702 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
703 *
704 * @return Bluetooth hardware address as string
705 */
Nick Pellybd022f42009-08-14 18:33:38 -0700706 public String getAddress() {
707 try {
fredc0f420372012-04-12 00:02:00 -0700708 return mManagerService.getAddress();
Nick Pellybd022f42009-08-14 18:33:38 -0700709 } catch (RemoteException e) {Log.e(TAG, "", e);}
710 return null;
711 }
712
713 /**
Nick Pellyde893f52009-09-08 13:15:33 -0700714 * Get the friendly Bluetooth name of the local Bluetooth adapter.
715 * <p>This name is visible to remote Bluetooth devices.
716 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
Nick Pellybd022f42009-08-14 18:33:38 -0700717 *
Nick Pellyde893f52009-09-08 13:15:33 -0700718 * @return the Bluetooth name, or null on error
Nick Pellybd022f42009-08-14 18:33:38 -0700719 */
720 public String getName() {
721 try {
fredc116d1d462012-04-20 14:47:08 -0700722 return mManagerService.getName();
Nick Pellybd022f42009-08-14 18:33:38 -0700723 } catch (RemoteException e) {Log.e(TAG, "", e);}
724 return null;
725 }
726
727 /**
Zhihai Xuaf5971e2013-06-10 20:28:31 -0700728 * enable or disable Bluetooth HCI snoop log.
729 *
730 * <p>Requires the {@link android.Manifest.permission#BLUETOOTH_ADMIN}
731 * permission
732 *
733 * @return true to indicate configure HCI log successfully, or false on
734 * immediate error
735 * @hide
736 */
737 public boolean configHciSnoopLog(boolean enable) {
738 try {
739 synchronized(mManagerCallback) {
740 if (mService != null) return mService.configHciSnoopLog(enable);
741 }
742 } catch (RemoteException e) {Log.e(TAG, "", e);}
743 return false;
744 }
745
746 /**
Jaikumar Ganesh58b93c32010-11-23 20:03:10 -0800747 * Get the UUIDs supported by the local Bluetooth adapter.
748 *
749 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
750 *
751 * @return the UUIDs supported by the local Bluetooth Adapter.
752 * @hide
753 */
754 public ParcelUuid[] getUuids() {
Matthew Xie44b58ab2011-11-16 12:27:57 -0800755 if (getState() != STATE_ON) return null;
Jaikumar Ganesh58b93c32010-11-23 20:03:10 -0800756 try {
fredc0f420372012-04-12 00:02:00 -0700757 synchronized(mManagerCallback) {
758 if (mService != null) return mService.getUuids();
759 }
Jaikumar Ganesh58b93c32010-11-23 20:03:10 -0800760 } catch (RemoteException e) {Log.e(TAG, "", e);}
761 return null;
762 }
763
764 /**
Jake Hamby0f584302010-09-16 18:12:51 -0700765 * Set the friendly Bluetooth name of the local Bluetooth adapter.
Nick Pellyde893f52009-09-08 13:15:33 -0700766 * <p>This name is visible to remote Bluetooth devices.
Jake Hamby0f584302010-09-16 18:12:51 -0700767 * <p>Valid Bluetooth names are a maximum of 248 bytes using UTF-8
768 * encoding, although many remote devices can only display the first
769 * 40 characters, and some may be limited to just 20.
Jaikumar Ganeshfec86f42010-08-09 16:54:03 -0700770 * <p>If Bluetooth state is not {@link #STATE_ON}, this API
771 * will return false. After turning on Bluetooth,
772 * wait for {@link #ACTION_STATE_CHANGED} with {@link #STATE_ON}
773 * to get the updated value.
Nick Pellyde893f52009-09-08 13:15:33 -0700774 * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN}
Nick Pellybd022f42009-08-14 18:33:38 -0700775 *
Nick Pellyde893f52009-09-08 13:15:33 -0700776 * @param name a valid Bluetooth name
777 * @return true if the name was set, false otherwise
Nick Pellybd022f42009-08-14 18:33:38 -0700778 */
779 public boolean setName(String name) {
Jaikumar Ganeshf5ff1702010-08-06 19:03:13 -0700780 if (getState() != STATE_ON) return false;
Nick Pellybd022f42009-08-14 18:33:38 -0700781 try {
fredc0f420372012-04-12 00:02:00 -0700782 synchronized(mManagerCallback) {
783 if (mService != null) return mService.setName(name);
784 }
Nick Pellybd022f42009-08-14 18:33:38 -0700785 } catch (RemoteException e) {Log.e(TAG, "", e);}
786 return false;
787 }
788
789 /**
Jake Hamby0f584302010-09-16 18:12:51 -0700790 * Get the current Bluetooth scan mode of the local Bluetooth adapter.
Nick Pellyde893f52009-09-08 13:15:33 -0700791 * <p>The Bluetooth scan mode determines if the local adapter is
792 * connectable and/or discoverable from remote Bluetooth devices.
793 * <p>Possible values are:
794 * {@link #SCAN_MODE_NONE},
795 * {@link #SCAN_MODE_CONNECTABLE},
796 * {@link #SCAN_MODE_CONNECTABLE_DISCOVERABLE}.
Jaikumar Ganeshfec86f42010-08-09 16:54:03 -0700797 * <p>If Bluetooth state is not {@link #STATE_ON}, this API
798 * will return {@link #SCAN_MODE_NONE}. After turning on Bluetooth,
799 * wait for {@link #ACTION_STATE_CHANGED} with {@link #STATE_ON}
800 * to get the updated value.
Nick Pellyde893f52009-09-08 13:15:33 -0700801 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
802 *
803 * @return scan mode
Nick Pellybd022f42009-08-14 18:33:38 -0700804 */
805 public int getScanMode() {
Jaikumar Ganeshf5ff1702010-08-06 19:03:13 -0700806 if (getState() != STATE_ON) return SCAN_MODE_NONE;
Nick Pellybd022f42009-08-14 18:33:38 -0700807 try {
fredc0f420372012-04-12 00:02:00 -0700808 synchronized(mManagerCallback) {
809 if (mService != null) return mService.getScanMode();
810 }
Nick Pellybd022f42009-08-14 18:33:38 -0700811 } catch (RemoteException e) {Log.e(TAG, "", e);}
Nick Pellyde893f52009-09-08 13:15:33 -0700812 return SCAN_MODE_NONE;
Nick Pellybd022f42009-08-14 18:33:38 -0700813 }
814
815 /**
Nick Pellyde893f52009-09-08 13:15:33 -0700816 * Set the Bluetooth scan mode of the local Bluetooth adapter.
817 * <p>The Bluetooth scan mode determines if the local adapter is
818 * connectable and/or discoverable from remote Bluetooth devices.
Nick Pelly12835472009-09-25 15:00:29 -0700819 * <p>For privacy reasons, discoverable mode is automatically turned off
820 * after <code>duration</code> seconds. For example, 120 seconds should be
821 * enough for a remote device to initiate and complete its discovery
822 * process.
Nick Pellyde893f52009-09-08 13:15:33 -0700823 * <p>Valid scan mode values are:
824 * {@link #SCAN_MODE_NONE},
825 * {@link #SCAN_MODE_CONNECTABLE},
826 * {@link #SCAN_MODE_CONNECTABLE_DISCOVERABLE}.
Jaikumar Ganeshfec86f42010-08-09 16:54:03 -0700827 * <p>If Bluetooth state is not {@link #STATE_ON}, this API
828 * will return false. After turning on Bluetooth,
829 * wait for {@link #ACTION_STATE_CHANGED} with {@link #STATE_ON}
830 * to get the updated value.
Nick Pelly18b1e792009-09-24 11:14:15 -0700831 * <p>Requires {@link android.Manifest.permission#WRITE_SECURE_SETTINGS}
832 * <p>Applications cannot set the scan mode. They should use
833 * <code>startActivityForResult(
834 * BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE})
835 * </code>instead.
Nick Pellyde893f52009-09-08 13:15:33 -0700836 *
837 * @param mode valid scan mode
Nick Pelly12835472009-09-25 15:00:29 -0700838 * @param duration time in seconds to apply scan mode, only used for
839 * {@link #SCAN_MODE_CONNECTABLE_DISCOVERABLE}
Nick Pellyde893f52009-09-08 13:15:33 -0700840 * @return true if the scan mode was set, false otherwise
Nick Pelly18b1e792009-09-24 11:14:15 -0700841 * @hide
Nick Pellybd022f42009-08-14 18:33:38 -0700842 */
Nick Pelly12835472009-09-25 15:00:29 -0700843 public boolean setScanMode(int mode, int duration) {
Jaikumar Ganeshf5ff1702010-08-06 19:03:13 -0700844 if (getState() != STATE_ON) return false;
Nick Pellybd022f42009-08-14 18:33:38 -0700845 try {
fredc0f420372012-04-12 00:02:00 -0700846 synchronized(mManagerCallback) {
847 if (mService != null) return mService.setScanMode(mode, duration);
848 }
Nick Pellybd022f42009-08-14 18:33:38 -0700849 } catch (RemoteException e) {Log.e(TAG, "", e);}
Nick Pellyde893f52009-09-08 13:15:33 -0700850 return false;
Nick Pellybd022f42009-08-14 18:33:38 -0700851 }
852
Nick Pelly45e27042009-08-19 11:00:00 -0700853 /** @hide */
Nick Pelly12835472009-09-25 15:00:29 -0700854 public boolean setScanMode(int mode) {
Jaikumar Ganeshf5ff1702010-08-06 19:03:13 -0700855 if (getState() != STATE_ON) return false;
Srikanth Uppala827de2d2012-04-04 03:33:26 -0700856 /* getDiscoverableTimeout() to use the latest from NV than use 0 */
857 return setScanMode(mode, getDiscoverableTimeout());
Nick Pelly12835472009-09-25 15:00:29 -0700858 }
859
860 /** @hide */
Nick Pellybd022f42009-08-14 18:33:38 -0700861 public int getDiscoverableTimeout() {
Jaikumar Ganeshf5ff1702010-08-06 19:03:13 -0700862 if (getState() != STATE_ON) return -1;
Nick Pellybd022f42009-08-14 18:33:38 -0700863 try {
fredc0f420372012-04-12 00:02:00 -0700864 synchronized(mManagerCallback) {
865 if (mService != null) return mService.getDiscoverableTimeout();
866 }
Nick Pellybd022f42009-08-14 18:33:38 -0700867 } catch (RemoteException e) {Log.e(TAG, "", e);}
868 return -1;
869 }
870
Nick Pelly45e27042009-08-19 11:00:00 -0700871 /** @hide */
Nick Pellybd022f42009-08-14 18:33:38 -0700872 public void setDiscoverableTimeout(int timeout) {
Jaikumar Ganeshf5ff1702010-08-06 19:03:13 -0700873 if (getState() != STATE_ON) return;
Nick Pellybd022f42009-08-14 18:33:38 -0700874 try {
fredc0f420372012-04-12 00:02:00 -0700875 synchronized(mManagerCallback) {
876 if (mService != null) mService.setDiscoverableTimeout(timeout);
877 }
Nick Pellybd022f42009-08-14 18:33:38 -0700878 } catch (RemoteException e) {Log.e(TAG, "", e);}
879 }
880
Nick Pelly005b2282009-09-10 10:21:56 -0700881 /**
882 * Start the remote device discovery process.
883 * <p>The discovery process usually involves an inquiry scan of about 12
884 * seconds, followed by a page scan of each new device to retrieve its
885 * Bluetooth name.
886 * <p>This is an asynchronous call, it will return immediately. Register
887 * for {@link #ACTION_DISCOVERY_STARTED} and {@link
888 * #ACTION_DISCOVERY_FINISHED} intents to determine exactly when the
889 * discovery starts and completes. Register for {@link
890 * BluetoothDevice#ACTION_FOUND} to be notified as remote Bluetooth devices
891 * are found.
892 * <p>Device discovery is a heavyweight procedure. New connections to
893 * remote Bluetooth devices should not be attempted while discovery is in
894 * progress, and existing connections will experience limited bandwidth
895 * and high latency. Use {@link #cancelDiscovery()} to cancel an ongoing
Scott Main6d95fc02009-11-19 17:00:19 -0800896 * discovery. Discovery is not managed by the Activity,
897 * but is run as a system service, so an application should always call
898 * {@link BluetoothAdapter#cancelDiscovery()} even if it
899 * did not directly request a discovery, just to be sure.
Nick Pelly005b2282009-09-10 10:21:56 -0700900 * <p>Device discovery will only find remote devices that are currently
901 * <i>discoverable</i> (inquiry scan enabled). Many Bluetooth devices are
902 * not discoverable by default, and need to be entered into a special mode.
Jaikumar Ganeshfec86f42010-08-09 16:54:03 -0700903 * <p>If Bluetooth state is not {@link #STATE_ON}, this API
904 * will return false. After turning on Bluetooth,
905 * wait for {@link #ACTION_STATE_CHANGED} with {@link #STATE_ON}
906 * to get the updated value.
Nick Pelly005b2282009-09-10 10:21:56 -0700907 * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN}.
908 *
909 * @return true on success, false on error
910 */
Nick Pellybd022f42009-08-14 18:33:38 -0700911 public boolean startDiscovery() {
Jaikumar Ganeshf5ff1702010-08-06 19:03:13 -0700912 if (getState() != STATE_ON) return false;
Nick Pellybd022f42009-08-14 18:33:38 -0700913 try {
fredc0f420372012-04-12 00:02:00 -0700914 synchronized(mManagerCallback) {
915 if (mService != null) return mService.startDiscovery();
916 }
Nick Pellybd022f42009-08-14 18:33:38 -0700917 } catch (RemoteException e) {Log.e(TAG, "", e);}
918 return false;
919 }
920
Nick Pelly005b2282009-09-10 10:21:56 -0700921 /**
922 * Cancel the current device discovery process.
923 * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN}.
Jake Hamby0f584302010-09-16 18:12:51 -0700924 * <p>Because discovery is a heavyweight procedure for the Bluetooth
Scott Main6d95fc02009-11-19 17:00:19 -0800925 * adapter, this method should always be called before attempting to connect
926 * to a remote device with {@link
927 * android.bluetooth.BluetoothSocket#connect()}. Discovery is not managed by
928 * the Activity, but is run as a system service, so an application should
929 * always call cancel discovery even if it did not directly request a
930 * discovery, just to be sure.
Jaikumar Ganeshfec86f42010-08-09 16:54:03 -0700931 * <p>If Bluetooth state is not {@link #STATE_ON}, this API
932 * will return false. After turning on Bluetooth,
933 * wait for {@link #ACTION_STATE_CHANGED} with {@link #STATE_ON}
934 * to get the updated value.
Nick Pelly005b2282009-09-10 10:21:56 -0700935 *
936 * @return true on success, false on error
937 */
938 public boolean cancelDiscovery() {
Jaikumar Ganeshf5ff1702010-08-06 19:03:13 -0700939 if (getState() != STATE_ON) return false;
Nick Pellybd022f42009-08-14 18:33:38 -0700940 try {
fredc0f420372012-04-12 00:02:00 -0700941 synchronized(mManagerCallback) {
942 if (mService != null) return mService.cancelDiscovery();
943 }
Nick Pellybd022f42009-08-14 18:33:38 -0700944 } catch (RemoteException e) {Log.e(TAG, "", e);}
Nick Pelly005b2282009-09-10 10:21:56 -0700945 return false;
Nick Pellybd022f42009-08-14 18:33:38 -0700946 }
947
Nick Pelly005b2282009-09-10 10:21:56 -0700948 /**
949 * Return true if the local Bluetooth adapter is currently in the device
950 * discovery process.
951 * <p>Device discovery is a heavyweight procedure. New connections to
952 * remote Bluetooth devices should not be attempted while discovery is in
953 * progress, and existing connections will experience limited bandwidth
954 * and high latency. Use {@link #cancelDiscovery()} to cancel an ongoing
955 * discovery.
956 * <p>Applications can also register for {@link #ACTION_DISCOVERY_STARTED}
957 * or {@link #ACTION_DISCOVERY_FINISHED} to be notified when discovery
958 * starts or completes.
Jaikumar Ganeshfec86f42010-08-09 16:54:03 -0700959 * <p>If Bluetooth state is not {@link #STATE_ON}, this API
960 * will return false. After turning on Bluetooth,
961 * wait for {@link #ACTION_STATE_CHANGED} with {@link #STATE_ON}
962 * to get the updated value.
Nick Pellye6ee3be2009-10-08 23:27:28 +0200963 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}.
Nick Pelly005b2282009-09-10 10:21:56 -0700964 *
965 * @return true if discovering
966 */
Nick Pellybd022f42009-08-14 18:33:38 -0700967 public boolean isDiscovering() {
Jaikumar Ganeshf5ff1702010-08-06 19:03:13 -0700968 if (getState() != STATE_ON) return false;
Nick Pellybd022f42009-08-14 18:33:38 -0700969 try {
fredc0f420372012-04-12 00:02:00 -0700970 synchronized(mManagerCallback) {
971 if (mService != null ) return mService.isDiscovering();
972 }
Nick Pellybd022f42009-08-14 18:33:38 -0700973 } catch (RemoteException e) {Log.e(TAG, "", e);}
974 return false;
975 }
976
977 /**
Wei Wang18c76932013-10-29 21:05:37 -0700978 * Returns whether BLE is currently advertising.
979 * <p>Requires {@link android.Manifest.permission#BLUETOOTH_PRIVILEGED}.
980 *
981 * @hide
982 */
983 public boolean isAdvertising() {
984 if (getState() != STATE_ON) return false;
985 try {
986 IBluetoothGatt iGatt = mManagerService.getBluetoothGatt();
987 return iGatt.isAdvertising();
988 } catch (RemoteException e) {
989 Log.e(TAG, "", e);
990 }
991 return false;
992 }
993
994 /**
Nick Pelly005b2282009-09-10 10:21:56 -0700995 * Return the set of {@link BluetoothDevice} objects that are bonded
996 * (paired) to the local adapter.
Jaikumar Ganeshfec86f42010-08-09 16:54:03 -0700997 * <p>If Bluetooth state is not {@link #STATE_ON}, this API
998 * will return an empty set. After turning on Bluetooth,
999 * wait for {@link #ACTION_STATE_CHANGED} with {@link #STATE_ON}
1000 * to get the updated value.
Nick Pellye6ee3be2009-10-08 23:27:28 +02001001 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}.
Nick Pellybd022f42009-08-14 18:33:38 -07001002 *
Nick Pelly005b2282009-09-10 10:21:56 -07001003 * @return unmodifiable set of {@link BluetoothDevice}, or null on error
Nick Pellybd022f42009-08-14 18:33:38 -07001004 */
1005 public Set<BluetoothDevice> getBondedDevices() {
Jaikumar Ganeshfec86f42010-08-09 16:54:03 -07001006 if (getState() != STATE_ON) {
Jaikumar Ganeshe4caddb2012-01-25 16:16:48 -08001007 return toDeviceSet(new BluetoothDevice[0]);
Jaikumar Ganeshfec86f42010-08-09 16:54:03 -07001008 }
Nick Pellybd022f42009-08-14 18:33:38 -07001009 try {
fredc0f420372012-04-12 00:02:00 -07001010 synchronized(mManagerCallback) {
1011 if (mService != null) return toDeviceSet(mService.getBondedDevices());
1012 }
1013 return toDeviceSet(new BluetoothDevice[0]);
Nick Pellybd022f42009-08-14 18:33:38 -07001014 } catch (RemoteException e) {Log.e(TAG, "", e);}
1015 return null;
1016 }
1017
1018 /**
Jaikumar Ganeshc53cab22010-10-26 16:02:26 -07001019 * Get the current connection state of the local Bluetooth adapter.
1020 * This can be used to check whether the local Bluetooth adapter is connected
1021 * to any profile of any other remote Bluetooth Device.
1022 *
1023 * <p> Use this function along with {@link #ACTION_CONNECTION_STATE_CHANGED}
1024 * intent to get the connection state of the adapter.
1025 *
1026 * @return One of {@link #STATE_CONNECTED}, {@link #STATE_DISCONNECTED},
1027 * {@link #STATE_CONNECTING} or {@link #STATE_DISCONNECTED}
1028 *
1029 * @hide
1030 */
1031 public int getConnectionState() {
1032 if (getState() != STATE_ON) return BluetoothAdapter.STATE_DISCONNECTED;
1033 try {
fredc0f420372012-04-12 00:02:00 -07001034 synchronized(mManagerCallback) {
1035 if (mService != null) return mService.getAdapterConnectionState();
1036 }
Jaikumar Ganeshc53cab22010-10-26 16:02:26 -07001037 } catch (RemoteException e) {Log.e(TAG, "getConnectionState:", e);}
1038 return BluetoothAdapter.STATE_DISCONNECTED;
1039 }
1040
1041 /**
Jaikumar Ganeshcb1d3542011-08-19 10:26:32 -07001042 * Get the current connection state of a profile.
1043 * This function can be used to check whether the local Bluetooth adapter
1044 * is connected to any remote device for a specific profile.
Scott Main2d68a6b2011-09-26 22:59:38 -07001045 * Profile can be one of {@link BluetoothProfile#HEALTH}, {@link BluetoothProfile#HEADSET},
Jaikumar Ganesh93547902011-08-23 12:21:55 -07001046 * {@link BluetoothProfile#A2DP}.
Jaikumar Ganeshcb1d3542011-08-19 10:26:32 -07001047 *
1048 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}.
1049 *
1050 * <p> Return value can be one of
Jaikumar Ganesh93547902011-08-23 12:21:55 -07001051 * {@link BluetoothProfile#STATE_DISCONNECTED},
1052 * {@link BluetoothProfile#STATE_CONNECTING},
1053 * {@link BluetoothProfile#STATE_CONNECTED},
1054 * {@link BluetoothProfile#STATE_DISCONNECTING}
Jaikumar Ganeshcb1d3542011-08-19 10:26:32 -07001055 */
1056 public int getProfileConnectionState(int profile) {
1057 if (getState() != STATE_ON) return BluetoothProfile.STATE_DISCONNECTED;
1058 try {
fredc0f420372012-04-12 00:02:00 -07001059 synchronized(mManagerCallback) {
1060 if (mService != null) return mService.getProfileConnectionState(profile);
1061 }
Jaikumar Ganesh93547902011-08-23 12:21:55 -07001062 } catch (RemoteException e) {
1063 Log.e(TAG, "getProfileConnectionState:", e);
1064 }
Jaikumar Ganeshcb1d3542011-08-19 10:26:32 -07001065 return BluetoothProfile.STATE_DISCONNECTED;
1066 }
1067
1068 /**
Nick Pelly45e27042009-08-19 11:00:00 -07001069 * Create a listening, secure RFCOMM Bluetooth socket.
1070 * <p>A remote device connecting to this socket will be authenticated and
Nick Pellybd022f42009-08-14 18:33:38 -07001071 * communication on this socket will be encrypted.
Nick Pelly45e27042009-08-19 11:00:00 -07001072 * <p>Use {@link BluetoothServerSocket#accept} to retrieve incoming
Nick Pelly24bb9b82009-10-02 20:34:18 -07001073 * connections from a listening {@link BluetoothServerSocket}.
Nick Pelly45e27042009-08-19 11:00:00 -07001074 * <p>Valid RFCOMM channels are in range 1 to 30.
Nick Pelly24bb9b82009-10-02 20:34:18 -07001075 * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN}
Nick Pelly45e27042009-08-19 11:00:00 -07001076 * @param channel RFCOMM channel to listen on
1077 * @return a listening RFCOMM BluetoothServerSocket
1078 * @throws IOException on error, for example Bluetooth not available, or
1079 * insufficient permissions, or channel in use.
Nick Pelly24bb9b82009-10-02 20:34:18 -07001080 * @hide
Nick Pellybd022f42009-08-14 18:33:38 -07001081 */
Nick Pelly45e27042009-08-19 11:00:00 -07001082 public BluetoothServerSocket listenUsingRfcommOn(int channel) throws IOException {
Nick Pellybd022f42009-08-14 18:33:38 -07001083 BluetoothServerSocket socket = new BluetoothServerSocket(
Nick Pelly45e27042009-08-19 11:00:00 -07001084 BluetoothSocket.TYPE_RFCOMM, true, true, channel);
Nick Pelly24bb9b82009-10-02 20:34:18 -07001085 int errno = socket.mSocket.bindListen();
1086 if (errno != 0) {
zzy3b147b72012-04-03 19:48:32 -07001087 //TODO(BT): Throw the same exception error code
1088 // that the previous code was using.
1089 //socket.mSocket.throwErrnoNative(errno);
1090 throw new IOException("Error: " + errno);
Nick Pellybd022f42009-08-14 18:33:38 -07001091 }
1092 return socket;
1093 }
1094
1095 /**
Nick Pelly24bb9b82009-10-02 20:34:18 -07001096 * Create a listening, secure RFCOMM Bluetooth socket with Service Record.
1097 * <p>A remote device connecting to this socket will be authenticated and
1098 * communication on this socket will be encrypted.
1099 * <p>Use {@link BluetoothServerSocket#accept} to retrieve incoming
1100 * connections from a listening {@link BluetoothServerSocket}.
1101 * <p>The system will assign an unused RFCOMM channel to listen on.
1102 * <p>The system will also register a Service Discovery
1103 * Protocol (SDP) record with the local SDP server containing the specified
1104 * UUID, service name, and auto-assigned channel. Remote Bluetooth devices
1105 * can use the same UUID to query our SDP server and discover which channel
1106 * to connect to. This SDP record will be removed when this socket is
1107 * closed, or if this application closes unexpectedly.
Nick Pelly16fb88a2009-10-07 07:44:03 +02001108 * <p>Use {@link BluetoothDevice#createRfcommSocketToServiceRecord} to
1109 * connect to this socket from another device using the same {@link UUID}.
Nick Pelly24bb9b82009-10-02 20:34:18 -07001110 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
1111 * @param name service name for SDP record
1112 * @param uuid uuid for SDP record
1113 * @return a listening RFCOMM BluetoothServerSocket
1114 * @throws IOException on error, for example Bluetooth not available, or
1115 * insufficient permissions, or channel in use.
1116 */
Nick Pelly16fb88a2009-10-07 07:44:03 +02001117 public BluetoothServerSocket listenUsingRfcommWithServiceRecord(String name, UUID uuid)
Nick Pelly24bb9b82009-10-02 20:34:18 -07001118 throws IOException {
Jaikumar Ganesh6eef14a2010-12-23 12:57:02 -08001119 return createNewRfcommSocketAndRecord(name, uuid, true, true);
1120 }
1121
1122 /**
1123 * Create a listening, insecure RFCOMM Bluetooth socket with Service Record.
Mathias Jeppssone3b9dc102011-03-21 15:06:52 +01001124 * <p>The link key is not required to be authenticated, i.e the communication may be
Jaikumar Ganesh6eef14a2010-12-23 12:57:02 -08001125 * vulnerable to Man In the Middle attacks. For Bluetooth 2.1 devices,
Mathias Jeppssone3b9dc102011-03-21 15:06:52 +01001126 * the link will be encrypted, as encryption is mandartory.
1127 * For legacy devices (pre Bluetooth 2.1 devices) the link will not
Jaikumar Ganesh6eef14a2010-12-23 12:57:02 -08001128 * be encrypted. Use {@link #listenUsingRfcommWithServiceRecord}, if an
1129 * encrypted and authenticated communication channel is desired.
1130 * <p>Use {@link BluetoothServerSocket#accept} to retrieve incoming
1131 * connections from a listening {@link BluetoothServerSocket}.
1132 * <p>The system will assign an unused RFCOMM channel to listen on.
1133 * <p>The system will also register a Service Discovery
1134 * Protocol (SDP) record with the local SDP server containing the specified
1135 * UUID, service name, and auto-assigned channel. Remote Bluetooth devices
1136 * can use the same UUID to query our SDP server and discover which channel
1137 * to connect to. This SDP record will be removed when this socket is
1138 * closed, or if this application closes unexpectedly.
1139 * <p>Use {@link BluetoothDevice#createRfcommSocketToServiceRecord} to
1140 * connect to this socket from another device using the same {@link UUID}.
1141 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
1142 * @param name service name for SDP record
1143 * @param uuid uuid for SDP record
1144 * @return a listening RFCOMM BluetoothServerSocket
1145 * @throws IOException on error, for example Bluetooth not available, or
1146 * insufficient permissions, or channel in use.
1147 */
1148 public BluetoothServerSocket listenUsingInsecureRfcommWithServiceRecord(String name, UUID uuid)
1149 throws IOException {
1150 return createNewRfcommSocketAndRecord(name, uuid, false, false);
1151 }
1152
Mathias Jeppssone3b9dc102011-03-21 15:06:52 +01001153 /**
1154 * Create a listening, encrypted,
1155 * RFCOMM Bluetooth socket with Service Record.
1156 * <p>The link will be encrypted, but the link key is not required to be authenticated
1157 * i.e the communication is vulnerable to Man In the Middle attacks. Use
1158 * {@link #listenUsingRfcommWithServiceRecord}, to ensure an authenticated link key.
1159 * <p> Use this socket if authentication of link key is not possible.
1160 * For example, for Bluetooth 2.1 devices, if any of the devices does not have
1161 * an input and output capability or just has the ability to display a numeric key,
1162 * a secure socket connection is not possible and this socket can be used.
1163 * Use {@link #listenUsingInsecureRfcommWithServiceRecord}, if encryption is not required.
1164 * For Bluetooth 2.1 devices, the link will be encrypted, as encryption is mandartory.
1165 * For more details, refer to the Security Model section 5.2 (vol 3) of
1166 * Bluetooth Core Specification version 2.1 + EDR.
1167 * <p>Use {@link BluetoothServerSocket#accept} to retrieve incoming
1168 * connections from a listening {@link BluetoothServerSocket}.
1169 * <p>The system will assign an unused RFCOMM channel to listen on.
1170 * <p>The system will also register a Service Discovery
1171 * Protocol (SDP) record with the local SDP server containing the specified
1172 * UUID, service name, and auto-assigned channel. Remote Bluetooth devices
1173 * can use the same UUID to query our SDP server and discover which channel
1174 * to connect to. This SDP record will be removed when this socket is
1175 * closed, or if this application closes unexpectedly.
1176 * <p>Use {@link BluetoothDevice#createRfcommSocketToServiceRecord} to
1177 * connect to this socket from another device using the same {@link UUID}.
1178 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
1179 * @param name service name for SDP record
1180 * @param uuid uuid for SDP record
1181 * @return a listening RFCOMM BluetoothServerSocket
1182 * @throws IOException on error, for example Bluetooth not available, or
1183 * insufficient permissions, or channel in use.
1184 * @hide
1185 */
1186 public BluetoothServerSocket listenUsingEncryptedRfcommWithServiceRecord(
1187 String name, UUID uuid) throws IOException {
1188 return createNewRfcommSocketAndRecord(name, uuid, false, true);
1189 }
1190
zzy3b147b72012-04-03 19:48:32 -07001191
Jaikumar Ganesh6eef14a2010-12-23 12:57:02 -08001192 private BluetoothServerSocket createNewRfcommSocketAndRecord(String name, UUID uuid,
1193 boolean auth, boolean encrypt) throws IOException {
Nick Pelly24bb9b82009-10-02 20:34:18 -07001194 BluetoothServerSocket socket;
zzy3b147b72012-04-03 19:48:32 -07001195 socket = new BluetoothServerSocket(BluetoothSocket.TYPE_RFCOMM, auth,
1196 encrypt, new ParcelUuid(uuid));
1197 socket.setServiceName(name);
1198 int errno = socket.mSocket.bindListen();
1199 if (errno != 0) {
1200 //TODO(BT): Throw the same exception error code
1201 // that the previous code was using.
1202 //socket.mSocket.throwErrnoNative(errno);
1203 throw new IOException("Error: " + errno);
Nick Pelly24bb9b82009-10-02 20:34:18 -07001204 }
Nick Pelly24bb9b82009-10-02 20:34:18 -07001205 return socket;
1206 }
1207
1208 /**
Nick Pellybd022f42009-08-14 18:33:38 -07001209 * Construct an unencrypted, unauthenticated, RFCOMM server socket.
1210 * Call #accept to retrieve connections to this socket.
1211 * @return An RFCOMM BluetoothServerSocket
1212 * @throws IOException On error, for example Bluetooth not available, or
1213 * insufficient permissions.
Nick Pelly45e27042009-08-19 11:00:00 -07001214 * @hide
Nick Pellybd022f42009-08-14 18:33:38 -07001215 */
1216 public BluetoothServerSocket listenUsingInsecureRfcommOn(int port) throws IOException {
1217 BluetoothServerSocket socket = new BluetoothServerSocket(
1218 BluetoothSocket.TYPE_RFCOMM, false, false, port);
Nick Pelly24bb9b82009-10-02 20:34:18 -07001219 int errno = socket.mSocket.bindListen();
1220 if (errno != 0) {
zzy3b147b72012-04-03 19:48:32 -07001221 //TODO(BT): Throw the same exception error code
1222 // that the previous code was using.
1223 //socket.mSocket.throwErrnoNative(errno);
1224 throw new IOException("Error: " + errno);
Nick Pellybd022f42009-08-14 18:33:38 -07001225 }
1226 return socket;
1227 }
1228
Mathias Jeppssone3b9dc102011-03-21 15:06:52 +01001229 /**
1230 * Construct an encrypted, RFCOMM server socket.
1231 * Call #accept to retrieve connections to this socket.
1232 * @return An RFCOMM BluetoothServerSocket
1233 * @throws IOException On error, for example Bluetooth not available, or
1234 * insufficient permissions.
1235 * @hide
1236 */
1237 public BluetoothServerSocket listenUsingEncryptedRfcommOn(int port)
1238 throws IOException {
1239 BluetoothServerSocket socket = new BluetoothServerSocket(
1240 BluetoothSocket.TYPE_RFCOMM, false, true, port);
1241 int errno = socket.mSocket.bindListen();
zzy3b147b72012-04-03 19:48:32 -07001242 if (errno < 0) {
1243 //TODO(BT): Throw the same exception error code
1244 // that the previous code was using.
1245 //socket.mSocket.throwErrnoNative(errno);
1246 throw new IOException("Error: " + errno);
Mathias Jeppssone3b9dc102011-03-21 15:06:52 +01001247 }
1248 return socket;
1249 }
1250
Nick Pellybd022f42009-08-14 18:33:38 -07001251 /**
1252 * Construct a SCO server socket.
1253 * Call #accept to retrieve connections to this socket.
1254 * @return A SCO BluetoothServerSocket
1255 * @throws IOException On error, for example Bluetooth not available, or
1256 * insufficient permissions.
Nick Pelly45e27042009-08-19 11:00:00 -07001257 * @hide
Nick Pellybd022f42009-08-14 18:33:38 -07001258 */
1259 public static BluetoothServerSocket listenUsingScoOn() throws IOException {
1260 BluetoothServerSocket socket = new BluetoothServerSocket(
1261 BluetoothSocket.TYPE_SCO, false, false, -1);
Nick Pelly24bb9b82009-10-02 20:34:18 -07001262 int errno = socket.mSocket.bindListen();
zzy3b147b72012-04-03 19:48:32 -07001263 if (errno < 0) {
1264 //TODO(BT): Throw the same exception error code
1265 // that the previous code was using.
1266 //socket.mSocket.throwErrnoNative(errno);
Nick Pellybd022f42009-08-14 18:33:38 -07001267 }
1268 return socket;
1269 }
1270
Jaikumar Ganeshcc5494c2010-09-09 15:37:57 -07001271 /**
1272 * Read the local Out of Band Pairing Data
1273 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
1274 *
1275 * @return Pair<byte[], byte[]> of Hash and Randomizer
1276 *
1277 * @hide
1278 */
1279 public Pair<byte[], byte[]> readOutOfBandData() {
1280 if (getState() != STATE_ON) return null;
Jaikumar Ganeshe4caddb2012-01-25 16:16:48 -08001281 //TODO(BT
1282 /*
Jaikumar Ganeshcc5494c2010-09-09 15:37:57 -07001283 try {
Jake Hambyf51eada2010-09-21 13:39:53 -07001284 byte[] hash;
1285 byte[] randomizer;
Jaikumar Ganeshcc5494c2010-09-09 15:37:57 -07001286
1287 byte[] ret = mService.readOutOfBandData();
1288
1289 if (ret == null || ret.length != 32) return null;
1290
1291 hash = Arrays.copyOfRange(ret, 0, 16);
1292 randomizer = Arrays.copyOfRange(ret, 16, 32);
1293
1294 if (DBG) {
1295 Log.d(TAG, "readOutOfBandData:" + Arrays.toString(hash) +
1296 ":" + Arrays.toString(randomizer));
1297 }
1298 return new Pair<byte[], byte[]>(hash, randomizer);
1299
Jaikumar Ganeshe4caddb2012-01-25 16:16:48 -08001300 } catch (RemoteException e) {Log.e(TAG, "", e);}*/
Jaikumar Ganeshcc5494c2010-09-09 15:37:57 -07001301 return null;
1302 }
1303
Scott Main299ae672011-01-19 21:13:18 -08001304 /**
Jaikumar Ganesh62c37ef2010-08-24 17:36:13 -07001305 * Get the profile proxy object associated with the profile.
1306 *
Ganesh Ganapathi Batta99081122013-02-05 15:28:33 -08001307 * <p>Profile can be one of {@link BluetoothProfile#HEALTH}, {@link BluetoothProfile#HEADSET},
Matthew Xieddf7e472013-03-01 18:41:02 -08001308 * {@link BluetoothProfile#A2DP}, {@link BluetoothProfile#GATT}, or
1309 * {@link BluetoothProfile#GATT_SERVER}. Clients must implement
Jaikumar Ganesh62c37ef2010-08-24 17:36:13 -07001310 * {@link BluetoothProfile.ServiceListener} to get notified of
1311 * the connection status and to get the proxy object.
1312 *
1313 * @param context Context of the application
1314 * @param listener The service Listener for connection callbacks.
Scott Main2d68a6b2011-09-26 22:59:38 -07001315 * @param profile The Bluetooth profile; either {@link BluetoothProfile#HEALTH},
1316 * {@link BluetoothProfile#HEADSET} or {@link BluetoothProfile#A2DP}.
Jaikumar Ganesh62c37ef2010-08-24 17:36:13 -07001317 * @return true on success, false on error
1318 */
1319 public boolean getProfileProxy(Context context, BluetoothProfile.ServiceListener listener,
1320 int profile) {
1321 if (context == null || listener == null) return false;
1322
1323 if (profile == BluetoothProfile.HEADSET) {
1324 BluetoothHeadset headset = new BluetoothHeadset(context, listener);
1325 return true;
1326 } else if (profile == BluetoothProfile.A2DP) {
1327 BluetoothA2dp a2dp = new BluetoothA2dp(context, listener);
1328 return true;
Jaikumar Ganesh4ab0e772011-02-18 14:52:32 -08001329 } else if (profile == BluetoothProfile.INPUT_DEVICE) {
1330 BluetoothInputDevice iDev = new BluetoothInputDevice(context, listener);
1331 return true;
Jaikumar Ganesh74ef1192011-02-23 10:22:15 -08001332 } else if (profile == BluetoothProfile.PAN) {
1333 BluetoothPan pan = new BluetoothPan(context, listener);
1334 return true;
Jaikumar Ganesh2ea1e852011-04-01 16:33:09 -07001335 } else if (profile == BluetoothProfile.HEALTH) {
1336 BluetoothHealth health = new BluetoothHealth(context, listener);
1337 return true;
Kim Schulz0d376052013-08-22 11:18:02 +02001338 } else if (profile == BluetoothProfile.MAP) {
1339 BluetoothMap map = new BluetoothMap(context, listener);
1340 return true;
Jaikumar Ganesh62c37ef2010-08-24 17:36:13 -07001341 } else {
1342 return false;
1343 }
1344 }
1345
1346 /**
1347 * Close the connection of the profile proxy to the Service.
1348 *
1349 * <p> Clients should call this when they are no longer using
1350 * the proxy obtained from {@link #getProfileProxy}.
Scott Main2d68a6b2011-09-26 22:59:38 -07001351 * Profile can be one of {@link BluetoothProfile#HEALTH}, {@link BluetoothProfile#HEADSET} or
Jaikumar Ganesh62c37ef2010-08-24 17:36:13 -07001352 * {@link BluetoothProfile#A2DP}
1353 *
1354 * @param profile
1355 * @param proxy Profile proxy object
1356 */
1357 public void closeProfileProxy(int profile, BluetoothProfile proxy) {
Jaikumar Ganesh9bb27512011-11-28 09:59:08 -08001358 if (proxy == null) return;
1359
1360 switch (profile) {
1361 case BluetoothProfile.HEADSET:
1362 BluetoothHeadset headset = (BluetoothHeadset)proxy;
Jaikumar Ganesh62c37ef2010-08-24 17:36:13 -07001363 headset.close();
Jaikumar Ganesh9bb27512011-11-28 09:59:08 -08001364 break;
1365 case BluetoothProfile.A2DP:
1366 BluetoothA2dp a2dp = (BluetoothA2dp)proxy;
1367 a2dp.close();
1368 break;
1369 case BluetoothProfile.INPUT_DEVICE:
1370 BluetoothInputDevice iDev = (BluetoothInputDevice)proxy;
1371 iDev.close();
1372 break;
1373 case BluetoothProfile.PAN:
1374 BluetoothPan pan = (BluetoothPan)proxy;
1375 pan.close();
1376 break;
1377 case BluetoothProfile.HEALTH:
1378 BluetoothHealth health = (BluetoothHealth)proxy;
1379 health.close();
1380 break;
Ganesh Ganapathi Batta99081122013-02-05 15:28:33 -08001381 case BluetoothProfile.GATT:
1382 BluetoothGatt gatt = (BluetoothGatt)proxy;
1383 gatt.close();
1384 break;
1385 case BluetoothProfile.GATT_SERVER:
1386 BluetoothGattServer gattServer = (BluetoothGattServer)proxy;
1387 gattServer.close();
1388 break;
Kim Schulz0d376052013-08-22 11:18:02 +02001389 case BluetoothProfile.MAP:
1390 BluetoothMap map = (BluetoothMap)proxy;
1391 map.close();
1392 break;
Jaikumar Ganesh62c37ef2010-08-24 17:36:13 -07001393 }
1394 }
1395
fredc0f420372012-04-12 00:02:00 -07001396 final private IBluetoothManagerCallback mManagerCallback =
1397 new IBluetoothManagerCallback.Stub() {
1398 public void onBluetoothServiceUp(IBluetooth bluetoothService) {
Matthew Xied77982e2012-11-29 20:26:19 -08001399 if (VDBG) Log.d(TAG, "onBluetoothServiceUp: " + bluetoothService);
fredc0f420372012-04-12 00:02:00 -07001400 synchronized (mManagerCallback) {
1401 mService = bluetoothService;
fredcbf072a72012-05-09 16:52:50 -07001402 for (IBluetoothManagerCallback cb : mProxyServiceStateCallbacks ){
fredc903ac6f2012-04-24 03:59:57 -07001403 try {
fredcd6883532012-04-25 17:46:13 -07001404 if (cb != null) {
1405 cb.onBluetoothServiceUp(bluetoothService);
1406 } else {
1407 Log.d(TAG, "onBluetoothServiceUp: cb is null!!!");
1408 }
fredc903ac6f2012-04-24 03:59:57 -07001409 } catch (Exception e) { Log.e(TAG,"",e);}
1410 }
fredc0f420372012-04-12 00:02:00 -07001411 }
1412 }
1413
1414 public void onBluetoothServiceDown() {
Matthew Xied77982e2012-11-29 20:26:19 -08001415 if (VDBG) Log.d(TAG, "onBluetoothServiceDown: " + mService);
fredc0f420372012-04-12 00:02:00 -07001416 synchronized (mManagerCallback) {
1417 mService = null;
fredcbf072a72012-05-09 16:52:50 -07001418 for (IBluetoothManagerCallback cb : mProxyServiceStateCallbacks ){
fredc903ac6f2012-04-24 03:59:57 -07001419 try {
fredcd6883532012-04-25 17:46:13 -07001420 if (cb != null) {
1421 cb.onBluetoothServiceDown();
1422 } else {
1423 Log.d(TAG, "onBluetoothServiceDown: cb is null!!!");
1424 }
fredc903ac6f2012-04-24 03:59:57 -07001425 } catch (Exception e) { Log.e(TAG,"",e);}
1426 }
fredc0f420372012-04-12 00:02:00 -07001427 }
1428 }
1429 };
1430
Jaikumar Ganeshef2cb7c2011-07-21 18:13:38 -07001431 /**
Martijn Coenen6c614b72012-04-18 13:01:15 -07001432 * Enable the Bluetooth Adapter, but don't auto-connect devices
1433 * and don't persist state. Only for use by system applications.
1434 * @hide
1435 */
1436 public boolean enableNoAutoConnect() {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001437 if (isEnabled() == true){
1438 if (DBG) Log.d(TAG, "enableNoAutoConnect(): BT is already enabled..!");
1439 return true;
1440 }
1441 try {
1442 return mManagerService.enableNoAutoConnect();
1443 } catch (RemoteException e) {Log.e(TAG, "", e);}
1444 return false;
Martijn Coenen6c614b72012-04-18 13:01:15 -07001445 }
1446
1447 /**
Jaikumar Ganeshef2cb7c2011-07-21 18:13:38 -07001448 * Enable control of the Bluetooth Adapter for a single application.
1449 *
1450 * <p>Some applications need to use Bluetooth for short periods of time to
1451 * transfer data but don't want all the associated implications like
1452 * automatic connection to headsets etc.
1453 *
1454 * <p> Multiple applications can call this. This is reference counted and
1455 * Bluetooth disabled only when no one else is using it. There will be no UI
1456 * shown to the user while bluetooth is being enabled. Any user action will
1457 * override this call. For example, if user wants Bluetooth on and the last
1458 * user of this API wanted to disable Bluetooth, Bluetooth will not be
1459 * turned off.
1460 *
1461 * <p> This API is only meant to be used by internal applications. Third
1462 * party applications but use {@link #enable} and {@link #disable} APIs.
1463 *
1464 * <p> If this API returns true, it means the callback will be called.
1465 * The callback will be called with the current state of Bluetooth.
1466 * If the state is not what was requested, an internal error would be the
Jaikumar Ganeshf5fb6c82011-08-03 14:17:22 -07001467 * reason. If Bluetooth is already on and if this function is called to turn
1468 * it on, the api will return true and a callback will be called.
1469 *
1470 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
Jaikumar Ganeshef2cb7c2011-07-21 18:13:38 -07001471 *
1472 * @param on True for on, false for off.
1473 * @param callback The callback to notify changes to the state.
1474 * @hide
1475 */
1476 public boolean changeApplicationBluetoothState(boolean on,
1477 BluetoothStateChangeCallback callback) {
1478 if (callback == null) return false;
1479
Jaikumar Ganeshe4caddb2012-01-25 16:16:48 -08001480 //TODO(BT)
1481 /*
Jaikumar Ganeshef2cb7c2011-07-21 18:13:38 -07001482 try {
1483 return mService.changeApplicationBluetoothState(on, new
1484 StateChangeCallbackWrapper(callback), new Binder());
1485 } catch (RemoteException e) {
1486 Log.e(TAG, "changeBluetoothState", e);
Jaikumar Ganeshe4caddb2012-01-25 16:16:48 -08001487 }*/
Jaikumar Ganeshef2cb7c2011-07-21 18:13:38 -07001488 return false;
1489 }
1490
1491 /**
1492 * @hide
1493 */
1494 public interface BluetoothStateChangeCallback {
1495 public void onBluetoothStateChange(boolean on);
1496 }
1497
1498 /**
1499 * @hide
1500 */
1501 public class StateChangeCallbackWrapper extends IBluetoothStateChangeCallback.Stub {
1502 private BluetoothStateChangeCallback mCallback;
1503
1504 StateChangeCallbackWrapper(BluetoothStateChangeCallback
1505 callback) {
1506 mCallback = callback;
1507 }
1508
1509 @Override
1510 public void onBluetoothStateChange(boolean on) {
1511 mCallback.onBluetoothStateChange(on);
1512 }
1513 }
1514
Jaikumar Ganeshe4caddb2012-01-25 16:16:48 -08001515 private Set<BluetoothDevice> toDeviceSet(BluetoothDevice[] devices) {
1516 Set<BluetoothDevice> deviceSet = new HashSet<BluetoothDevice>(Arrays.asList(devices));
1517 return Collections.unmodifiableSet(deviceSet);
Nick Pellybd022f42009-08-14 18:33:38 -07001518 }
Nick Pelly005b2282009-09-10 10:21:56 -07001519
fredc0f420372012-04-12 00:02:00 -07001520 protected void finalize() throws Throwable {
1521 try {
1522 mManagerService.unregisterAdapter(mManagerCallback);
1523 } catch (RemoteException e) {
1524 Log.e(TAG, "", e);
1525 } finally {
1526 super.finalize();
1527 }
1528 }
1529
1530
Nick Pelly005b2282009-09-10 10:21:56 -07001531 /**
Nick Pelly75596b42011-12-07 15:03:55 -08001532 * Validate a String Bluetooth address, such as "00:43:A8:23:10:F0"
Nick Pelly55e66f12009-09-18 11:37:06 -07001533 * <p>Alphabetic characters must be uppercase to be valid.
Nick Pelly005b2282009-09-10 10:21:56 -07001534 *
1535 * @param address Bluetooth address as string
1536 * @return true if the address is valid, false otherwise
1537 */
1538 public static boolean checkBluetoothAddress(String address) {
1539 if (address == null || address.length() != ADDRESS_LENGTH) {
1540 return false;
1541 }
1542 for (int i = 0; i < ADDRESS_LENGTH; i++) {
1543 char c = address.charAt(i);
1544 switch (i % 3) {
1545 case 0:
1546 case 1:
Nick Pelly55e66f12009-09-18 11:37:06 -07001547 if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F')) {
1548 // hex character, OK
1549 break;
Nick Pelly005b2282009-09-10 10:21:56 -07001550 }
1551 return false;
1552 case 2:
1553 if (c == ':') {
1554 break; // OK
1555 }
1556 return false;
1557 }
1558 }
1559 return true;
1560 }
fredc0f420372012-04-12 00:02:00 -07001561
1562 /*package*/ IBluetoothManager getBluetoothManager() {
1563 return mManagerService;
1564 }
1565
fredcbf072a72012-05-09 16:52:50 -07001566 private ArrayList<IBluetoothManagerCallback> mProxyServiceStateCallbacks = new ArrayList<IBluetoothManagerCallback>();
fredcd6883532012-04-25 17:46:13 -07001567
fredc903ac6f2012-04-24 03:59:57 -07001568 /*package*/ IBluetooth getBluetoothService(IBluetoothManagerCallback cb) {
fredc0f420372012-04-12 00:02:00 -07001569 synchronized (mManagerCallback) {
fredcd6883532012-04-25 17:46:13 -07001570 if (cb == null) {
fredcbf072a72012-05-09 16:52:50 -07001571 Log.w(TAG, "getBluetoothService() called with no BluetoothManagerCallback");
1572 } else if (!mProxyServiceStateCallbacks.contains(cb)) {
1573 mProxyServiceStateCallbacks.add(cb);
fredc903ac6f2012-04-24 03:59:57 -07001574 }
1575 }
1576 return mService;
1577 }
1578
1579 /*package*/ void removeServiceStateCallback(IBluetoothManagerCallback cb) {
1580 synchronized (mManagerCallback) {
fredcbf072a72012-05-09 16:52:50 -07001581 mProxyServiceStateCallbacks.remove(cb);
fredc0f420372012-04-12 00:02:00 -07001582 }
1583 }
Matthew Xieddf7e472013-03-01 18:41:02 -08001584
1585 /**
Matthew Xiecdd94e32013-04-11 16:36:26 -07001586 * Callback interface used to deliver LE scan results.
Matthew Xieddf7e472013-03-01 18:41:02 -08001587 *
Matthew Xiecdd94e32013-04-11 16:36:26 -07001588 * @see #startLeScan(LeScanCallback)
1589 * @see #startLeScan(UUID[], LeScanCallback)
Matthew Xieddf7e472013-03-01 18:41:02 -08001590 */
Matthew Xiecdd94e32013-04-11 16:36:26 -07001591 public interface LeScanCallback {
1592 /**
1593 * Callback reporting an LE device found during a device scan initiated
1594 * by the {@link BluetoothAdapter#startLeScan} function.
1595 *
1596 * @param device Identifies the remote device
1597 * @param rssi The RSSI value for the remote device as reported by the
1598 * Bluetooth hardware. 0 if no RSSI value is available.
1599 * @param scanRecord The content of the advertisement record offered by
1600 * the remote device.
1601 */
1602 public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord);
Matthew Xieddf7e472013-03-01 18:41:02 -08001603 }
1604
1605 /**
1606 * Starts a scan for Bluetooth LE devices.
1607 *
1608 * <p>Results of the scan are reported using the
Matthew Xiecdd94e32013-04-11 16:36:26 -07001609 * {@link LeScanCallback#onLeScan} callback.
Matthew Xieddf7e472013-03-01 18:41:02 -08001610 *
Matthew Xied5752332013-04-24 17:51:37 -07001611 * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN} permission.
Matthew Xieddf7e472013-03-01 18:41:02 -08001612 *
Matthew Xiecdd94e32013-04-11 16:36:26 -07001613 * @param callback the callback LE scan results are delivered
Matthew Xieddf7e472013-03-01 18:41:02 -08001614 * @return true, if the scan was started successfully
1615 */
Matthew Xiecdd94e32013-04-11 16:36:26 -07001616 public boolean startLeScan(LeScanCallback callback) {
1617 return startLeScan(null, callback);
Matthew Xieddf7e472013-03-01 18:41:02 -08001618 }
1619
1620 /**
1621 * Starts a scan for Bluetooth LE devices, looking for devices that
1622 * advertise given services.
1623 *
1624 * <p>Devices which advertise all specified services are reported using the
Matthew Xiecdd94e32013-04-11 16:36:26 -07001625 * {@link LeScanCallback#onLeScan} callback.
Matthew Xieddf7e472013-03-01 18:41:02 -08001626 *
Matthew Xied5752332013-04-24 17:51:37 -07001627 * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN} permission.
Matthew Xieddf7e472013-03-01 18:41:02 -08001628 *
1629 * @param serviceUuids Array of services to look for
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
1632 */
Matthew Xiecdd94e32013-04-11 16:36:26 -07001633 public boolean startLeScan(UUID[] serviceUuids, LeScanCallback callback) {
1634 if (DBG) Log.d(TAG, "startLeScan(): " + serviceUuids);
Matthew Xieddf7e472013-03-01 18:41:02 -08001635
Matthew Xiecdd94e32013-04-11 16:36:26 -07001636 if (callback == null) {
1637 if (DBG) Log.e(TAG, "startLeScan: null callback");
Matthew Xieddf7e472013-03-01 18:41:02 -08001638 return false;
1639 }
1640
Matthew Xiecdd94e32013-04-11 16:36:26 -07001641 synchronized(mLeScanClients) {
1642 if (mLeScanClients.containsKey(callback)) {
1643 if (DBG) Log.e(TAG, "LE Scan has already started");
1644 return false;
1645 }
1646
1647 try {
1648 IBluetoothGatt iGatt = mManagerService.getBluetoothGatt();
Matthew Xie32ab77b2013-05-08 19:26:57 -07001649 if (iGatt == null) {
1650 // BLE is not supported
1651 return false;
1652 }
1653
Matthew Xiecdd94e32013-04-11 16:36:26 -07001654 UUID uuid = UUID.randomUUID();
1655 GattCallbackWrapper wrapper = new GattCallbackWrapper(this, callback, serviceUuids);
Matthew Xiecdd94e32013-04-11 16:36:26 -07001656 iGatt.registerClient(new ParcelUuid(uuid), wrapper);
1657 if (wrapper.scanStarted()) {
1658 mLeScanClients.put(callback, wrapper);
1659 return true;
1660 }
1661 } catch (RemoteException e) {
1662 Log.e(TAG,"",e);
1663 }
1664 }
1665 return false;
Matthew Xieddf7e472013-03-01 18:41:02 -08001666 }
1667
1668 /**
1669 * Stops an ongoing Bluetooth LE device scan.
1670 *
Matthew Xied5752332013-04-24 17:51:37 -07001671 * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN} permission.
Matthew Xiecdd94e32013-04-11 16:36:26 -07001672 *
1673 * @param callback used to identify which scan to stop
1674 * must be the same handle used to start the scan
Matthew Xieddf7e472013-03-01 18:41:02 -08001675 */
Matthew Xiecdd94e32013-04-11 16:36:26 -07001676 public void stopLeScan(LeScanCallback callback) {
1677 if (DBG) Log.d(TAG, "stopLeScan()");
1678 GattCallbackWrapper wrapper;
1679 synchronized(mLeScanClients) {
1680 wrapper = mLeScanClients.remove(callback);
1681 if (wrapper == null) return;
Matthew Xieddf7e472013-03-01 18:41:02 -08001682 }
Matthew Xiecdd94e32013-04-11 16:36:26 -07001683 wrapper.stopLeScan();
Matthew Xieddf7e472013-03-01 18:41:02 -08001684 }
1685
1686 /**
1687 * Bluetooth GATT interface callbacks
1688 */
Matthew Xiecdd94e32013-04-11 16:36:26 -07001689 private static class GattCallbackWrapper extends IBluetoothGattCallback.Stub {
1690 private static final int LE_CALLBACK_REG_TIMEOUT = 2000;
1691 private static final int LE_CALLBACK_REG_WAIT_COUNT = 5;
Wei Wang18c76932013-10-29 21:05:37 -07001692 private static final int CALLBACK_TYPE_SCAN = 0;
1693 private static final int CALLBACK_TYPE_ADV = 1;
Matthew Xieddf7e472013-03-01 18:41:02 -08001694
Matthew Xiecdd94e32013-04-11 16:36:26 -07001695 private final LeScanCallback mLeScanCb;
Wei Wang18c76932013-10-29 21:05:37 -07001696 private int mCallbackType;
1697
Matthew Xiecdd94e32013-04-11 16:36:26 -07001698 // mLeHandle 0: not registered
1699 // -1: scan stopped
1700 // >0: registered and scan started
1701 private int mLeHandle;
1702 private final UUID[] mScanFilter;
1703 private WeakReference<BluetoothAdapter> mBluetoothAdapter;
Matthew Xieddf7e472013-03-01 18:41:02 -08001704
Matthew Xiecdd94e32013-04-11 16:36:26 -07001705 public GattCallbackWrapper(BluetoothAdapter bluetoothAdapter,
1706 LeScanCallback leScanCb, UUID[] uuid) {
1707 mBluetoothAdapter = new WeakReference<BluetoothAdapter>(bluetoothAdapter);
1708 mLeScanCb = leScanCb;
1709 mScanFilter = uuid;
1710 mLeHandle = 0;
Wei Wang18c76932013-10-29 21:05:37 -07001711 mCallbackType = CALLBACK_TYPE_SCAN;
1712 }
1713
1714 public GattCallbackWrapper(BluetoothAdapter bluetoothAdapter, LeScanCallback leScanCb,
1715 UUID[] uuid, int type) {
1716 mBluetoothAdapter = new WeakReference<BluetoothAdapter>(bluetoothAdapter);
1717 mLeScanCb = leScanCb;
1718 mScanFilter = uuid;
1719 mLeHandle = 0;
1720 mCallbackType = type;
Matthew Xiecdd94e32013-04-11 16:36:26 -07001721 }
Matthew Xieddf7e472013-03-01 18:41:02 -08001722
Matthew Xiecdd94e32013-04-11 16:36:26 -07001723 public boolean scanStarted() {
1724 boolean started = false;
1725 synchronized(this) {
1726 if (mLeHandle == -1) return false;
1727
1728 int count = 0;
1729 // wait for callback registration and LE scan to start
1730 while (mLeHandle == 0 && count < LE_CALLBACK_REG_WAIT_COUNT) {
1731 try {
1732 wait(LE_CALLBACK_REG_TIMEOUT);
1733 } catch (InterruptedException e) {
1734 Log.e(TAG, "Callback reg wait interrupted: " + e);
1735 }
1736 count++;
Matthew Xieddf7e472013-03-01 18:41:02 -08001737 }
Matthew Xiecdd94e32013-04-11 16:36:26 -07001738 started = (mLeHandle > 0);
Matthew Xieddf7e472013-03-01 18:41:02 -08001739 }
Matthew Xiecdd94e32013-04-11 16:36:26 -07001740 return started;
1741 }
Matthew Xieddf7e472013-03-01 18:41:02 -08001742
Wei Wang18c76932013-10-29 21:05:37 -07001743 public void stopAdvertising() {
1744 synchronized (this) {
1745 if (mLeHandle <= 0) {
1746 Log.e(TAG, "Error state, mLeHandle: " + mLeHandle);
1747 return;
1748 }
1749 BluetoothAdapter adapter = mBluetoothAdapter.get();
1750 if (adapter != null) {
1751 try {
1752 IBluetoothGatt iGatt = adapter.getBluetoothManager().getBluetoothGatt();
1753 iGatt.stopAdvertising();
1754 Log.d(TAG, "unregeistering client " + mLeHandle);
1755 iGatt.unregisterClient(mLeHandle);
1756 } catch (RemoteException e) {
1757 Log.e(TAG, "Failed to stop advertising and unregister" + e);
1758 }
1759 } else {
1760 Log.e(TAG, "stopAdvertising, BluetoothAdapter is null");
1761 }
1762 mLeHandle = -1;
1763 notifyAll();
1764 }
1765 }
1766
Matthew Xiecdd94e32013-04-11 16:36:26 -07001767 public void stopLeScan() {
1768 synchronized(this) {
1769 if (mLeHandle <= 0) {
1770 Log.e(TAG, "Error state, mLeHandle: " + mLeHandle);
1771 return;
1772 }
1773 BluetoothAdapter adapter = mBluetoothAdapter.get();
1774 if (adapter != null) {
1775 try {
1776 IBluetoothGatt iGatt = adapter.getBluetoothManager().getBluetoothGatt();
1777 iGatt.stopScan(mLeHandle, false);
1778 iGatt.unregisterClient(mLeHandle);
1779 } catch (RemoteException e) {
1780 Log.e(TAG, "Failed to stop scan and unregister" + e);
1781 }
1782 } else {
1783 Log.e(TAG, "stopLeScan, BluetoothAdapter is null");
1784 }
1785 mLeHandle = -1;
1786 notifyAll();
Matthew Xieddf7e472013-03-01 18:41:02 -08001787 }
Matthew Xiecdd94e32013-04-11 16:36:26 -07001788 }
Matthew Xieddf7e472013-03-01 18:41:02 -08001789
Matthew Xiecdd94e32013-04-11 16:36:26 -07001790 /**
1791 * Application interface registered - app is ready to go
1792 */
1793 public void onClientRegistered(int status, int clientIf) {
1794 if (DBG) Log.d(TAG, "onClientRegistered() - status=" + status +
1795 " clientIf=" + clientIf);
1796 synchronized(this) {
1797 if (mLeHandle == -1) {
1798 if (DBG) Log.d(TAG, "onClientRegistered LE scan canceled");
1799 }
1800
1801 if (status == BluetoothGatt.GATT_SUCCESS) {
1802 mLeHandle = clientIf;
1803 IBluetoothGatt iGatt = null;
1804 try {
1805 BluetoothAdapter adapter = mBluetoothAdapter.get();
1806 if (adapter != null) {
1807 iGatt = adapter.getBluetoothManager().getBluetoothGatt();
Wei Wang18c76932013-10-29 21:05:37 -07001808 if (mCallbackType == CALLBACK_TYPE_ADV) {
1809 iGatt.startAdvertising(mLeHandle);
Matthew Xiecdd94e32013-04-11 16:36:26 -07001810 } else {
Wei Wang18c76932013-10-29 21:05:37 -07001811 if (mScanFilter == null) {
1812 iGatt.startScan(mLeHandle, false);
1813 } else {
1814 ParcelUuid[] uuids = new ParcelUuid[mScanFilter.length];
1815 for(int i = 0; i != uuids.length; ++i) {
1816 uuids[i] = new ParcelUuid(mScanFilter[i]);
1817 }
1818 iGatt.startScanWithUuids(mLeHandle, false, uuids);
1819 }
Matthew Xiecdd94e32013-04-11 16:36:26 -07001820 }
1821 } else {
1822 Log.e(TAG, "onClientRegistered, BluetoothAdapter null");
1823 mLeHandle = -1;
1824 }
1825 } catch (RemoteException e) {
1826 Log.e(TAG, "fail to start le scan: " + e);
1827 mLeHandle = -1;
1828 }
1829 if (mLeHandle == -1) {
Wei Wang18c76932013-10-29 21:05:37 -07001830 // registration succeeded but start scan or advertise failed
Matthew Xiecdd94e32013-04-11 16:36:26 -07001831 if (iGatt != null) {
1832 try {
1833 iGatt.unregisterClient(mLeHandle);
1834 } catch (RemoteException e) {
1835 Log.e(TAG, "fail to unregister callback: " + mLeHandle +
1836 " error: " + e);
1837 }
1838 }
1839 }
1840 } else {
1841 // registration failed
1842 mLeHandle = -1;
1843 }
1844 notifyAll();
Matthew Xieddf7e472013-03-01 18:41:02 -08001845 }
Matthew Xiecdd94e32013-04-11 16:36:26 -07001846 }
Matthew Xieddf7e472013-03-01 18:41:02 -08001847
Matthew Xiecdd94e32013-04-11 16:36:26 -07001848 public void onClientConnectionState(int status, int clientIf,
1849 boolean connected, String address) {
1850 // no op
1851 }
1852
1853 /**
1854 * Callback reporting an LE scan result.
1855 * @hide
1856 */
1857 public void onScanResult(String address, int rssi, byte[] advData) {
1858 if (DBG) Log.d(TAG, "onScanResult() - Device=" + address + " RSSI=" +rssi);
1859
1860 // Check null in case the scan has been stopped
1861 synchronized(this) {
1862 if (mLeHandle <= 0) return;
Matthew Xieddf7e472013-03-01 18:41:02 -08001863 }
Matthew Xiecdd94e32013-04-11 16:36:26 -07001864 try {
1865 BluetoothAdapter adapter = mBluetoothAdapter.get();
1866 if (adapter == null) {
1867 Log.d(TAG, "onScanResult, BluetoothAdapter null");
1868 return;
1869 }
1870 mLeScanCb.onLeScan(adapter.getRemoteDevice(address), rssi, advData);
1871 } catch (Exception ex) {
1872 Log.w(TAG, "Unhandled exception: " + ex);
Matthew Xieddf7e472013-03-01 18:41:02 -08001873 }
Matthew Xiecdd94e32013-04-11 16:36:26 -07001874 }
Matthew Xieddf7e472013-03-01 18:41:02 -08001875
Matthew Xiecdd94e32013-04-11 16:36:26 -07001876 public void onGetService(String address, int srvcType,
1877 int srvcInstId, ParcelUuid srvcUuid) {
1878 // no op
1879 }
Matthew Xieddf7e472013-03-01 18:41:02 -08001880
Matthew Xiecdd94e32013-04-11 16:36:26 -07001881 public void onGetIncludedService(String address, int srvcType,
1882 int srvcInstId, ParcelUuid srvcUuid,
1883 int inclSrvcType, int inclSrvcInstId,
1884 ParcelUuid inclSrvcUuid) {
1885 // no op
1886 }
Matthew Xieddf7e472013-03-01 18:41:02 -08001887
Matthew Xiecdd94e32013-04-11 16:36:26 -07001888 public void onGetCharacteristic(String address, int srvcType,
1889 int srvcInstId, ParcelUuid srvcUuid,
1890 int charInstId, ParcelUuid charUuid,
1891 int charProps) {
1892 // no op
1893 }
Matthew Xieddf7e472013-03-01 18:41:02 -08001894
Matthew Xiecdd94e32013-04-11 16:36:26 -07001895 public void onGetDescriptor(String address, int srvcType,
1896 int srvcInstId, ParcelUuid srvcUuid,
1897 int charInstId, ParcelUuid charUuid,
Andre Eisenbach25b9cf92013-07-08 23:58:16 -07001898 int descInstId, ParcelUuid descUuid) {
Matthew Xiecdd94e32013-04-11 16:36:26 -07001899 // no op
1900 }
1901
1902 public void onSearchComplete(String address, int status) {
1903 // no op
1904 }
1905
1906 public void onCharacteristicRead(String address, int status, int srvcType,
1907 int srvcInstId, ParcelUuid srvcUuid,
1908 int charInstId, ParcelUuid charUuid, byte[] value) {
1909 // no op
1910 }
1911
1912 public void onCharacteristicWrite(String address, int status, int srvcType,
1913 int srvcInstId, ParcelUuid srvcUuid,
1914 int charInstId, ParcelUuid charUuid) {
1915 // no op
1916 }
1917
1918 public void onNotify(String address, int srvcType,
Matthew Xieddf7e472013-03-01 18:41:02 -08001919 int srvcInstId, ParcelUuid srvcUuid,
1920 int charInstId, ParcelUuid charUuid,
1921 byte[] value) {
Matthew Xiecdd94e32013-04-11 16:36:26 -07001922 // no op
1923 }
Matthew Xieddf7e472013-03-01 18:41:02 -08001924
Matthew Xiecdd94e32013-04-11 16:36:26 -07001925 public void onDescriptorRead(String address, int status, int srvcType,
1926 int srvcInstId, ParcelUuid srvcUuid,
1927 int charInstId, ParcelUuid charUuid,
Andre Eisenbach25b9cf92013-07-08 23:58:16 -07001928 int descInstId, ParcelUuid descrUuid, byte[] value) {
Matthew Xiecdd94e32013-04-11 16:36:26 -07001929 // no op
1930 }
Matthew Xieddf7e472013-03-01 18:41:02 -08001931
Matthew Xiecdd94e32013-04-11 16:36:26 -07001932 public void onDescriptorWrite(String address, int status, int srvcType,
1933 int srvcInstId, ParcelUuid srvcUuid,
1934 int charInstId, ParcelUuid charUuid,
Andre Eisenbach25b9cf92013-07-08 23:58:16 -07001935 int descInstId, ParcelUuid descrUuid) {
Matthew Xiecdd94e32013-04-11 16:36:26 -07001936 // no op
1937 }
Matthew Xieddf7e472013-03-01 18:41:02 -08001938
Matthew Xiecdd94e32013-04-11 16:36:26 -07001939 public void onExecuteWrite(String address, int status) {
1940 // no op
1941 }
Matthew Xieddf7e472013-03-01 18:41:02 -08001942
Matthew Xiecdd94e32013-04-11 16:36:26 -07001943 public void onReadRemoteRssi(String address, int rssi, int status) {
1944 // no op
1945 }
Andre Eisenbachf46b21a2013-08-06 19:57:48 -07001946
1947 public void onListen(int status) {
1948 // no op
1949 }
Matthew Xiecdd94e32013-04-11 16:36:26 -07001950 }
Matthew Xieddf7e472013-03-01 18:41:02 -08001951
Nick Pellybd022f42009-08-14 18:33:38 -07001952}