blob: d1f1f2af44c991b97c673373562a3f4a2cf7762f [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 Pelly24bb9b82009-10-02 20:34:18 -070022import android.os.Binder;
Nick Pellyf242b7b2009-10-08 00:12:45 +020023import android.os.IBinder;
Nick Pelly24bb9b82009-10-02 20:34:18 -070024import android.os.Message;
Nick Pellyaef439e2009-09-28 12:33:17 -070025import android.os.ParcelUuid;
Nick Pellybd022f42009-08-14 18:33:38 -070026import android.os.RemoteException;
Nick Pellyf242b7b2009-10-08 00:12:45 +020027import android.os.ServiceManager;
Nick Pellybd022f42009-08-14 18:33:38 -070028import android.util.Log;
Jaikumar Ganeshcc5494c2010-09-09 15:37:57 -070029import android.util.Pair;
Wei Wang86b3fa62013-10-29 21:05:37 -070030
Nick Pellybd022f42009-08-14 18:33:38 -070031import java.io.IOException;
Matthew Xiecdd94e32013-04-11 16:36:26 -070032import java.lang.ref.WeakReference;
fredc903ac6f2012-04-24 03:59:57 -070033import java.util.ArrayList;
Jaikumar Ganeshcc5494c2010-09-09 15:37:57 -070034import java.util.Arrays;
Nick Pellybd022f42009-08-14 18:33:38 -070035import java.util.Collections;
Matthew Xiecdd94e32013-04-11 16:36:26 -070036import java.util.HashMap;
Wei Wang86b3fa62013-10-29 21:05:37 -070037import java.util.HashSet;
Jeff Sharkeyfea17de2013-06-11 14:13:09 -070038import java.util.Locale;
Matthew Xiecdd94e32013-04-11 16:36:26 -070039import java.util.Map;
Nick Pelly24bb9b82009-10-02 20:34:18 -070040import java.util.Random;
41import java.util.Set;
Nick Pelly16fb88a2009-10-07 07:44:03 +020042import java.util.UUID;
Nick Pellybd022f42009-08-14 18:33:38 -070043
44/**
Scott Main9fab0ae2009-11-03 18:17:59 -080045 * Represents the local device Bluetooth adapter. The {@link BluetoothAdapter}
46 * lets you perform fundamental Bluetooth tasks, such as initiate
47 * device discovery, query a list of bonded (paired) devices,
48 * instantiate a {@link BluetoothDevice} using a known MAC address, and create
49 * a {@link BluetoothServerSocket} to listen for connection requests from other
Matthew Xieb30f91e2013-05-29 10:19:06 -070050 * devices, and start a scan for Bluetooth LE devices.
Scott Main9fab0ae2009-11-03 18:17:59 -080051 *
52 * <p>To get a {@link BluetoothAdapter} representing the local Bluetooth
Kim Schulz0d376052013-08-22 11:18:02 +020053 * adapter, when running on JELLY_BEAN_MR1 and below, call the
Matthew Xieb30f91e2013-05-29 10:19:06 -070054 * static {@link #getDefaultAdapter} method; when running on JELLY_BEAN_MR2 and
55 * higher, retrieve it through
56 * {@link android.content.Context#getSystemService} with
57 * {@link android.content.Context#BLUETOOTH_SERVICE}.
Scott Main9fab0ae2009-11-03 18:17:59 -080058 * Fundamentally, this is your starting point for all
59 * Bluetooth actions. Once you have the local adapter, you can get a set of
60 * {@link BluetoothDevice} objects representing all paired devices with
61 * {@link #getBondedDevices()}; start device discovery with
62 * {@link #startDiscovery()}; or create a {@link BluetoothServerSocket} to
63 * listen for incoming connection requests with
Matthew Xieb30f91e2013-05-29 10:19:06 -070064 * {@link #listenUsingRfcommWithServiceRecord(String,UUID)}; or start a scan for
65 * Bluetooth LE devices with {@link #startLeScan(LeScanCallback callback)}.
Scott Main9fab0ae2009-11-03 18:17:59 -080066 *
67 * <p class="note"><strong>Note:</strong>
68 * Most methods require the {@link android.Manifest.permission#BLUETOOTH}
69 * permission and some also require the
70 * {@link android.Manifest.permission#BLUETOOTH_ADMIN} permission.
71 *
Joe Fernandez3aef8e1d2011-12-20 10:38:34 -080072 * <div class="special reference">
73 * <h3>Developer Guides</h3>
74 * <p>For more information about using Bluetooth, read the
75 * <a href="{@docRoot}guide/topics/wireless/bluetooth.html">Bluetooth</a> developer guide.</p>
76 * </div>
77 *
Scott Main9fab0ae2009-11-03 18:17:59 -080078 * {@see BluetoothDevice}
79 * {@see BluetoothServerSocket}
Nick Pellybd022f42009-08-14 18:33:38 -070080 */
81public final class BluetoothAdapter {
82 private static final String TAG = "BluetoothAdapter";
fredc0f420372012-04-12 00:02:00 -070083 private static final boolean DBG = true;
Matthew Xie3b6214f2012-08-29 00:12:29 -070084 private static final boolean VDBG = false;
Nick Pellybd022f42009-08-14 18:33:38 -070085
Nick Pellyde893f52009-09-08 13:15:33 -070086 /**
Nick Pellyb24e11b2009-09-08 17:40:43 -070087 * Sentinel error value for this class. Guaranteed to not equal any other
88 * integer constant in this class. Provided as a convenience for functions
89 * that require a sentinel error value, for example:
90 * <p><code>Intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
91 * BluetoothAdapter.ERROR)</code>
92 */
Nick Pelly005b2282009-09-10 10:21:56 -070093 public static final int ERROR = Integer.MIN_VALUE;
Nick Pellyb24e11b2009-09-08 17:40:43 -070094
95 /**
Nick Pellyde893f52009-09-08 13:15:33 -070096 * Broadcast Action: The state of the local Bluetooth adapter has been
97 * changed.
98 * <p>For example, Bluetooth has been turned on or off.
Nick Pelly005b2282009-09-10 10:21:56 -070099 * <p>Always contains the extra fields {@link #EXTRA_STATE} and {@link
Nick Pellyde893f52009-09-08 13:15:33 -0700100 * #EXTRA_PREVIOUS_STATE} containing the new and old states
101 * respectively.
102 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} to receive.
103 */
104 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
105 public static final String ACTION_STATE_CHANGED =
Nick Pelly005b2282009-09-10 10:21:56 -0700106 "android.bluetooth.adapter.action.STATE_CHANGED";
Nick Pellybd022f42009-08-14 18:33:38 -0700107
Nick Pellyde893f52009-09-08 13:15:33 -0700108 /**
109 * Used as an int extra field in {@link #ACTION_STATE_CHANGED}
110 * intents to request the current power state. Possible values are:
111 * {@link #STATE_OFF},
112 * {@link #STATE_TURNING_ON},
113 * {@link #STATE_ON},
114 * {@link #STATE_TURNING_OFF},
115 */
116 public static final String EXTRA_STATE =
Nick Pelly005b2282009-09-10 10:21:56 -0700117 "android.bluetooth.adapter.extra.STATE";
Nick Pellyde893f52009-09-08 13:15:33 -0700118 /**
119 * Used as an int extra field in {@link #ACTION_STATE_CHANGED}
120 * intents to request the previous power state. Possible values are:
121 * {@link #STATE_OFF},
122 * {@link #STATE_TURNING_ON},
123 * {@link #STATE_ON},
124 * {@link #STATE_TURNING_OFF},
125 */
126 public static final String EXTRA_PREVIOUS_STATE =
Nick Pelly005b2282009-09-10 10:21:56 -0700127 "android.bluetooth.adapter.extra.PREVIOUS_STATE";
Nick Pellybd022f42009-08-14 18:33:38 -0700128
Nick Pellyde893f52009-09-08 13:15:33 -0700129 /**
130 * Indicates the local Bluetooth adapter is off.
131 */
Nick Pelly005b2282009-09-10 10:21:56 -0700132 public static final int STATE_OFF = 10;
Nick Pellyde893f52009-09-08 13:15:33 -0700133 /**
134 * Indicates the local Bluetooth adapter is turning on. However local
135 * clients should wait for {@link #STATE_ON} before attempting to
136 * use the adapter.
137 */
Nick Pelly005b2282009-09-10 10:21:56 -0700138 public static final int STATE_TURNING_ON = 11;
Nick Pellyde893f52009-09-08 13:15:33 -0700139 /**
140 * Indicates the local Bluetooth adapter is on, and ready for use.
141 */
Nick Pelly005b2282009-09-10 10:21:56 -0700142 public static final int STATE_ON = 12;
Nick Pellyde893f52009-09-08 13:15:33 -0700143 /**
144 * Indicates the local Bluetooth adapter is turning off. Local clients
145 * should immediately attempt graceful disconnection of any remote links.
146 */
Nick Pelly005b2282009-09-10 10:21:56 -0700147 public static final int STATE_TURNING_OFF = 13;
Nick Pellyde893f52009-09-08 13:15:33 -0700148
149 /**
Nick Pelly18b1e792009-09-24 11:14:15 -0700150 * Activity Action: Show a system activity that requests discoverable mode.
Scott Main6d95fc02009-11-19 17:00:19 -0800151 * This activity will also request the user to turn on Bluetooth if it
Nick Pelly1acdcc12009-09-28 10:33:55 -0700152 * is not currently enabled.
Nick Pelly18b1e792009-09-24 11:14:15 -0700153 * <p>Discoverable mode is equivalent to {@link
154 * #SCAN_MODE_CONNECTABLE_DISCOVERABLE}. It allows remote devices to see
155 * this Bluetooth adapter when they perform a discovery.
Scott Main6d95fc02009-11-19 17:00:19 -0800156 * <p>For privacy, Android is not discoverable by default.
157 * <p>The sender of this Intent can optionally use extra field {@link
Nick Pelly18b1e792009-09-24 11:14:15 -0700158 * #EXTRA_DISCOVERABLE_DURATION} to request the duration of
159 * discoverability. Currently the default duration is 120 seconds, and
160 * maximum duration is capped at 300 seconds for each request.
161 * <p>Notification of the result of this activity is posted using the
162 * {@link android.app.Activity#onActivityResult} callback. The
163 * <code>resultCode</code>
Michael Chancdd28642009-11-05 18:29:01 -0800164 * will be the duration (in seconds) of discoverability or
165 * {@link android.app.Activity#RESULT_CANCELED} if the user rejected
166 * discoverability or an error has occurred.
Nick Pelly18b1e792009-09-24 11:14:15 -0700167 * <p>Applications can also listen for {@link #ACTION_SCAN_MODE_CHANGED}
Scott Main6d95fc02009-11-19 17:00:19 -0800168 * for global notification whenever the scan mode changes. For example, an
169 * application can be notified when the device has ended discoverability.
Nick Pelly1acdcc12009-09-28 10:33:55 -0700170 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
Nick Pelly18b1e792009-09-24 11:14:15 -0700171 */
172 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
173 public static final String ACTION_REQUEST_DISCOVERABLE =
174 "android.bluetooth.adapter.action.REQUEST_DISCOVERABLE";
175
176 /**
177 * Used as an optional int extra field in {@link
178 * #ACTION_REQUEST_DISCOVERABLE} intents to request a specific duration
179 * for discoverability in seconds. The current default is 120 seconds, and
180 * requests over 300 seconds will be capped. These values could change.
181 */
182 public static final String EXTRA_DISCOVERABLE_DURATION =
183 "android.bluetooth.adapter.extra.DISCOVERABLE_DURATION";
184
185 /**
Wei Wang86b3fa62013-10-29 21:05:37 -0700186 * Activity Action: Show a system activity to request BLE advertising.<br>
187 * If the device is not doing BLE advertising, this activity will start BLE advertising for the
188 * device, otherwise it will continue BLE advertising using the current
189 * {@link BluetoothAdvScanData}. <br>
190 * Note this activity will also request the user to turn on Bluetooth if it's not currently
191 * enabled.
192 * @hide
193 */
194 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
195 public static final String ACTION_START_ADVERTISING =
196 "android.bluetooth.adapter.action.START_ADVERTISING";
197
198 /**
199 * Activity Action: Stop the current BLE advertising.
200 * @hide
201 */
202 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
203 public static final String ACTION_STOP_ADVERTISING =
204 "android.bluetooth.adapter.action.STOP_ADVERTISING";
205
206 /**
207 * Broadcast Action: Indicate BLE Advertising is started.
208 * @hide
209 */
210 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
211 public static final String ACTION_BLUETOOTH_ADVERTISING_STARTED =
212 "android.bluetooth.adapter.action.ADVERTISING_STARTED";
213
214 /**
215 * Broadcast Action: Indicated BLE Advertising is stopped.
216 * @hide
217 */
218 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
219 public static final String ACTION_BLUETOOTH_ADVERTISING_STOPPED =
220 "android.bluetooth.adapter.action.ADVERTISING_STOPPED";
221
222 /**
Nick Pelly1acdcc12009-09-28 10:33:55 -0700223 * Activity Action: Show a system activity that allows the user to turn on
224 * Bluetooth.
225 * <p>This system activity will return once Bluetooth has completed turning
226 * on, or the user has decided not to turn Bluetooth on.
227 * <p>Notification of the result of this activity is posted using the
228 * {@link android.app.Activity#onActivityResult} callback. The
229 * <code>resultCode</code>
Michael Chancdd28642009-11-05 18:29:01 -0800230 * will be {@link android.app.Activity#RESULT_OK} if Bluetooth has been
231 * turned on or {@link android.app.Activity#RESULT_CANCELED} if the user
232 * has rejected the request or an error has occurred.
Nick Pelly1acdcc12009-09-28 10:33:55 -0700233 * <p>Applications can also listen for {@link #ACTION_STATE_CHANGED}
234 * for global notification whenever Bluetooth is turned on or off.
235 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
236 */
237 @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
238 public static final String ACTION_REQUEST_ENABLE =
239 "android.bluetooth.adapter.action.REQUEST_ENABLE";
240
241 /**
Nick Pellyde893f52009-09-08 13:15:33 -0700242 * Broadcast Action: Indicates the Bluetooth scan mode of the local Adapter
243 * has changed.
Nick Pelly005b2282009-09-10 10:21:56 -0700244 * <p>Always contains the extra fields {@link #EXTRA_SCAN_MODE} and {@link
Nick Pellyde893f52009-09-08 13:15:33 -0700245 * #EXTRA_PREVIOUS_SCAN_MODE} containing the new and old scan modes
246 * respectively.
247 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
248 */
249 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
250 public static final String ACTION_SCAN_MODE_CHANGED =
Nick Pelly005b2282009-09-10 10:21:56 -0700251 "android.bluetooth.adapter.action.SCAN_MODE_CHANGED";
Nick Pellyde893f52009-09-08 13:15:33 -0700252
253 /**
254 * Used as an int extra field in {@link #ACTION_SCAN_MODE_CHANGED}
255 * intents to request the current scan mode. Possible values are:
256 * {@link #SCAN_MODE_NONE},
257 * {@link #SCAN_MODE_CONNECTABLE},
258 * {@link #SCAN_MODE_CONNECTABLE_DISCOVERABLE},
259 */
Nick Pelly005b2282009-09-10 10:21:56 -0700260 public static final String EXTRA_SCAN_MODE = "android.bluetooth.adapter.extra.SCAN_MODE";
Nick Pellyde893f52009-09-08 13:15:33 -0700261 /**
262 * Used as an int extra field in {@link #ACTION_SCAN_MODE_CHANGED}
263 * intents to request the previous scan mode. Possible values are:
264 * {@link #SCAN_MODE_NONE},
265 * {@link #SCAN_MODE_CONNECTABLE},
266 * {@link #SCAN_MODE_CONNECTABLE_DISCOVERABLE},
267 */
268 public static final String EXTRA_PREVIOUS_SCAN_MODE =
Nick Pelly005b2282009-09-10 10:21:56 -0700269 "android.bluetooth.adapter.extra.PREVIOUS_SCAN_MODE";
Nick Pellyde893f52009-09-08 13:15:33 -0700270
271 /**
272 * Indicates that both inquiry scan and page scan are disabled on the local
273 * Bluetooth adapter. Therefore this device is neither discoverable
274 * nor connectable from remote Bluetooth devices.
275 */
Nick Pelly005b2282009-09-10 10:21:56 -0700276 public static final int SCAN_MODE_NONE = 20;
Nick Pellyde893f52009-09-08 13:15:33 -0700277 /**
278 * Indicates that inquiry scan is disabled, but page scan is enabled on the
279 * local Bluetooth adapter. Therefore this device is not discoverable from
280 * remote Bluetooth devices, but is connectable from remote devices that
281 * have previously discovered this device.
282 */
Nick Pelly005b2282009-09-10 10:21:56 -0700283 public static final int SCAN_MODE_CONNECTABLE = 21;
Nick Pellyde893f52009-09-08 13:15:33 -0700284 /**
285 * Indicates that both inquiry scan and page scan are enabled on the local
286 * Bluetooth adapter. Therefore this device is both discoverable and
287 * connectable from remote Bluetooth devices.
288 */
Nick Pelly005b2282009-09-10 10:21:56 -0700289 public static final int SCAN_MODE_CONNECTABLE_DISCOVERABLE = 23;
Nick Pellybd022f42009-08-14 18:33:38 -0700290
Nick Pelly005b2282009-09-10 10:21:56 -0700291 /**
292 * Broadcast Action: The local Bluetooth adapter has started the remote
293 * device discovery process.
294 * <p>This usually involves an inquiry scan of about 12 seconds, followed
295 * by a page scan of each new device to retrieve its Bluetooth name.
296 * <p>Register for {@link BluetoothDevice#ACTION_FOUND} to be notified as
297 * remote Bluetooth devices are found.
298 * <p>Device discovery is a heavyweight procedure. New connections to
299 * remote Bluetooth devices should not be attempted while discovery is in
300 * progress, and existing connections will experience limited bandwidth
301 * and high latency. Use {@link #cancelDiscovery()} to cancel an ongoing
302 * discovery.
303 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} to receive.
304 */
305 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
306 public static final String ACTION_DISCOVERY_STARTED =
307 "android.bluetooth.adapter.action.DISCOVERY_STARTED";
308 /**
309 * Broadcast Action: The local Bluetooth adapter has finished the device
310 * discovery process.
311 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} to receive.
312 */
313 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
314 public static final String ACTION_DISCOVERY_FINISHED =
315 "android.bluetooth.adapter.action.DISCOVERY_FINISHED";
316
317 /**
318 * Broadcast Action: The local Bluetooth adapter has changed its friendly
319 * Bluetooth name.
320 * <p>This name is visible to remote Bluetooth devices.
321 * <p>Always contains the extra field {@link #EXTRA_LOCAL_NAME} containing
322 * the name.
323 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} to receive.
324 */
325 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
326 public static final String ACTION_LOCAL_NAME_CHANGED =
327 "android.bluetooth.adapter.action.LOCAL_NAME_CHANGED";
328 /**
329 * Used as a String extra field in {@link #ACTION_LOCAL_NAME_CHANGED}
330 * intents to request the local Bluetooth name.
331 */
332 public static final String EXTRA_LOCAL_NAME = "android.bluetooth.adapter.extra.LOCAL_NAME";
333
Jaikumar Ganesh62c37ef2010-08-24 17:36:13 -0700334 /**
335 * Intent used to broadcast the change in connection state of the local
336 * Bluetooth adapter to a profile of the remote device. When the adapter is
337 * not connected to any profiles of any remote devices and it attempts a
338 * connection to a profile this intent will sent. Once connected, this intent
339 * will not be sent for any more connection attempts to any profiles of any
340 * remote device. When the adapter disconnects from the last profile its
341 * connected to of any remote device, this intent will be sent.
342 *
343 * <p> This intent is useful for applications that are only concerned about
344 * whether the local adapter is connected to any profile of any device and
345 * are not really concerned about which profile. For example, an application
346 * which displays an icon to display whether Bluetooth is connected or not
347 * can use this intent.
348 *
349 * <p>This intent will have 3 extras:
Jaikumar Ganesh0b5b35f2011-02-01 16:47:11 -0800350 * {@link #EXTRA_CONNECTION_STATE} - The current connection state.
351 * {@link #EXTRA_PREVIOUS_CONNECTION_STATE}- The previous connection state.
Jaikumar Ganesh62c37ef2010-08-24 17:36:13 -0700352 * {@link BluetoothDevice#EXTRA_DEVICE} - The remote device.
353 *
Jaikumar Ganesh0b5b35f2011-02-01 16:47:11 -0800354 * {@link #EXTRA_CONNECTION_STATE} or {@link #EXTRA_PREVIOUS_CONNECTION_STATE}
355 * can be any of {@link #STATE_DISCONNECTED}, {@link #STATE_CONNECTING},
Jaikumar Ganesh62c37ef2010-08-24 17:36:13 -0700356 * {@link #STATE_CONNECTED}, {@link #STATE_DISCONNECTING}.
357 *
358 * <p>Requires {@link android.Manifest.permission#BLUETOOTH} to receive.
359 */
360 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
361 public static final String ACTION_CONNECTION_STATE_CHANGED =
362 "android.bluetooth.adapter.action.CONNECTION_STATE_CHANGED";
363
364 /**
365 * Extra used by {@link #ACTION_CONNECTION_STATE_CHANGED}
366 *
367 * This extra represents the current connection state.
368 */
369 public static final String EXTRA_CONNECTION_STATE =
370 "android.bluetooth.adapter.extra.CONNECTION_STATE";
371
372 /**
373 * Extra used by {@link #ACTION_CONNECTION_STATE_CHANGED}
374 *
375 * This extra represents the previous connection state.
376 */
377 public static final String EXTRA_PREVIOUS_CONNECTION_STATE =
378 "android.bluetooth.adapter.extra.PREVIOUS_CONNECTION_STATE";
379
380 /** The profile is in disconnected state */
381 public static final int STATE_DISCONNECTED = 0;
382 /** The profile is in connecting state */
383 public static final int STATE_CONNECTING = 1;
384 /** The profile is in connected state */
385 public static final int STATE_CONNECTED = 2;
386 /** The profile is in disconnecting state */
387 public static final int STATE_DISCONNECTING = 3;
388
Nick Pellyf242b7b2009-10-08 00:12:45 +0200389 /** @hide */
fredc0f420372012-04-12 00:02:00 -0700390 public static final String BLUETOOTH_MANAGER_SERVICE = "bluetooth_manager";
Nick Pellyf242b7b2009-10-08 00:12:45 +0200391
Nick Pelly005b2282009-09-10 10:21:56 -0700392 private static final int ADDRESS_LENGTH = 17;
Nick Pellybd022f42009-08-14 18:33:38 -0700393
Nick Pellyf242b7b2009-10-08 00:12:45 +0200394 /**
Jake Hambyf51eada2010-09-21 13:39:53 -0700395 * Lazily initialized singleton. Guaranteed final after first object
Nick Pellyf242b7b2009-10-08 00:12:45 +0200396 * constructed.
397 */
398 private static BluetoothAdapter sAdapter;
399
fredc0f420372012-04-12 00:02:00 -0700400 private final IBluetoothManager mManagerService;
401 private IBluetooth mService;
Nick Pellybd022f42009-08-14 18:33:38 -0700402
Matthew Xiecdd94e32013-04-11 16:36:26 -0700403 private final Map<LeScanCallback, GattCallbackWrapper> mLeScanClients;
Wei Wang86b3fa62013-10-29 21:05:37 -0700404 private BluetoothAdvScanData mBluetoothAdvScanData = null;
405 private GattCallbackWrapper mAdvertisingCallback;
Matthew Xie484867a2011-08-25 16:45:58 -0700406
Nick Pellybd022f42009-08-14 18:33:38 -0700407 /**
Nick Pellyf242b7b2009-10-08 00:12:45 +0200408 * Get a handle to the default local Bluetooth adapter.
409 * <p>Currently Android only supports one Bluetooth adapter, but the API
410 * could be extended to support more. This will always return the default
411 * adapter.
412 * @return the default local adapter, or null if Bluetooth is not supported
413 * on this hardware platform
414 */
415 public static synchronized BluetoothAdapter getDefaultAdapter() {
416 if (sAdapter == null) {
fredc0f420372012-04-12 00:02:00 -0700417 IBinder b = ServiceManager.getService(BLUETOOTH_MANAGER_SERVICE);
Nick Pellyf242b7b2009-10-08 00:12:45 +0200418 if (b != null) {
fredc0f420372012-04-12 00:02:00 -0700419 IBluetoothManager managerService = IBluetoothManager.Stub.asInterface(b);
420 sAdapter = new BluetoothAdapter(managerService);
Jaikumar Ganeshe4caddb2012-01-25 16:16:48 -0800421 } else {
422 Log.e(TAG, "Bluetooth binder is null");
Nick Pellyf242b7b2009-10-08 00:12:45 +0200423 }
424 }
425 return sAdapter;
426 }
427
428 /**
429 * Use {@link #getDefaultAdapter} to get the BluetoothAdapter instance.
Nick Pellybd022f42009-08-14 18:33:38 -0700430 */
fredc0f420372012-04-12 00:02:00 -0700431 BluetoothAdapter(IBluetoothManager managerService) {
432
433 if (managerService == null) {
434 throw new IllegalArgumentException("bluetooth manager service is null");
Nick Pellybd022f42009-08-14 18:33:38 -0700435 }
fredc0f420372012-04-12 00:02:00 -0700436 try {
437 mService = managerService.registerAdapter(mManagerCallback);
438 } catch (RemoteException e) {Log.e(TAG, "", e);}
439 mManagerService = managerService;
Matthew Xiecdd94e32013-04-11 16:36:26 -0700440 mLeScanClients = new HashMap<LeScanCallback, GattCallbackWrapper>();
Nick Pellybd022f42009-08-14 18:33:38 -0700441 }
442
443 /**
Nick Pelly45e27042009-08-19 11:00:00 -0700444 * Get a {@link BluetoothDevice} object for the given Bluetooth hardware
445 * address.
446 * <p>Valid Bluetooth hardware addresses must be upper case, in a format
Nick Pelly005b2282009-09-10 10:21:56 -0700447 * such as "00:11:22:33:AA:BB". The helper {@link #checkBluetoothAddress} is
448 * available to validate a Bluetooth address.
Nick Pelly45e27042009-08-19 11:00:00 -0700449 * <p>A {@link BluetoothDevice} will always be returned for a valid
450 * hardware address, even if this adapter has never seen that device.
Nick Pellyde893f52009-09-08 13:15:33 -0700451 *
Nick Pellybd022f42009-08-14 18:33:38 -0700452 * @param address valid Bluetooth MAC address
Nick Pelly45e27042009-08-19 11:00:00 -0700453 * @throws IllegalArgumentException if address is invalid
Nick Pellybd022f42009-08-14 18:33:38 -0700454 */
455 public BluetoothDevice getRemoteDevice(String address) {
456 return new BluetoothDevice(address);
457 }
458
459 /**
Nick Pelly75596b42011-12-07 15:03:55 -0800460 * Get a {@link BluetoothDevice} object for the given Bluetooth hardware
461 * address.
462 * <p>Valid Bluetooth hardware addresses must be 6 bytes. This method
463 * expects the address in network byte order (MSB first).
464 * <p>A {@link BluetoothDevice} will always be returned for a valid
465 * hardware address, even if this adapter has never seen that device.
466 *
467 * @param address Bluetooth MAC address (6 bytes)
468 * @throws IllegalArgumentException if address is invalid
469 */
470 public BluetoothDevice getRemoteDevice(byte[] address) {
471 if (address == null || address.length != 6) {
472 throw new IllegalArgumentException("Bluetooth address must have 6 bytes");
473 }
Jeff Sharkeyfea17de2013-06-11 14:13:09 -0700474 return new BluetoothDevice(String.format(Locale.US, "%02X:%02X:%02X:%02X:%02X:%02X",
Nick Pelly75596b42011-12-07 15:03:55 -0800475 address[0], address[1], address[2], address[3], address[4], address[5]));
476 }
477
478 /**
Wei Wang86b3fa62013-10-29 21:05:37 -0700479 * Returns a {@link BluetoothAdvScanData} object representing advertising data.
480 * @hide
481 */
482 public BluetoothAdvScanData getAdvScanData() {
483 try {
484 IBluetoothGatt iGatt = mManagerService.getBluetoothGatt();
485 if (iGatt == null) {
486 // BLE is not supported
487 Log.e(TAG, "failed to start, iGatt null");
488 return null;
489 }
490 if (mBluetoothAdvScanData == null) {
491 mBluetoothAdvScanData = new BluetoothAdvScanData(iGatt, BluetoothAdvScanData.AD);
492 }
493 return mBluetoothAdvScanData;
494 } catch (RemoteException e) {
495 Log.e(TAG, "failed to get advScanData, error: " + e);
496 return null;
497 }
498 }
499
500
501 /**
502 * Start BLE advertising using current {@link BluetoothAdvScanData}.
503 * An app should start advertising by requesting
504 * {@link BluetoothAdapter#ACTION_START_ADVERTISING} instead of calling this method directly.
505 * <p>Requires {@link android.Manifest.permission#BLUETOOTH_PRIVILEGED}
506 *
507 * @return true if BLE avertising succeeds, false otherwise.
508 * @hide
509 */
510 public boolean startAdvertising() {
511 if (getState() != STATE_ON) return false;
512
513 try {
514 IBluetoothGatt iGatt = mManagerService.getBluetoothGatt();
515 if (iGatt == null) {
516 // BLE is not supported.
517 return false;
518 }
519 // Restart/reset advertising packets if advertising is in progress.
520 if (isAdvertising()) {
521 // Invalid advertising callback.
522 if (mAdvertisingCallback == null || mAdvertisingCallback.mLeHandle == -1) {
523 Log.e(TAG, "failed to restart advertising, invalid callback");
524 return false;
525 }
526 iGatt.startAdvertising(mAdvertisingCallback.mLeHandle);
527 return true;
528 }
529 UUID uuid = UUID.randomUUID();
530 GattCallbackWrapper wrapper =
531 new GattCallbackWrapper(this, null, null, GattCallbackWrapper.CALLBACK_TYPE_ADV);
532 iGatt.registerClient(new ParcelUuid(uuid), wrapper);
533 mAdvertisingCallback = wrapper;
534 return true;
535 } catch (RemoteException e) {
536 Log.e(TAG, "", e);
537 return false;
538 }
539 }
540
541 /**
542 * Stop BLE advertising.
543 * An app should stop advertising by requesting
544 * {@link BluetoothAdapter#ACTION_STOP_ADVERTISING} instead of calling this method directly.
545 * <p>Requires {@link android.Manifest.permission#BLUETOOTH_PRIVILEGED}
546 * @return true if BLE advertising stops, false otherwise.
547 * @hide
548 */
549 public boolean stopAdvertisting() {
550 try {
551 IBluetoothGatt iGatt = mManagerService.getBluetoothGatt();
552 if (iGatt == null) {
553 // BLE is not supported
554 return false;
555 }
556 if (mAdvertisingCallback == null) {
557 // no callback.
558 return false;
559 }
560 mAdvertisingCallback.stopAdvertising();
561 mAdvertisingCallback = null;
562 return true;
563 } catch (RemoteException e) {
564 Log.e(TAG, "", e);
565 return false;
566 }
567 }
568
569 /**
Nick Pellyde893f52009-09-08 13:15:33 -0700570 * Return true if Bluetooth is currently enabled and ready for use.
571 * <p>Equivalent to:
572 * <code>getBluetoothState() == STATE_ON</code>
573 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
Nick Pellybd022f42009-08-14 18:33:38 -0700574 *
Nick Pellyde893f52009-09-08 13:15:33 -0700575 * @return true if the local adapter is turned on
Nick Pellybd022f42009-08-14 18:33:38 -0700576 */
577 public boolean isEnabled() {
fredc0f420372012-04-12 00:02:00 -0700578
Nick Pellybd022f42009-08-14 18:33:38 -0700579 try {
fredc0f420372012-04-12 00:02:00 -0700580 synchronized(mManagerCallback) {
581 if (mService != null) return mService.isEnabled();
582 }
Nick Pellybd022f42009-08-14 18:33:38 -0700583 } catch (RemoteException e) {Log.e(TAG, "", e);}
584 return false;
585 }
586
587 /**
Nick Pellyde893f52009-09-08 13:15:33 -0700588 * Get the current state of the local Bluetooth adapter.
589 * <p>Possible return values are
590 * {@link #STATE_OFF},
591 * {@link #STATE_TURNING_ON},
592 * {@link #STATE_ON},
593 * {@link #STATE_TURNING_OFF}.
594 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
Nick Pellybd022f42009-08-14 18:33:38 -0700595 *
Nick Pellyde893f52009-09-08 13:15:33 -0700596 * @return current state of Bluetooth adapter
Nick Pellybd022f42009-08-14 18:33:38 -0700597 */
Nick Pellyde893f52009-09-08 13:15:33 -0700598 public int getState() {
Nick Pellybd022f42009-08-14 18:33:38 -0700599 try {
fredc0f420372012-04-12 00:02:00 -0700600 synchronized(mManagerCallback) {
601 if (mService != null)
602 {
fredcbf072a72012-05-09 16:52:50 -0700603 int state= mService.getState();
Matthew Xie3b6214f2012-08-29 00:12:29 -0700604 if (VDBG) Log.d(TAG, "" + hashCode() + ": getState(). Returning " + state);
fredcbf072a72012-05-09 16:52:50 -0700605 return state;
fredc0f420372012-04-12 00:02:00 -0700606 }
607 // TODO(BT) there might be a small gap during STATE_TURNING_ON that
608 // mService is null, handle that case
609 }
Nick Pellybd022f42009-08-14 18:33:38 -0700610 } catch (RemoteException e) {Log.e(TAG, "", e);}
fredcbf072a72012-05-09 16:52:50 -0700611 if (DBG) Log.d(TAG, "" + hashCode() + ": getState() : mService = null. Returning STATE_OFF");
Nick Pellyde893f52009-09-08 13:15:33 -0700612 return STATE_OFF;
Nick Pellybd022f42009-08-14 18:33:38 -0700613 }
614
615 /**
Scott Mained2a70d2009-12-09 16:07:39 -0800616 * Turn on the local Bluetooth adapter&mdash;do not use without explicit
617 * user action to turn on Bluetooth.
Nick Pellyde893f52009-09-08 13:15:33 -0700618 * <p>This powers on the underlying Bluetooth hardware, and starts all
619 * Bluetooth system services.
Scott Mained2a70d2009-12-09 16:07:39 -0800620 * <p class="caution"><strong>Bluetooth should never be enabled without
621 * direct user consent</strong>. If you want to turn on Bluetooth in order
622 * to create a wireless connection, you should use the {@link
623 * #ACTION_REQUEST_ENABLE} Intent, which will raise a dialog that requests
624 * user permission to turn on Bluetooth. The {@link #enable()} method is
625 * provided only for applications that include a user interface for changing
626 * system settings, such as a "power manager" app.</p>
Brad Fitzpatrick3219ab42009-09-25 16:31:39 +0400627 * <p>This is an asynchronous call: it will return immediately, and
Nick Pellyde893f52009-09-08 13:15:33 -0700628 * clients should listen for {@link #ACTION_STATE_CHANGED}
629 * to be notified of subsequent adapter state changes. If this call returns
630 * true, then the adapter state will immediately transition from {@link
631 * #STATE_OFF} to {@link #STATE_TURNING_ON}, and some time
632 * later transition to either {@link #STATE_OFF} or {@link
633 * #STATE_ON}. If this call returns false then there was an
634 * immediate problem that will prevent the adapter from being turned on -
635 * such as Airplane mode, or the adapter is already turned on.
Scott Mained2a70d2009-12-09 16:07:39 -0800636 * <p>Requires the {@link android.Manifest.permission#BLUETOOTH_ADMIN}
637 * permission
Nick Pellyde893f52009-09-08 13:15:33 -0700638 *
639 * @return true to indicate adapter startup has begun, or false on
640 * immediate error
Nick Pellybd022f42009-08-14 18:33:38 -0700641 */
642 public boolean enable() {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700643 if (isEnabled() == true){
644 if (DBG) Log.d(TAG, "enable(): BT is already enabled..!");
645 return true;
646 }
Nick Pellybd022f42009-08-14 18:33:38 -0700647 try {
Kausik Sinnaswamya097f512012-04-16 16:38:27 +0530648 return mManagerService.enable();
Nick Pellybd022f42009-08-14 18:33:38 -0700649 } catch (RemoteException e) {Log.e(TAG, "", e);}
650 return false;
651 }
652
653 /**
Scott Mained2a70d2009-12-09 16:07:39 -0800654 * Turn off the local Bluetooth adapter&mdash;do not use without explicit
655 * user action to turn off Bluetooth.
Nick Pellyde893f52009-09-08 13:15:33 -0700656 * <p>This gracefully shuts down all Bluetooth connections, stops Bluetooth
657 * system services, and powers down the underlying Bluetooth hardware.
Jake Hambyf51eada2010-09-21 13:39:53 -0700658 * <p class="caution"><strong>Bluetooth should never be disabled without
Scott Mained2a70d2009-12-09 16:07:39 -0800659 * direct user consent</strong>. The {@link #disable()} method is
660 * provided only for applications that include a user interface for changing
661 * system settings, such as a "power manager" app.</p>
Brad Fitzpatrick3219ab42009-09-25 16:31:39 +0400662 * <p>This is an asynchronous call: it will return immediately, and
Nick Pellyde893f52009-09-08 13:15:33 -0700663 * clients should listen for {@link #ACTION_STATE_CHANGED}
664 * to be notified of subsequent adapter state changes. If this call returns
665 * true, then the adapter state will immediately transition from {@link
666 * #STATE_ON} to {@link #STATE_TURNING_OFF}, and some time
667 * later transition to either {@link #STATE_OFF} or {@link
668 * #STATE_ON}. If this call returns false then there was an
669 * immediate problem that will prevent the adapter from being turned off -
670 * such as the adapter already being turned off.
Scott Mained2a70d2009-12-09 16:07:39 -0800671 * <p>Requires the {@link android.Manifest.permission#BLUETOOTH_ADMIN}
672 * permission
Nick Pellybd022f42009-08-14 18:33:38 -0700673 *
Nick Pellyde893f52009-09-08 13:15:33 -0700674 * @return true to indicate adapter shutdown has begun, or false on
675 * immediate error
Nick Pellybd022f42009-08-14 18:33:38 -0700676 */
677 public boolean disable() {
678 try {
fredc0f420372012-04-12 00:02:00 -0700679 return mManagerService.disable(true);
Jaikumar Ganeshe21a4ac2012-03-06 17:15:16 -0800680 } catch (RemoteException e) {Log.e(TAG, "", e);}
681 return false;
682 }
683
684 /**
685 * Turn off the local Bluetooth adapter and don't persist the setting.
686 *
687 * <p>Requires the {@link android.Manifest.permission#BLUETOOTH_ADMIN}
688 * permission
689 *
690 * @return true to indicate adapter shutdown has begun, or false on
691 * immediate error
692 * @hide
693 */
694 public boolean disable(boolean persist) {
fredc0f420372012-04-12 00:02:00 -0700695
Jaikumar Ganeshe21a4ac2012-03-06 17:15:16 -0800696 try {
fredc0f420372012-04-12 00:02:00 -0700697 return mManagerService.disable(persist);
Nick Pellybd022f42009-08-14 18:33:38 -0700698 } catch (RemoteException e) {Log.e(TAG, "", e);}
699 return false;
700 }
701
Nick Pellyde893f52009-09-08 13:15:33 -0700702 /**
703 * Returns the hardware address of the local Bluetooth adapter.
704 * <p>For example, "00:11:22:AA:BB:CC".
705 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
706 *
707 * @return Bluetooth hardware address as string
708 */
Nick Pellybd022f42009-08-14 18:33:38 -0700709 public String getAddress() {
710 try {
fredc0f420372012-04-12 00:02:00 -0700711 return mManagerService.getAddress();
Nick Pellybd022f42009-08-14 18:33:38 -0700712 } catch (RemoteException e) {Log.e(TAG, "", e);}
713 return null;
714 }
715
716 /**
Nick Pellyde893f52009-09-08 13:15:33 -0700717 * Get the friendly Bluetooth name of the local Bluetooth adapter.
718 * <p>This name is visible to remote Bluetooth devices.
719 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
Nick Pellybd022f42009-08-14 18:33:38 -0700720 *
Nick Pellyde893f52009-09-08 13:15:33 -0700721 * @return the Bluetooth name, or null on error
Nick Pellybd022f42009-08-14 18:33:38 -0700722 */
723 public String getName() {
724 try {
fredc116d1d462012-04-20 14:47:08 -0700725 return mManagerService.getName();
Nick Pellybd022f42009-08-14 18:33:38 -0700726 } catch (RemoteException e) {Log.e(TAG, "", e);}
727 return null;
728 }
729
730 /**
Zhihai Xuaf5971e2013-06-10 20:28:31 -0700731 * enable or disable Bluetooth HCI snoop log.
732 *
733 * <p>Requires the {@link android.Manifest.permission#BLUETOOTH_ADMIN}
734 * permission
735 *
736 * @return true to indicate configure HCI log successfully, or false on
737 * immediate error
738 * @hide
739 */
740 public boolean configHciSnoopLog(boolean enable) {
741 try {
742 synchronized(mManagerCallback) {
743 if (mService != null) return mService.configHciSnoopLog(enable);
744 }
745 } catch (RemoteException e) {Log.e(TAG, "", e);}
746 return false;
747 }
748
749 /**
Jaikumar Ganesh58b93c32010-11-23 20:03:10 -0800750 * Get the UUIDs supported by the local Bluetooth adapter.
751 *
752 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
753 *
754 * @return the UUIDs supported by the local Bluetooth Adapter.
755 * @hide
756 */
757 public ParcelUuid[] getUuids() {
Matthew Xie44b58ab2011-11-16 12:27:57 -0800758 if (getState() != STATE_ON) return null;
Jaikumar Ganesh58b93c32010-11-23 20:03:10 -0800759 try {
fredc0f420372012-04-12 00:02:00 -0700760 synchronized(mManagerCallback) {
761 if (mService != null) return mService.getUuids();
762 }
Jaikumar Ganesh58b93c32010-11-23 20:03:10 -0800763 } catch (RemoteException e) {Log.e(TAG, "", e);}
764 return null;
765 }
766
767 /**
Jake Hamby0f584302010-09-16 18:12:51 -0700768 * Set the friendly Bluetooth name of the local Bluetooth adapter.
Nick Pellyde893f52009-09-08 13:15:33 -0700769 * <p>This name is visible to remote Bluetooth devices.
Jake Hamby0f584302010-09-16 18:12:51 -0700770 * <p>Valid Bluetooth names are a maximum of 248 bytes using UTF-8
771 * encoding, although many remote devices can only display the first
772 * 40 characters, and some may be limited to just 20.
Jaikumar Ganeshfec86f42010-08-09 16:54:03 -0700773 * <p>If Bluetooth state is not {@link #STATE_ON}, this API
774 * will return false. After turning on Bluetooth,
775 * wait for {@link #ACTION_STATE_CHANGED} with {@link #STATE_ON}
776 * to get the updated value.
Nick Pellyde893f52009-09-08 13:15:33 -0700777 * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN}
Nick Pellybd022f42009-08-14 18:33:38 -0700778 *
Nick Pellyde893f52009-09-08 13:15:33 -0700779 * @param name a valid Bluetooth name
780 * @return true if the name was set, false otherwise
Nick Pellybd022f42009-08-14 18:33:38 -0700781 */
782 public boolean setName(String name) {
Jaikumar Ganeshf5ff1702010-08-06 19:03:13 -0700783 if (getState() != STATE_ON) return false;
Nick Pellybd022f42009-08-14 18:33:38 -0700784 try {
fredc0f420372012-04-12 00:02:00 -0700785 synchronized(mManagerCallback) {
786 if (mService != null) return mService.setName(name);
787 }
Nick Pellybd022f42009-08-14 18:33:38 -0700788 } catch (RemoteException e) {Log.e(TAG, "", e);}
789 return false;
790 }
791
792 /**
Jake Hamby0f584302010-09-16 18:12:51 -0700793 * Get the current Bluetooth scan mode of the local Bluetooth adapter.
Nick Pellyde893f52009-09-08 13:15:33 -0700794 * <p>The Bluetooth scan mode determines if the local adapter is
795 * connectable and/or discoverable from remote Bluetooth devices.
796 * <p>Possible values are:
797 * {@link #SCAN_MODE_NONE},
798 * {@link #SCAN_MODE_CONNECTABLE},
799 * {@link #SCAN_MODE_CONNECTABLE_DISCOVERABLE}.
Jaikumar Ganeshfec86f42010-08-09 16:54:03 -0700800 * <p>If Bluetooth state is not {@link #STATE_ON}, this API
801 * will return {@link #SCAN_MODE_NONE}. After turning on Bluetooth,
802 * wait for {@link #ACTION_STATE_CHANGED} with {@link #STATE_ON}
803 * to get the updated value.
Nick Pellyde893f52009-09-08 13:15:33 -0700804 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
805 *
806 * @return scan mode
Nick Pellybd022f42009-08-14 18:33:38 -0700807 */
808 public int getScanMode() {
Jaikumar Ganeshf5ff1702010-08-06 19:03:13 -0700809 if (getState() != STATE_ON) return SCAN_MODE_NONE;
Nick Pellybd022f42009-08-14 18:33:38 -0700810 try {
fredc0f420372012-04-12 00:02:00 -0700811 synchronized(mManagerCallback) {
812 if (mService != null) return mService.getScanMode();
813 }
Nick Pellybd022f42009-08-14 18:33:38 -0700814 } catch (RemoteException e) {Log.e(TAG, "", e);}
Nick Pellyde893f52009-09-08 13:15:33 -0700815 return SCAN_MODE_NONE;
Nick Pellybd022f42009-08-14 18:33:38 -0700816 }
817
818 /**
Nick Pellyde893f52009-09-08 13:15:33 -0700819 * Set the Bluetooth scan mode of the local Bluetooth adapter.
820 * <p>The Bluetooth scan mode determines if the local adapter is
821 * connectable and/or discoverable from remote Bluetooth devices.
Nick Pelly12835472009-09-25 15:00:29 -0700822 * <p>For privacy reasons, discoverable mode is automatically turned off
823 * after <code>duration</code> seconds. For example, 120 seconds should be
824 * enough for a remote device to initiate and complete its discovery
825 * process.
Nick Pellyde893f52009-09-08 13:15:33 -0700826 * <p>Valid scan mode values are:
827 * {@link #SCAN_MODE_NONE},
828 * {@link #SCAN_MODE_CONNECTABLE},
829 * {@link #SCAN_MODE_CONNECTABLE_DISCOVERABLE}.
Jaikumar Ganeshfec86f42010-08-09 16:54:03 -0700830 * <p>If Bluetooth state is not {@link #STATE_ON}, this API
831 * will return false. After turning on Bluetooth,
832 * wait for {@link #ACTION_STATE_CHANGED} with {@link #STATE_ON}
833 * to get the updated value.
Nick Pelly18b1e792009-09-24 11:14:15 -0700834 * <p>Requires {@link android.Manifest.permission#WRITE_SECURE_SETTINGS}
835 * <p>Applications cannot set the scan mode. They should use
836 * <code>startActivityForResult(
837 * BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE})
838 * </code>instead.
Nick Pellyde893f52009-09-08 13:15:33 -0700839 *
840 * @param mode valid scan mode
Nick Pelly12835472009-09-25 15:00:29 -0700841 * @param duration time in seconds to apply scan mode, only used for
842 * {@link #SCAN_MODE_CONNECTABLE_DISCOVERABLE}
Nick Pellyde893f52009-09-08 13:15:33 -0700843 * @return true if the scan mode was set, false otherwise
Nick Pelly18b1e792009-09-24 11:14:15 -0700844 * @hide
Nick Pellybd022f42009-08-14 18:33:38 -0700845 */
Nick Pelly12835472009-09-25 15:00:29 -0700846 public boolean setScanMode(int mode, int duration) {
Jaikumar Ganeshf5ff1702010-08-06 19:03:13 -0700847 if (getState() != STATE_ON) return false;
Nick Pellybd022f42009-08-14 18:33:38 -0700848 try {
fredc0f420372012-04-12 00:02:00 -0700849 synchronized(mManagerCallback) {
850 if (mService != null) return mService.setScanMode(mode, duration);
851 }
Nick Pellybd022f42009-08-14 18:33:38 -0700852 } catch (RemoteException e) {Log.e(TAG, "", e);}
Nick Pellyde893f52009-09-08 13:15:33 -0700853 return false;
Nick Pellybd022f42009-08-14 18:33:38 -0700854 }
855
Nick Pelly45e27042009-08-19 11:00:00 -0700856 /** @hide */
Nick Pelly12835472009-09-25 15:00:29 -0700857 public boolean setScanMode(int mode) {
Jaikumar Ganeshf5ff1702010-08-06 19:03:13 -0700858 if (getState() != STATE_ON) return false;
Srikanth Uppala827de2d2012-04-04 03:33:26 -0700859 /* getDiscoverableTimeout() to use the latest from NV than use 0 */
860 return setScanMode(mode, getDiscoverableTimeout());
Nick Pelly12835472009-09-25 15:00:29 -0700861 }
862
863 /** @hide */
Nick Pellybd022f42009-08-14 18:33:38 -0700864 public int getDiscoverableTimeout() {
Jaikumar Ganeshf5ff1702010-08-06 19:03:13 -0700865 if (getState() != STATE_ON) return -1;
Nick Pellybd022f42009-08-14 18:33:38 -0700866 try {
fredc0f420372012-04-12 00:02:00 -0700867 synchronized(mManagerCallback) {
868 if (mService != null) return mService.getDiscoverableTimeout();
869 }
Nick Pellybd022f42009-08-14 18:33:38 -0700870 } catch (RemoteException e) {Log.e(TAG, "", e);}
871 return -1;
872 }
873
Nick Pelly45e27042009-08-19 11:00:00 -0700874 /** @hide */
Nick Pellybd022f42009-08-14 18:33:38 -0700875 public void setDiscoverableTimeout(int timeout) {
Jaikumar Ganeshf5ff1702010-08-06 19:03:13 -0700876 if (getState() != STATE_ON) return;
Nick Pellybd022f42009-08-14 18:33:38 -0700877 try {
fredc0f420372012-04-12 00:02:00 -0700878 synchronized(mManagerCallback) {
879 if (mService != null) mService.setDiscoverableTimeout(timeout);
880 }
Nick Pellybd022f42009-08-14 18:33:38 -0700881 } catch (RemoteException e) {Log.e(TAG, "", e);}
882 }
883
Nick Pelly005b2282009-09-10 10:21:56 -0700884 /**
885 * Start the remote device discovery process.
886 * <p>The discovery process usually involves an inquiry scan of about 12
887 * seconds, followed by a page scan of each new device to retrieve its
888 * Bluetooth name.
889 * <p>This is an asynchronous call, it will return immediately. Register
890 * for {@link #ACTION_DISCOVERY_STARTED} and {@link
891 * #ACTION_DISCOVERY_FINISHED} intents to determine exactly when the
892 * discovery starts and completes. Register for {@link
893 * BluetoothDevice#ACTION_FOUND} to be notified as remote Bluetooth devices
894 * are found.
895 * <p>Device discovery is a heavyweight procedure. New connections to
896 * remote Bluetooth devices should not be attempted while discovery is in
897 * progress, and existing connections will experience limited bandwidth
898 * and high latency. Use {@link #cancelDiscovery()} to cancel an ongoing
Scott Main6d95fc02009-11-19 17:00:19 -0800899 * discovery. Discovery is not managed by the Activity,
900 * but is run as a system service, so an application should always call
901 * {@link BluetoothAdapter#cancelDiscovery()} even if it
902 * did not directly request a discovery, just to be sure.
Nick Pelly005b2282009-09-10 10:21:56 -0700903 * <p>Device discovery will only find remote devices that are currently
904 * <i>discoverable</i> (inquiry scan enabled). Many Bluetooth devices are
905 * not discoverable by default, and need to be entered into a special mode.
Jaikumar Ganeshfec86f42010-08-09 16:54:03 -0700906 * <p>If Bluetooth state is not {@link #STATE_ON}, this API
907 * will return false. After turning on Bluetooth,
908 * wait for {@link #ACTION_STATE_CHANGED} with {@link #STATE_ON}
909 * to get the updated value.
Nick Pelly005b2282009-09-10 10:21:56 -0700910 * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN}.
911 *
912 * @return true on success, false on error
913 */
Nick Pellybd022f42009-08-14 18:33:38 -0700914 public boolean startDiscovery() {
Jaikumar Ganeshf5ff1702010-08-06 19:03:13 -0700915 if (getState() != STATE_ON) return false;
Nick Pellybd022f42009-08-14 18:33:38 -0700916 try {
fredc0f420372012-04-12 00:02:00 -0700917 synchronized(mManagerCallback) {
918 if (mService != null) return mService.startDiscovery();
919 }
Nick Pellybd022f42009-08-14 18:33:38 -0700920 } catch (RemoteException e) {Log.e(TAG, "", e);}
921 return false;
922 }
923
Nick Pelly005b2282009-09-10 10:21:56 -0700924 /**
925 * Cancel the current device discovery process.
926 * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN}.
Jake Hamby0f584302010-09-16 18:12:51 -0700927 * <p>Because discovery is a heavyweight procedure for the Bluetooth
Scott Main6d95fc02009-11-19 17:00:19 -0800928 * adapter, this method should always be called before attempting to connect
929 * to a remote device with {@link
930 * android.bluetooth.BluetoothSocket#connect()}. Discovery is not managed by
931 * the Activity, but is run as a system service, so an application should
932 * always call cancel discovery even if it did not directly request a
933 * discovery, just to be sure.
Jaikumar Ganeshfec86f42010-08-09 16:54:03 -0700934 * <p>If Bluetooth state is not {@link #STATE_ON}, this API
935 * will return false. After turning on Bluetooth,
936 * wait for {@link #ACTION_STATE_CHANGED} with {@link #STATE_ON}
937 * to get the updated value.
Nick Pelly005b2282009-09-10 10:21:56 -0700938 *
939 * @return true on success, false on error
940 */
941 public boolean cancelDiscovery() {
Jaikumar Ganeshf5ff1702010-08-06 19:03:13 -0700942 if (getState() != STATE_ON) return false;
Nick Pellybd022f42009-08-14 18:33:38 -0700943 try {
fredc0f420372012-04-12 00:02:00 -0700944 synchronized(mManagerCallback) {
945 if (mService != null) return mService.cancelDiscovery();
946 }
Nick Pellybd022f42009-08-14 18:33:38 -0700947 } catch (RemoteException e) {Log.e(TAG, "", e);}
Nick Pelly005b2282009-09-10 10:21:56 -0700948 return false;
Nick Pellybd022f42009-08-14 18:33:38 -0700949 }
950
Nick Pelly005b2282009-09-10 10:21:56 -0700951 /**
952 * Return true if the local Bluetooth adapter is currently in the device
953 * discovery process.
954 * <p>Device discovery is a heavyweight procedure. New connections to
955 * remote Bluetooth devices should not be attempted while discovery is in
956 * progress, and existing connections will experience limited bandwidth
957 * and high latency. Use {@link #cancelDiscovery()} to cancel an ongoing
958 * discovery.
959 * <p>Applications can also register for {@link #ACTION_DISCOVERY_STARTED}
960 * or {@link #ACTION_DISCOVERY_FINISHED} to be notified when discovery
961 * starts or completes.
Jaikumar Ganeshfec86f42010-08-09 16:54:03 -0700962 * <p>If Bluetooth state is not {@link #STATE_ON}, this API
963 * will return false. After turning on Bluetooth,
964 * wait for {@link #ACTION_STATE_CHANGED} with {@link #STATE_ON}
965 * to get the updated value.
Nick Pellye6ee3be2009-10-08 23:27:28 +0200966 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}.
Nick Pelly005b2282009-09-10 10:21:56 -0700967 *
968 * @return true if discovering
969 */
Nick Pellybd022f42009-08-14 18:33:38 -0700970 public boolean isDiscovering() {
Jaikumar Ganeshf5ff1702010-08-06 19:03:13 -0700971 if (getState() != STATE_ON) return false;
Nick Pellybd022f42009-08-14 18:33:38 -0700972 try {
fredc0f420372012-04-12 00:02:00 -0700973 synchronized(mManagerCallback) {
974 if (mService != null ) return mService.isDiscovering();
975 }
Nick Pellybd022f42009-08-14 18:33:38 -0700976 } catch (RemoteException e) {Log.e(TAG, "", e);}
977 return false;
978 }
979
980 /**
Wei Wang86b3fa62013-10-29 21:05:37 -0700981 * Returns whether BLE is currently advertising.
982 * <p>Requires {@link android.Manifest.permission#BLUETOOTH_PRIVILEGED}.
983 *
984 * @hide
985 */
986 public boolean isAdvertising() {
987 if (getState() != STATE_ON) return false;
988 try {
989 IBluetoothGatt iGatt = mManagerService.getBluetoothGatt();
990 return iGatt.isAdvertising();
991 } catch (RemoteException e) {
992 Log.e(TAG, "", e);
993 }
994 return false;
995 }
996
997 /**
Nick Pelly005b2282009-09-10 10:21:56 -0700998 * Return the set of {@link BluetoothDevice} objects that are bonded
999 * (paired) to the local adapter.
Jaikumar Ganeshfec86f42010-08-09 16:54:03 -07001000 * <p>If Bluetooth state is not {@link #STATE_ON}, this API
1001 * will return an empty set. After turning on Bluetooth,
1002 * wait for {@link #ACTION_STATE_CHANGED} with {@link #STATE_ON}
1003 * to get the updated value.
Nick Pellye6ee3be2009-10-08 23:27:28 +02001004 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}.
Nick Pellybd022f42009-08-14 18:33:38 -07001005 *
Nick Pelly005b2282009-09-10 10:21:56 -07001006 * @return unmodifiable set of {@link BluetoothDevice}, or null on error
Nick Pellybd022f42009-08-14 18:33:38 -07001007 */
1008 public Set<BluetoothDevice> getBondedDevices() {
Jaikumar Ganeshfec86f42010-08-09 16:54:03 -07001009 if (getState() != STATE_ON) {
Jaikumar Ganeshe4caddb2012-01-25 16:16:48 -08001010 return toDeviceSet(new BluetoothDevice[0]);
Jaikumar Ganeshfec86f42010-08-09 16:54:03 -07001011 }
Nick Pellybd022f42009-08-14 18:33:38 -07001012 try {
fredc0f420372012-04-12 00:02:00 -07001013 synchronized(mManagerCallback) {
1014 if (mService != null) return toDeviceSet(mService.getBondedDevices());
1015 }
1016 return toDeviceSet(new BluetoothDevice[0]);
Nick Pellybd022f42009-08-14 18:33:38 -07001017 } catch (RemoteException e) {Log.e(TAG, "", e);}
1018 return null;
1019 }
1020
1021 /**
Jaikumar Ganeshc53cab22010-10-26 16:02:26 -07001022 * Get the current connection state of the local Bluetooth adapter.
1023 * This can be used to check whether the local Bluetooth adapter is connected
1024 * to any profile of any other remote Bluetooth Device.
1025 *
1026 * <p> Use this function along with {@link #ACTION_CONNECTION_STATE_CHANGED}
1027 * intent to get the connection state of the adapter.
1028 *
1029 * @return One of {@link #STATE_CONNECTED}, {@link #STATE_DISCONNECTED},
1030 * {@link #STATE_CONNECTING} or {@link #STATE_DISCONNECTED}
1031 *
1032 * @hide
1033 */
1034 public int getConnectionState() {
1035 if (getState() != STATE_ON) return BluetoothAdapter.STATE_DISCONNECTED;
1036 try {
fredc0f420372012-04-12 00:02:00 -07001037 synchronized(mManagerCallback) {
1038 if (mService != null) return mService.getAdapterConnectionState();
1039 }
Jaikumar Ganeshc53cab22010-10-26 16:02:26 -07001040 } catch (RemoteException e) {Log.e(TAG, "getConnectionState:", e);}
1041 return BluetoothAdapter.STATE_DISCONNECTED;
1042 }
1043
1044 /**
Jaikumar Ganeshcb1d3542011-08-19 10:26:32 -07001045 * Get the current connection state of a profile.
1046 * This function can be used to check whether the local Bluetooth adapter
1047 * is connected to any remote device for a specific profile.
Scott Main2d68a6b2011-09-26 22:59:38 -07001048 * Profile can be one of {@link BluetoothProfile#HEALTH}, {@link BluetoothProfile#HEADSET},
Jaikumar Ganesh93547902011-08-23 12:21:55 -07001049 * {@link BluetoothProfile#A2DP}.
Jaikumar Ganeshcb1d3542011-08-19 10:26:32 -07001050 *
1051 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}.
1052 *
1053 * <p> Return value can be one of
Jaikumar Ganesh93547902011-08-23 12:21:55 -07001054 * {@link BluetoothProfile#STATE_DISCONNECTED},
1055 * {@link BluetoothProfile#STATE_CONNECTING},
1056 * {@link BluetoothProfile#STATE_CONNECTED},
1057 * {@link BluetoothProfile#STATE_DISCONNECTING}
Jaikumar Ganeshcb1d3542011-08-19 10:26:32 -07001058 */
1059 public int getProfileConnectionState(int profile) {
1060 if (getState() != STATE_ON) return BluetoothProfile.STATE_DISCONNECTED;
1061 try {
fredc0f420372012-04-12 00:02:00 -07001062 synchronized(mManagerCallback) {
1063 if (mService != null) return mService.getProfileConnectionState(profile);
1064 }
Jaikumar Ganesh93547902011-08-23 12:21:55 -07001065 } catch (RemoteException e) {
1066 Log.e(TAG, "getProfileConnectionState:", e);
1067 }
Jaikumar Ganeshcb1d3542011-08-19 10:26:32 -07001068 return BluetoothProfile.STATE_DISCONNECTED;
1069 }
1070
1071 /**
Nick Pelly45e27042009-08-19 11:00:00 -07001072 * Create a listening, secure RFCOMM Bluetooth socket.
1073 * <p>A remote device connecting to this socket will be authenticated and
Nick Pellybd022f42009-08-14 18:33:38 -07001074 * communication on this socket will be encrypted.
Nick Pelly45e27042009-08-19 11:00:00 -07001075 * <p>Use {@link BluetoothServerSocket#accept} to retrieve incoming
Nick Pelly24bb9b82009-10-02 20:34:18 -07001076 * connections from a listening {@link BluetoothServerSocket}.
Nick Pelly45e27042009-08-19 11:00:00 -07001077 * <p>Valid RFCOMM channels are in range 1 to 30.
Nick Pelly24bb9b82009-10-02 20:34:18 -07001078 * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN}
Nick Pelly45e27042009-08-19 11:00:00 -07001079 * @param channel RFCOMM channel to listen on
1080 * @return a listening RFCOMM BluetoothServerSocket
1081 * @throws IOException on error, for example Bluetooth not available, or
1082 * insufficient permissions, or channel in use.
Nick Pelly24bb9b82009-10-02 20:34:18 -07001083 * @hide
Nick Pellybd022f42009-08-14 18:33:38 -07001084 */
Nick Pelly45e27042009-08-19 11:00:00 -07001085 public BluetoothServerSocket listenUsingRfcommOn(int channel) throws IOException {
Nick Pellybd022f42009-08-14 18:33:38 -07001086 BluetoothServerSocket socket = new BluetoothServerSocket(
Nick Pelly45e27042009-08-19 11:00:00 -07001087 BluetoothSocket.TYPE_RFCOMM, true, true, channel);
Nick Pelly24bb9b82009-10-02 20:34:18 -07001088 int errno = socket.mSocket.bindListen();
1089 if (errno != 0) {
zzy3b147b72012-04-03 19:48:32 -07001090 //TODO(BT): Throw the same exception error code
1091 // that the previous code was using.
1092 //socket.mSocket.throwErrnoNative(errno);
1093 throw new IOException("Error: " + errno);
Nick Pellybd022f42009-08-14 18:33:38 -07001094 }
1095 return socket;
1096 }
1097
1098 /**
Nick Pelly24bb9b82009-10-02 20:34:18 -07001099 * Create a listening, secure RFCOMM Bluetooth socket with Service Record.
1100 * <p>A remote device connecting to this socket will be authenticated and
1101 * communication on this socket will be encrypted.
1102 * <p>Use {@link BluetoothServerSocket#accept} to retrieve incoming
1103 * connections from a listening {@link BluetoothServerSocket}.
1104 * <p>The system will assign an unused RFCOMM channel to listen on.
1105 * <p>The system will also register a Service Discovery
1106 * Protocol (SDP) record with the local SDP server containing the specified
1107 * UUID, service name, and auto-assigned channel. Remote Bluetooth devices
1108 * can use the same UUID to query our SDP server and discover which channel
1109 * to connect to. This SDP record will be removed when this socket is
1110 * closed, or if this application closes unexpectedly.
Nick Pelly16fb88a2009-10-07 07:44:03 +02001111 * <p>Use {@link BluetoothDevice#createRfcommSocketToServiceRecord} to
1112 * connect to this socket from another device using the same {@link UUID}.
Nick Pelly24bb9b82009-10-02 20:34:18 -07001113 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
1114 * @param name service name for SDP record
1115 * @param uuid uuid for SDP record
1116 * @return a listening RFCOMM BluetoothServerSocket
1117 * @throws IOException on error, for example Bluetooth not available, or
1118 * insufficient permissions, or channel in use.
1119 */
Nick Pelly16fb88a2009-10-07 07:44:03 +02001120 public BluetoothServerSocket listenUsingRfcommWithServiceRecord(String name, UUID uuid)
Nick Pelly24bb9b82009-10-02 20:34:18 -07001121 throws IOException {
Jaikumar Ganesh6eef14a2010-12-23 12:57:02 -08001122 return createNewRfcommSocketAndRecord(name, uuid, true, true);
1123 }
1124
1125 /**
1126 * Create a listening, insecure RFCOMM Bluetooth socket with Service Record.
Mathias Jeppssone3b9dc102011-03-21 15:06:52 +01001127 * <p>The link key is not required to be authenticated, i.e the communication may be
Jaikumar Ganesh6eef14a2010-12-23 12:57:02 -08001128 * vulnerable to Man In the Middle attacks. For Bluetooth 2.1 devices,
Mathias Jeppssone3b9dc102011-03-21 15:06:52 +01001129 * the link will be encrypted, as encryption is mandartory.
1130 * For legacy devices (pre Bluetooth 2.1 devices) the link will not
Jaikumar Ganesh6eef14a2010-12-23 12:57:02 -08001131 * be encrypted. Use {@link #listenUsingRfcommWithServiceRecord}, if an
1132 * encrypted and authenticated communication channel is desired.
1133 * <p>Use {@link BluetoothServerSocket#accept} to retrieve incoming
1134 * connections from a listening {@link BluetoothServerSocket}.
1135 * <p>The system will assign an unused RFCOMM channel to listen on.
1136 * <p>The system will also register a Service Discovery
1137 * Protocol (SDP) record with the local SDP server containing the specified
1138 * UUID, service name, and auto-assigned channel. Remote Bluetooth devices
1139 * can use the same UUID to query our SDP server and discover which channel
1140 * to connect to. This SDP record will be removed when this socket is
1141 * closed, or if this application closes unexpectedly.
1142 * <p>Use {@link BluetoothDevice#createRfcommSocketToServiceRecord} to
1143 * connect to this socket from another device using the same {@link UUID}.
1144 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
1145 * @param name service name for SDP record
1146 * @param uuid uuid for SDP record
1147 * @return a listening RFCOMM BluetoothServerSocket
1148 * @throws IOException on error, for example Bluetooth not available, or
1149 * insufficient permissions, or channel in use.
1150 */
1151 public BluetoothServerSocket listenUsingInsecureRfcommWithServiceRecord(String name, UUID uuid)
1152 throws IOException {
1153 return createNewRfcommSocketAndRecord(name, uuid, false, false);
1154 }
1155
Mathias Jeppssone3b9dc102011-03-21 15:06:52 +01001156 /**
1157 * Create a listening, encrypted,
1158 * RFCOMM Bluetooth socket with Service Record.
1159 * <p>The link will be encrypted, but the link key is not required to be authenticated
1160 * i.e the communication is vulnerable to Man In the Middle attacks. Use
1161 * {@link #listenUsingRfcommWithServiceRecord}, to ensure an authenticated link key.
1162 * <p> Use this socket if authentication of link key is not possible.
1163 * For example, for Bluetooth 2.1 devices, if any of the devices does not have
1164 * an input and output capability or just has the ability to display a numeric key,
1165 * a secure socket connection is not possible and this socket can be used.
1166 * Use {@link #listenUsingInsecureRfcommWithServiceRecord}, if encryption is not required.
1167 * For Bluetooth 2.1 devices, the link will be encrypted, as encryption is mandartory.
1168 * For more details, refer to the Security Model section 5.2 (vol 3) of
1169 * Bluetooth Core Specification version 2.1 + EDR.
1170 * <p>Use {@link BluetoothServerSocket#accept} to retrieve incoming
1171 * connections from a listening {@link BluetoothServerSocket}.
1172 * <p>The system will assign an unused RFCOMM channel to listen on.
1173 * <p>The system will also register a Service Discovery
1174 * Protocol (SDP) record with the local SDP server containing the specified
1175 * UUID, service name, and auto-assigned channel. Remote Bluetooth devices
1176 * can use the same UUID to query our SDP server and discover which channel
1177 * to connect to. This SDP record will be removed when this socket is
1178 * closed, or if this application closes unexpectedly.
1179 * <p>Use {@link BluetoothDevice#createRfcommSocketToServiceRecord} to
1180 * connect to this socket from another device using the same {@link UUID}.
1181 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
1182 * @param name service name for SDP record
1183 * @param uuid uuid for SDP record
1184 * @return a listening RFCOMM BluetoothServerSocket
1185 * @throws IOException on error, for example Bluetooth not available, or
1186 * insufficient permissions, or channel in use.
1187 * @hide
1188 */
1189 public BluetoothServerSocket listenUsingEncryptedRfcommWithServiceRecord(
1190 String name, UUID uuid) throws IOException {
1191 return createNewRfcommSocketAndRecord(name, uuid, false, true);
1192 }
1193
zzy3b147b72012-04-03 19:48:32 -07001194
Jaikumar Ganesh6eef14a2010-12-23 12:57:02 -08001195 private BluetoothServerSocket createNewRfcommSocketAndRecord(String name, UUID uuid,
1196 boolean auth, boolean encrypt) throws IOException {
Nick Pelly24bb9b82009-10-02 20:34:18 -07001197 BluetoothServerSocket socket;
zzy3b147b72012-04-03 19:48:32 -07001198 socket = new BluetoothServerSocket(BluetoothSocket.TYPE_RFCOMM, auth,
1199 encrypt, new ParcelUuid(uuid));
1200 socket.setServiceName(name);
1201 int errno = socket.mSocket.bindListen();
1202 if (errno != 0) {
1203 //TODO(BT): Throw the same exception error code
1204 // that the previous code was using.
1205 //socket.mSocket.throwErrnoNative(errno);
1206 throw new IOException("Error: " + errno);
Nick Pelly24bb9b82009-10-02 20:34:18 -07001207 }
Nick Pelly24bb9b82009-10-02 20:34:18 -07001208 return socket;
1209 }
1210
1211 /**
Nick Pellybd022f42009-08-14 18:33:38 -07001212 * Construct an unencrypted, unauthenticated, RFCOMM server socket.
1213 * Call #accept to retrieve connections to this socket.
1214 * @return An RFCOMM BluetoothServerSocket
1215 * @throws IOException On error, for example Bluetooth not available, or
1216 * insufficient permissions.
Nick Pelly45e27042009-08-19 11:00:00 -07001217 * @hide
Nick Pellybd022f42009-08-14 18:33:38 -07001218 */
1219 public BluetoothServerSocket listenUsingInsecureRfcommOn(int port) throws IOException {
1220 BluetoothServerSocket socket = new BluetoothServerSocket(
1221 BluetoothSocket.TYPE_RFCOMM, false, false, port);
Nick Pelly24bb9b82009-10-02 20:34:18 -07001222 int errno = socket.mSocket.bindListen();
1223 if (errno != 0) {
zzy3b147b72012-04-03 19:48:32 -07001224 //TODO(BT): Throw the same exception error code
1225 // that the previous code was using.
1226 //socket.mSocket.throwErrnoNative(errno);
1227 throw new IOException("Error: " + errno);
Nick Pellybd022f42009-08-14 18:33:38 -07001228 }
1229 return socket;
1230 }
1231
Mathias Jeppssone3b9dc102011-03-21 15:06:52 +01001232 /**
1233 * Construct an encrypted, RFCOMM server socket.
1234 * Call #accept to retrieve connections to this socket.
1235 * @return An RFCOMM BluetoothServerSocket
1236 * @throws IOException On error, for example Bluetooth not available, or
1237 * insufficient permissions.
1238 * @hide
1239 */
1240 public BluetoothServerSocket listenUsingEncryptedRfcommOn(int port)
1241 throws IOException {
1242 BluetoothServerSocket socket = new BluetoothServerSocket(
1243 BluetoothSocket.TYPE_RFCOMM, false, true, port);
1244 int errno = socket.mSocket.bindListen();
zzy3b147b72012-04-03 19:48:32 -07001245 if (errno < 0) {
1246 //TODO(BT): Throw the same exception error code
1247 // that the previous code was using.
1248 //socket.mSocket.throwErrnoNative(errno);
1249 throw new IOException("Error: " + errno);
Mathias Jeppssone3b9dc102011-03-21 15:06:52 +01001250 }
1251 return socket;
1252 }
1253
Nick Pellybd022f42009-08-14 18:33:38 -07001254 /**
1255 * Construct a SCO server socket.
1256 * Call #accept to retrieve connections to this socket.
1257 * @return A SCO BluetoothServerSocket
1258 * @throws IOException On error, for example Bluetooth not available, or
1259 * insufficient permissions.
Nick Pelly45e27042009-08-19 11:00:00 -07001260 * @hide
Nick Pellybd022f42009-08-14 18:33:38 -07001261 */
1262 public static BluetoothServerSocket listenUsingScoOn() throws IOException {
1263 BluetoothServerSocket socket = new BluetoothServerSocket(
1264 BluetoothSocket.TYPE_SCO, false, false, -1);
Nick Pelly24bb9b82009-10-02 20:34:18 -07001265 int errno = socket.mSocket.bindListen();
zzy3b147b72012-04-03 19:48:32 -07001266 if (errno < 0) {
1267 //TODO(BT): Throw the same exception error code
1268 // that the previous code was using.
1269 //socket.mSocket.throwErrnoNative(errno);
Nick Pellybd022f42009-08-14 18:33:38 -07001270 }
1271 return socket;
1272 }
1273
Jaikumar Ganeshcc5494c2010-09-09 15:37:57 -07001274 /**
1275 * Read the local Out of Band Pairing Data
1276 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
1277 *
1278 * @return Pair<byte[], byte[]> of Hash and Randomizer
1279 *
1280 * @hide
1281 */
1282 public Pair<byte[], byte[]> readOutOfBandData() {
1283 if (getState() != STATE_ON) return null;
Jaikumar Ganeshe4caddb2012-01-25 16:16:48 -08001284 //TODO(BT
1285 /*
Jaikumar Ganeshcc5494c2010-09-09 15:37:57 -07001286 try {
Jake Hambyf51eada2010-09-21 13:39:53 -07001287 byte[] hash;
1288 byte[] randomizer;
Jaikumar Ganeshcc5494c2010-09-09 15:37:57 -07001289
1290 byte[] ret = mService.readOutOfBandData();
1291
1292 if (ret == null || ret.length != 32) return null;
1293
1294 hash = Arrays.copyOfRange(ret, 0, 16);
1295 randomizer = Arrays.copyOfRange(ret, 16, 32);
1296
1297 if (DBG) {
1298 Log.d(TAG, "readOutOfBandData:" + Arrays.toString(hash) +
1299 ":" + Arrays.toString(randomizer));
1300 }
1301 return new Pair<byte[], byte[]>(hash, randomizer);
1302
Jaikumar Ganeshe4caddb2012-01-25 16:16:48 -08001303 } catch (RemoteException e) {Log.e(TAG, "", e);}*/
Jaikumar Ganeshcc5494c2010-09-09 15:37:57 -07001304 return null;
1305 }
1306
Scott Main299ae672011-01-19 21:13:18 -08001307 /**
Jaikumar Ganesh62c37ef2010-08-24 17:36:13 -07001308 * Get the profile proxy object associated with the profile.
1309 *
Ganesh Ganapathi Batta99081122013-02-05 15:28:33 -08001310 * <p>Profile can be one of {@link BluetoothProfile#HEALTH}, {@link BluetoothProfile#HEADSET},
Matthew Xieddf7e472013-03-01 18:41:02 -08001311 * {@link BluetoothProfile#A2DP}, {@link BluetoothProfile#GATT}, or
1312 * {@link BluetoothProfile#GATT_SERVER}. Clients must implement
Jaikumar Ganesh62c37ef2010-08-24 17:36:13 -07001313 * {@link BluetoothProfile.ServiceListener} to get notified of
1314 * the connection status and to get the proxy object.
1315 *
1316 * @param context Context of the application
1317 * @param listener The service Listener for connection callbacks.
Scott Main2d68a6b2011-09-26 22:59:38 -07001318 * @param profile The Bluetooth profile; either {@link BluetoothProfile#HEALTH},
1319 * {@link BluetoothProfile#HEADSET} or {@link BluetoothProfile#A2DP}.
Jaikumar Ganesh62c37ef2010-08-24 17:36:13 -07001320 * @return true on success, false on error
1321 */
1322 public boolean getProfileProxy(Context context, BluetoothProfile.ServiceListener listener,
1323 int profile) {
1324 if (context == null || listener == null) return false;
1325
1326 if (profile == BluetoothProfile.HEADSET) {
1327 BluetoothHeadset headset = new BluetoothHeadset(context, listener);
1328 return true;
1329 } else if (profile == BluetoothProfile.A2DP) {
1330 BluetoothA2dp a2dp = new BluetoothA2dp(context, listener);
1331 return true;
Jaikumar Ganesh4ab0e772011-02-18 14:52:32 -08001332 } else if (profile == BluetoothProfile.INPUT_DEVICE) {
1333 BluetoothInputDevice iDev = new BluetoothInputDevice(context, listener);
1334 return true;
Jaikumar Ganesh74ef1192011-02-23 10:22:15 -08001335 } else if (profile == BluetoothProfile.PAN) {
1336 BluetoothPan pan = new BluetoothPan(context, listener);
1337 return true;
Jaikumar Ganesh2ea1e852011-04-01 16:33:09 -07001338 } else if (profile == BluetoothProfile.HEALTH) {
1339 BluetoothHealth health = new BluetoothHealth(context, listener);
1340 return true;
Kim Schulz0d376052013-08-22 11:18:02 +02001341 } else if (profile == BluetoothProfile.MAP) {
1342 BluetoothMap map = new BluetoothMap(context, listener);
1343 return true;
Jaikumar Ganesh62c37ef2010-08-24 17:36:13 -07001344 } else {
1345 return false;
1346 }
1347 }
1348
1349 /**
1350 * Close the connection of the profile proxy to the Service.
1351 *
1352 * <p> Clients should call this when they are no longer using
1353 * the proxy obtained from {@link #getProfileProxy}.
Scott Main2d68a6b2011-09-26 22:59:38 -07001354 * Profile can be one of {@link BluetoothProfile#HEALTH}, {@link BluetoothProfile#HEADSET} or
Jaikumar Ganesh62c37ef2010-08-24 17:36:13 -07001355 * {@link BluetoothProfile#A2DP}
1356 *
1357 * @param profile
1358 * @param proxy Profile proxy object
1359 */
1360 public void closeProfileProxy(int profile, BluetoothProfile proxy) {
Jaikumar Ganesh9bb27512011-11-28 09:59:08 -08001361 if (proxy == null) return;
1362
1363 switch (profile) {
1364 case BluetoothProfile.HEADSET:
1365 BluetoothHeadset headset = (BluetoothHeadset)proxy;
Jaikumar Ganesh62c37ef2010-08-24 17:36:13 -07001366 headset.close();
Jaikumar Ganesh9bb27512011-11-28 09:59:08 -08001367 break;
1368 case BluetoothProfile.A2DP:
1369 BluetoothA2dp a2dp = (BluetoothA2dp)proxy;
1370 a2dp.close();
1371 break;
1372 case BluetoothProfile.INPUT_DEVICE:
1373 BluetoothInputDevice iDev = (BluetoothInputDevice)proxy;
1374 iDev.close();
1375 break;
1376 case BluetoothProfile.PAN:
1377 BluetoothPan pan = (BluetoothPan)proxy;
1378 pan.close();
1379 break;
1380 case BluetoothProfile.HEALTH:
1381 BluetoothHealth health = (BluetoothHealth)proxy;
1382 health.close();
1383 break;
Ganesh Ganapathi Batta99081122013-02-05 15:28:33 -08001384 case BluetoothProfile.GATT:
1385 BluetoothGatt gatt = (BluetoothGatt)proxy;
1386 gatt.close();
1387 break;
1388 case BluetoothProfile.GATT_SERVER:
1389 BluetoothGattServer gattServer = (BluetoothGattServer)proxy;
1390 gattServer.close();
1391 break;
Kim Schulz0d376052013-08-22 11:18:02 +02001392 case BluetoothProfile.MAP:
1393 BluetoothMap map = (BluetoothMap)proxy;
1394 map.close();
1395 break;
Jaikumar Ganesh62c37ef2010-08-24 17:36:13 -07001396 }
1397 }
1398
fredc0f420372012-04-12 00:02:00 -07001399 final private IBluetoothManagerCallback mManagerCallback =
1400 new IBluetoothManagerCallback.Stub() {
1401 public void onBluetoothServiceUp(IBluetooth bluetoothService) {
Matthew Xied77982e2012-11-29 20:26:19 -08001402 if (VDBG) Log.d(TAG, "onBluetoothServiceUp: " + bluetoothService);
fredc0f420372012-04-12 00:02:00 -07001403 synchronized (mManagerCallback) {
1404 mService = bluetoothService;
fredcbf072a72012-05-09 16:52:50 -07001405 for (IBluetoothManagerCallback cb : mProxyServiceStateCallbacks ){
fredc903ac6f2012-04-24 03:59:57 -07001406 try {
fredcd6883532012-04-25 17:46:13 -07001407 if (cb != null) {
1408 cb.onBluetoothServiceUp(bluetoothService);
1409 } else {
1410 Log.d(TAG, "onBluetoothServiceUp: cb is null!!!");
1411 }
fredc903ac6f2012-04-24 03:59:57 -07001412 } catch (Exception e) { Log.e(TAG,"",e);}
1413 }
fredc0f420372012-04-12 00:02:00 -07001414 }
1415 }
1416
1417 public void onBluetoothServiceDown() {
Matthew Xied77982e2012-11-29 20:26:19 -08001418 if (VDBG) Log.d(TAG, "onBluetoothServiceDown: " + mService);
fredc0f420372012-04-12 00:02:00 -07001419 synchronized (mManagerCallback) {
1420 mService = null;
fredcbf072a72012-05-09 16:52:50 -07001421 for (IBluetoothManagerCallback cb : mProxyServiceStateCallbacks ){
fredc903ac6f2012-04-24 03:59:57 -07001422 try {
fredcd6883532012-04-25 17:46:13 -07001423 if (cb != null) {
1424 cb.onBluetoothServiceDown();
1425 } else {
1426 Log.d(TAG, "onBluetoothServiceDown: cb is null!!!");
1427 }
fredc903ac6f2012-04-24 03:59:57 -07001428 } catch (Exception e) { Log.e(TAG,"",e);}
1429 }
fredc0f420372012-04-12 00:02:00 -07001430 }
1431 }
1432 };
1433
Jaikumar Ganeshef2cb7c2011-07-21 18:13:38 -07001434 /**
Martijn Coenen6c614b72012-04-18 13:01:15 -07001435 * Enable the Bluetooth Adapter, but don't auto-connect devices
1436 * and don't persist state. Only for use by system applications.
1437 * @hide
1438 */
1439 public boolean enableNoAutoConnect() {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001440 if (isEnabled() == true){
1441 if (DBG) Log.d(TAG, "enableNoAutoConnect(): BT is already enabled..!");
1442 return true;
1443 }
1444 try {
1445 return mManagerService.enableNoAutoConnect();
1446 } catch (RemoteException e) {Log.e(TAG, "", e);}
1447 return false;
Martijn Coenen6c614b72012-04-18 13:01:15 -07001448 }
1449
1450 /**
Jaikumar Ganeshef2cb7c2011-07-21 18:13:38 -07001451 * Enable control of the Bluetooth Adapter for a single application.
1452 *
1453 * <p>Some applications need to use Bluetooth for short periods of time to
1454 * transfer data but don't want all the associated implications like
1455 * automatic connection to headsets etc.
1456 *
1457 * <p> Multiple applications can call this. This is reference counted and
1458 * Bluetooth disabled only when no one else is using it. There will be no UI
1459 * shown to the user while bluetooth is being enabled. Any user action will
1460 * override this call. For example, if user wants Bluetooth on and the last
1461 * user of this API wanted to disable Bluetooth, Bluetooth will not be
1462 * turned off.
1463 *
1464 * <p> This API is only meant to be used by internal applications. Third
1465 * party applications but use {@link #enable} and {@link #disable} APIs.
1466 *
1467 * <p> If this API returns true, it means the callback will be called.
1468 * The callback will be called with the current state of Bluetooth.
1469 * If the state is not what was requested, an internal error would be the
Jaikumar Ganeshf5fb6c82011-08-03 14:17:22 -07001470 * reason. If Bluetooth is already on and if this function is called to turn
1471 * it on, the api will return true and a callback will be called.
1472 *
1473 * <p>Requires {@link android.Manifest.permission#BLUETOOTH}
Jaikumar Ganeshef2cb7c2011-07-21 18:13:38 -07001474 *
1475 * @param on True for on, false for off.
1476 * @param callback The callback to notify changes to the state.
1477 * @hide
1478 */
1479 public boolean changeApplicationBluetoothState(boolean on,
1480 BluetoothStateChangeCallback callback) {
1481 if (callback == null) return false;
1482
Jaikumar Ganeshe4caddb2012-01-25 16:16:48 -08001483 //TODO(BT)
1484 /*
Jaikumar Ganeshef2cb7c2011-07-21 18:13:38 -07001485 try {
1486 return mService.changeApplicationBluetoothState(on, new
1487 StateChangeCallbackWrapper(callback), new Binder());
1488 } catch (RemoteException e) {
1489 Log.e(TAG, "changeBluetoothState", e);
Jaikumar Ganeshe4caddb2012-01-25 16:16:48 -08001490 }*/
Jaikumar Ganeshef2cb7c2011-07-21 18:13:38 -07001491 return false;
1492 }
1493
1494 /**
1495 * @hide
1496 */
1497 public interface BluetoothStateChangeCallback {
1498 public void onBluetoothStateChange(boolean on);
1499 }
1500
1501 /**
1502 * @hide
1503 */
1504 public class StateChangeCallbackWrapper extends IBluetoothStateChangeCallback.Stub {
1505 private BluetoothStateChangeCallback mCallback;
1506
1507 StateChangeCallbackWrapper(BluetoothStateChangeCallback
1508 callback) {
1509 mCallback = callback;
1510 }
1511
1512 @Override
1513 public void onBluetoothStateChange(boolean on) {
1514 mCallback.onBluetoothStateChange(on);
1515 }
1516 }
1517
Jaikumar Ganeshe4caddb2012-01-25 16:16:48 -08001518 private Set<BluetoothDevice> toDeviceSet(BluetoothDevice[] devices) {
1519 Set<BluetoothDevice> deviceSet = new HashSet<BluetoothDevice>(Arrays.asList(devices));
1520 return Collections.unmodifiableSet(deviceSet);
Nick Pellybd022f42009-08-14 18:33:38 -07001521 }
Nick Pelly005b2282009-09-10 10:21:56 -07001522
fredc0f420372012-04-12 00:02:00 -07001523 protected void finalize() throws Throwable {
1524 try {
1525 mManagerService.unregisterAdapter(mManagerCallback);
1526 } catch (RemoteException e) {
1527 Log.e(TAG, "", e);
1528 } finally {
1529 super.finalize();
1530 }
1531 }
1532
1533
Nick Pelly005b2282009-09-10 10:21:56 -07001534 /**
Nick Pelly75596b42011-12-07 15:03:55 -08001535 * Validate a String Bluetooth address, such as "00:43:A8:23:10:F0"
Nick Pelly55e66f12009-09-18 11:37:06 -07001536 * <p>Alphabetic characters must be uppercase to be valid.
Nick Pelly005b2282009-09-10 10:21:56 -07001537 *
1538 * @param address Bluetooth address as string
1539 * @return true if the address is valid, false otherwise
1540 */
1541 public static boolean checkBluetoothAddress(String address) {
1542 if (address == null || address.length() != ADDRESS_LENGTH) {
1543 return false;
1544 }
1545 for (int i = 0; i < ADDRESS_LENGTH; i++) {
1546 char c = address.charAt(i);
1547 switch (i % 3) {
1548 case 0:
1549 case 1:
Nick Pelly55e66f12009-09-18 11:37:06 -07001550 if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F')) {
1551 // hex character, OK
1552 break;
Nick Pelly005b2282009-09-10 10:21:56 -07001553 }
1554 return false;
1555 case 2:
1556 if (c == ':') {
1557 break; // OK
1558 }
1559 return false;
1560 }
1561 }
1562 return true;
1563 }
fredc0f420372012-04-12 00:02:00 -07001564
1565 /*package*/ IBluetoothManager getBluetoothManager() {
1566 return mManagerService;
1567 }
1568
fredcbf072a72012-05-09 16:52:50 -07001569 private ArrayList<IBluetoothManagerCallback> mProxyServiceStateCallbacks = new ArrayList<IBluetoothManagerCallback>();
fredcd6883532012-04-25 17:46:13 -07001570
fredc903ac6f2012-04-24 03:59:57 -07001571 /*package*/ IBluetooth getBluetoothService(IBluetoothManagerCallback cb) {
fredc0f420372012-04-12 00:02:00 -07001572 synchronized (mManagerCallback) {
fredcd6883532012-04-25 17:46:13 -07001573 if (cb == null) {
fredcbf072a72012-05-09 16:52:50 -07001574 Log.w(TAG, "getBluetoothService() called with no BluetoothManagerCallback");
1575 } else if (!mProxyServiceStateCallbacks.contains(cb)) {
1576 mProxyServiceStateCallbacks.add(cb);
fredc903ac6f2012-04-24 03:59:57 -07001577 }
1578 }
1579 return mService;
1580 }
1581
1582 /*package*/ void removeServiceStateCallback(IBluetoothManagerCallback cb) {
1583 synchronized (mManagerCallback) {
fredcbf072a72012-05-09 16:52:50 -07001584 mProxyServiceStateCallbacks.remove(cb);
fredc0f420372012-04-12 00:02:00 -07001585 }
1586 }
Matthew Xieddf7e472013-03-01 18:41:02 -08001587
1588 /**
Matthew Xiecdd94e32013-04-11 16:36:26 -07001589 * Callback interface used to deliver LE scan results.
Matthew Xieddf7e472013-03-01 18:41:02 -08001590 *
Matthew Xiecdd94e32013-04-11 16:36:26 -07001591 * @see #startLeScan(LeScanCallback)
1592 * @see #startLeScan(UUID[], LeScanCallback)
Matthew Xieddf7e472013-03-01 18:41:02 -08001593 */
Matthew Xiecdd94e32013-04-11 16:36:26 -07001594 public interface LeScanCallback {
1595 /**
1596 * Callback reporting an LE device found during a device scan initiated
1597 * by the {@link BluetoothAdapter#startLeScan} function.
1598 *
1599 * @param device Identifies the remote device
1600 * @param rssi The RSSI value for the remote device as reported by the
1601 * Bluetooth hardware. 0 if no RSSI value is available.
1602 * @param scanRecord The content of the advertisement record offered by
1603 * the remote device.
1604 */
1605 public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord);
Matthew Xieddf7e472013-03-01 18:41:02 -08001606 }
1607
1608 /**
1609 * Starts a scan for Bluetooth LE devices.
1610 *
1611 * <p>Results of the scan are reported using the
Matthew Xiecdd94e32013-04-11 16:36:26 -07001612 * {@link LeScanCallback#onLeScan} callback.
Matthew Xieddf7e472013-03-01 18:41:02 -08001613 *
Matthew Xied5752332013-04-24 17:51:37 -07001614 * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN} permission.
Matthew Xieddf7e472013-03-01 18:41:02 -08001615 *
Matthew Xiecdd94e32013-04-11 16:36:26 -07001616 * @param callback the callback LE scan results are delivered
Matthew Xieddf7e472013-03-01 18:41:02 -08001617 * @return true, if the scan was started successfully
1618 */
Matthew Xiecdd94e32013-04-11 16:36:26 -07001619 public boolean startLeScan(LeScanCallback callback) {
1620 return startLeScan(null, callback);
Matthew Xieddf7e472013-03-01 18:41:02 -08001621 }
1622
1623 /**
1624 * Starts a scan for Bluetooth LE devices, looking for devices that
1625 * advertise given services.
1626 *
1627 * <p>Devices which advertise all specified services are reported using the
Matthew Xiecdd94e32013-04-11 16:36:26 -07001628 * {@link LeScanCallback#onLeScan} callback.
Matthew Xieddf7e472013-03-01 18:41:02 -08001629 *
Matthew Xied5752332013-04-24 17:51:37 -07001630 * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN} permission.
Matthew Xieddf7e472013-03-01 18:41:02 -08001631 *
1632 * @param serviceUuids Array of services to look for
Matthew Xiecdd94e32013-04-11 16:36:26 -07001633 * @param callback the callback LE scan results are delivered
Matthew Xieddf7e472013-03-01 18:41:02 -08001634 * @return true, if the scan was started successfully
1635 */
Matthew Xiecdd94e32013-04-11 16:36:26 -07001636 public boolean startLeScan(UUID[] serviceUuids, LeScanCallback callback) {
1637 if (DBG) Log.d(TAG, "startLeScan(): " + serviceUuids);
Matthew Xieddf7e472013-03-01 18:41:02 -08001638
Matthew Xiecdd94e32013-04-11 16:36:26 -07001639 if (callback == null) {
1640 if (DBG) Log.e(TAG, "startLeScan: null callback");
Matthew Xieddf7e472013-03-01 18:41:02 -08001641 return false;
1642 }
1643
Matthew Xiecdd94e32013-04-11 16:36:26 -07001644 synchronized(mLeScanClients) {
1645 if (mLeScanClients.containsKey(callback)) {
1646 if (DBG) Log.e(TAG, "LE Scan has already started");
1647 return false;
1648 }
1649
1650 try {
1651 IBluetoothGatt iGatt = mManagerService.getBluetoothGatt();
Matthew Xie32ab77b2013-05-08 19:26:57 -07001652 if (iGatt == null) {
1653 // BLE is not supported
1654 return false;
1655 }
1656
Matthew Xiecdd94e32013-04-11 16:36:26 -07001657 UUID uuid = UUID.randomUUID();
1658 GattCallbackWrapper wrapper = new GattCallbackWrapper(this, callback, serviceUuids);
Matthew Xiecdd94e32013-04-11 16:36:26 -07001659 iGatt.registerClient(new ParcelUuid(uuid), wrapper);
1660 if (wrapper.scanStarted()) {
1661 mLeScanClients.put(callback, wrapper);
1662 return true;
1663 }
1664 } catch (RemoteException e) {
1665 Log.e(TAG,"",e);
1666 }
1667 }
1668 return false;
Matthew Xieddf7e472013-03-01 18:41:02 -08001669 }
1670
1671 /**
1672 * Stops an ongoing Bluetooth LE device scan.
1673 *
Matthew Xied5752332013-04-24 17:51:37 -07001674 * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN} permission.
Matthew Xiecdd94e32013-04-11 16:36:26 -07001675 *
1676 * @param callback used to identify which scan to stop
1677 * must be the same handle used to start the scan
Matthew Xieddf7e472013-03-01 18:41:02 -08001678 */
Matthew Xiecdd94e32013-04-11 16:36:26 -07001679 public void stopLeScan(LeScanCallback callback) {
1680 if (DBG) Log.d(TAG, "stopLeScan()");
1681 GattCallbackWrapper wrapper;
1682 synchronized(mLeScanClients) {
1683 wrapper = mLeScanClients.remove(callback);
1684 if (wrapper == null) return;
Matthew Xieddf7e472013-03-01 18:41:02 -08001685 }
Matthew Xiecdd94e32013-04-11 16:36:26 -07001686 wrapper.stopLeScan();
Matthew Xieddf7e472013-03-01 18:41:02 -08001687 }
1688
1689 /**
1690 * Bluetooth GATT interface callbacks
1691 */
Matthew Xiecdd94e32013-04-11 16:36:26 -07001692 private static class GattCallbackWrapper extends IBluetoothGattCallback.Stub {
1693 private static final int LE_CALLBACK_REG_TIMEOUT = 2000;
1694 private static final int LE_CALLBACK_REG_WAIT_COUNT = 5;
Wei Wang86b3fa62013-10-29 21:05:37 -07001695 private static final int CALLBACK_TYPE_SCAN = 0;
1696 private static final int CALLBACK_TYPE_ADV = 1;
Matthew Xieddf7e472013-03-01 18:41:02 -08001697
Matthew Xiecdd94e32013-04-11 16:36:26 -07001698 private final LeScanCallback mLeScanCb;
Wei Wang86b3fa62013-10-29 21:05:37 -07001699 private int mCallbackType;
1700
Matthew Xiecdd94e32013-04-11 16:36:26 -07001701 // mLeHandle 0: not registered
1702 // -1: scan stopped
1703 // >0: registered and scan started
1704 private int mLeHandle;
1705 private final UUID[] mScanFilter;
1706 private WeakReference<BluetoothAdapter> mBluetoothAdapter;
Matthew Xieddf7e472013-03-01 18:41:02 -08001707
Matthew Xiecdd94e32013-04-11 16:36:26 -07001708 public GattCallbackWrapper(BluetoothAdapter bluetoothAdapter,
1709 LeScanCallback leScanCb, UUID[] uuid) {
1710 mBluetoothAdapter = new WeakReference<BluetoothAdapter>(bluetoothAdapter);
1711 mLeScanCb = leScanCb;
1712 mScanFilter = uuid;
1713 mLeHandle = 0;
Wei Wang86b3fa62013-10-29 21:05:37 -07001714 mCallbackType = CALLBACK_TYPE_SCAN;
1715 }
1716
1717 public GattCallbackWrapper(BluetoothAdapter bluetoothAdapter, LeScanCallback leScanCb,
1718 UUID[] uuid, int type) {
1719 mBluetoothAdapter = new WeakReference<BluetoothAdapter>(bluetoothAdapter);
1720 mLeScanCb = leScanCb;
1721 mScanFilter = uuid;
1722 mLeHandle = 0;
1723 mCallbackType = type;
Matthew Xiecdd94e32013-04-11 16:36:26 -07001724 }
Matthew Xieddf7e472013-03-01 18:41:02 -08001725
Matthew Xiecdd94e32013-04-11 16:36:26 -07001726 public boolean scanStarted() {
1727 boolean started = false;
1728 synchronized(this) {
1729 if (mLeHandle == -1) return false;
1730
1731 int count = 0;
1732 // wait for callback registration and LE scan to start
1733 while (mLeHandle == 0 && count < LE_CALLBACK_REG_WAIT_COUNT) {
1734 try {
1735 wait(LE_CALLBACK_REG_TIMEOUT);
1736 } catch (InterruptedException e) {
1737 Log.e(TAG, "Callback reg wait interrupted: " + e);
1738 }
1739 count++;
Matthew Xieddf7e472013-03-01 18:41:02 -08001740 }
Matthew Xiecdd94e32013-04-11 16:36:26 -07001741 started = (mLeHandle > 0);
Matthew Xieddf7e472013-03-01 18:41:02 -08001742 }
Matthew Xiecdd94e32013-04-11 16:36:26 -07001743 return started;
1744 }
Matthew Xieddf7e472013-03-01 18:41:02 -08001745
Wei Wang86b3fa62013-10-29 21:05:37 -07001746 public void stopAdvertising() {
1747 synchronized (this) {
1748 if (mLeHandle <= 0) {
1749 Log.e(TAG, "Error state, mLeHandle: " + mLeHandle);
1750 return;
1751 }
1752 BluetoothAdapter adapter = mBluetoothAdapter.get();
1753 if (adapter != null) {
1754 try {
1755 IBluetoothGatt iGatt = adapter.getBluetoothManager().getBluetoothGatt();
1756 iGatt.stopAdvertising();
1757 Log.d(TAG, "unregeistering client " + mLeHandle);
1758 iGatt.unregisterClient(mLeHandle);
1759 } catch (RemoteException e) {
1760 Log.e(TAG, "Failed to stop advertising and unregister" + e);
1761 }
1762 } else {
1763 Log.e(TAG, "stopAdvertising, BluetoothAdapter is null");
1764 }
1765 mLeHandle = -1;
1766 notifyAll();
1767 }
1768 }
1769
Matthew Xiecdd94e32013-04-11 16:36:26 -07001770 public void stopLeScan() {
1771 synchronized(this) {
1772 if (mLeHandle <= 0) {
1773 Log.e(TAG, "Error state, mLeHandle: " + mLeHandle);
1774 return;
1775 }
1776 BluetoothAdapter adapter = mBluetoothAdapter.get();
1777 if (adapter != null) {
1778 try {
1779 IBluetoothGatt iGatt = adapter.getBluetoothManager().getBluetoothGatt();
1780 iGatt.stopScan(mLeHandle, false);
1781 iGatt.unregisterClient(mLeHandle);
1782 } catch (RemoteException e) {
1783 Log.e(TAG, "Failed to stop scan and unregister" + e);
1784 }
1785 } else {
1786 Log.e(TAG, "stopLeScan, BluetoothAdapter is null");
1787 }
1788 mLeHandle = -1;
1789 notifyAll();
Matthew Xieddf7e472013-03-01 18:41:02 -08001790 }
Matthew Xiecdd94e32013-04-11 16:36:26 -07001791 }
Matthew Xieddf7e472013-03-01 18:41:02 -08001792
Matthew Xiecdd94e32013-04-11 16:36:26 -07001793 /**
1794 * Application interface registered - app is ready to go
1795 */
1796 public void onClientRegistered(int status, int clientIf) {
1797 if (DBG) Log.d(TAG, "onClientRegistered() - status=" + status +
1798 " clientIf=" + clientIf);
1799 synchronized(this) {
1800 if (mLeHandle == -1) {
1801 if (DBG) Log.d(TAG, "onClientRegistered LE scan canceled");
1802 }
1803
1804 if (status == BluetoothGatt.GATT_SUCCESS) {
1805 mLeHandle = clientIf;
1806 IBluetoothGatt iGatt = null;
1807 try {
1808 BluetoothAdapter adapter = mBluetoothAdapter.get();
1809 if (adapter != null) {
1810 iGatt = adapter.getBluetoothManager().getBluetoothGatt();
Wei Wang86b3fa62013-10-29 21:05:37 -07001811 if (mCallbackType == CALLBACK_TYPE_ADV) {
1812 iGatt.startAdvertising(mLeHandle);
Matthew Xiecdd94e32013-04-11 16:36:26 -07001813 } else {
Wei Wang86b3fa62013-10-29 21:05:37 -07001814 if (mScanFilter == null) {
1815 iGatt.startScan(mLeHandle, false);
1816 } else {
1817 ParcelUuid[] uuids = new ParcelUuid[mScanFilter.length];
1818 for(int i = 0; i != uuids.length; ++i) {
1819 uuids[i] = new ParcelUuid(mScanFilter[i]);
1820 }
1821 iGatt.startScanWithUuids(mLeHandle, false, uuids);
1822 }
Matthew Xiecdd94e32013-04-11 16:36:26 -07001823 }
1824 } else {
1825 Log.e(TAG, "onClientRegistered, BluetoothAdapter null");
1826 mLeHandle = -1;
1827 }
1828 } catch (RemoteException e) {
1829 Log.e(TAG, "fail to start le scan: " + e);
1830 mLeHandle = -1;
1831 }
1832 if (mLeHandle == -1) {
Wei Wang86b3fa62013-10-29 21:05:37 -07001833 // registration succeeded but start scan or advertise failed
Matthew Xiecdd94e32013-04-11 16:36:26 -07001834 if (iGatt != null) {
1835 try {
1836 iGatt.unregisterClient(mLeHandle);
1837 } catch (RemoteException e) {
1838 Log.e(TAG, "fail to unregister callback: " + mLeHandle +
1839 " error: " + e);
1840 }
1841 }
1842 }
1843 } else {
1844 // registration failed
1845 mLeHandle = -1;
1846 }
1847 notifyAll();
Matthew Xieddf7e472013-03-01 18:41:02 -08001848 }
Matthew Xiecdd94e32013-04-11 16:36:26 -07001849 }
Matthew Xieddf7e472013-03-01 18:41:02 -08001850
Matthew Xiecdd94e32013-04-11 16:36:26 -07001851 public void onClientConnectionState(int status, int clientIf,
1852 boolean connected, String address) {
1853 // no op
1854 }
1855
1856 /**
1857 * Callback reporting an LE scan result.
1858 * @hide
1859 */
1860 public void onScanResult(String address, int rssi, byte[] advData) {
1861 if (DBG) Log.d(TAG, "onScanResult() - Device=" + address + " RSSI=" +rssi);
1862
1863 // Check null in case the scan has been stopped
1864 synchronized(this) {
1865 if (mLeHandle <= 0) return;
Matthew Xieddf7e472013-03-01 18:41:02 -08001866 }
Matthew Xiecdd94e32013-04-11 16:36:26 -07001867 try {
1868 BluetoothAdapter adapter = mBluetoothAdapter.get();
1869 if (adapter == null) {
1870 Log.d(TAG, "onScanResult, BluetoothAdapter null");
1871 return;
1872 }
1873 mLeScanCb.onLeScan(adapter.getRemoteDevice(address), rssi, advData);
1874 } catch (Exception ex) {
1875 Log.w(TAG, "Unhandled exception: " + ex);
Matthew Xieddf7e472013-03-01 18:41:02 -08001876 }
Matthew Xiecdd94e32013-04-11 16:36:26 -07001877 }
Matthew Xieddf7e472013-03-01 18:41:02 -08001878
Matthew Xiecdd94e32013-04-11 16:36:26 -07001879 public void onGetService(String address, int srvcType,
1880 int srvcInstId, ParcelUuid srvcUuid) {
1881 // no op
1882 }
Matthew Xieddf7e472013-03-01 18:41:02 -08001883
Matthew Xiecdd94e32013-04-11 16:36:26 -07001884 public void onGetIncludedService(String address, int srvcType,
1885 int srvcInstId, ParcelUuid srvcUuid,
1886 int inclSrvcType, int inclSrvcInstId,
1887 ParcelUuid inclSrvcUuid) {
1888 // no op
1889 }
Matthew Xieddf7e472013-03-01 18:41:02 -08001890
Matthew Xiecdd94e32013-04-11 16:36:26 -07001891 public void onGetCharacteristic(String address, int srvcType,
1892 int srvcInstId, ParcelUuid srvcUuid,
1893 int charInstId, ParcelUuid charUuid,
1894 int charProps) {
1895 // no op
1896 }
Matthew Xieddf7e472013-03-01 18:41:02 -08001897
Matthew Xiecdd94e32013-04-11 16:36:26 -07001898 public void onGetDescriptor(String address, int srvcType,
1899 int srvcInstId, ParcelUuid srvcUuid,
1900 int charInstId, ParcelUuid charUuid,
Andre Eisenbach25b9cf92013-07-08 23:58:16 -07001901 int descInstId, ParcelUuid descUuid) {
Matthew Xiecdd94e32013-04-11 16:36:26 -07001902 // no op
1903 }
1904
1905 public void onSearchComplete(String address, int status) {
1906 // no op
1907 }
1908
1909 public void onCharacteristicRead(String address, int status, int srvcType,
1910 int srvcInstId, ParcelUuid srvcUuid,
1911 int charInstId, ParcelUuid charUuid, byte[] value) {
1912 // no op
1913 }
1914
1915 public void onCharacteristicWrite(String address, int status, int srvcType,
1916 int srvcInstId, ParcelUuid srvcUuid,
1917 int charInstId, ParcelUuid charUuid) {
1918 // no op
1919 }
1920
1921 public void onNotify(String address, int srvcType,
Matthew Xieddf7e472013-03-01 18:41:02 -08001922 int srvcInstId, ParcelUuid srvcUuid,
1923 int charInstId, ParcelUuid charUuid,
1924 byte[] value) {
Matthew Xiecdd94e32013-04-11 16:36:26 -07001925 // no op
1926 }
Matthew Xieddf7e472013-03-01 18:41:02 -08001927
Matthew Xiecdd94e32013-04-11 16:36:26 -07001928 public void onDescriptorRead(String address, int status, int srvcType,
1929 int srvcInstId, ParcelUuid srvcUuid,
1930 int charInstId, ParcelUuid charUuid,
Andre Eisenbach25b9cf92013-07-08 23:58:16 -07001931 int descInstId, ParcelUuid descrUuid, byte[] value) {
Matthew Xiecdd94e32013-04-11 16:36:26 -07001932 // no op
1933 }
Matthew Xieddf7e472013-03-01 18:41:02 -08001934
Matthew Xiecdd94e32013-04-11 16:36:26 -07001935 public void onDescriptorWrite(String address, int status, int srvcType,
1936 int srvcInstId, ParcelUuid srvcUuid,
1937 int charInstId, ParcelUuid charUuid,
Andre Eisenbach25b9cf92013-07-08 23:58:16 -07001938 int descInstId, ParcelUuid descrUuid) {
Matthew Xiecdd94e32013-04-11 16:36:26 -07001939 // no op
1940 }
Matthew Xieddf7e472013-03-01 18:41:02 -08001941
Matthew Xiecdd94e32013-04-11 16:36:26 -07001942 public void onExecuteWrite(String address, int status) {
1943 // no op
1944 }
Matthew Xieddf7e472013-03-01 18:41:02 -08001945
Matthew Xiecdd94e32013-04-11 16:36:26 -07001946 public void onReadRemoteRssi(String address, int rssi, int status) {
1947 // no op
1948 }
Andre Eisenbachf46b21a2013-08-06 19:57:48 -07001949
1950 public void onListen(int status) {
1951 // no op
1952 }
Matthew Xiecdd94e32013-04-11 16:36:26 -07001953 }
Matthew Xieddf7e472013-03-01 18:41:02 -08001954
Nick Pellybd022f42009-08-14 18:33:38 -07001955}