blob: ea7b696f68b518adbcc53fbe7474b7bcc78fb36f [file] [log] [blame]
fredc0f420372012-04-12 00:02:00 -07001/*
Zhihai Xufa0fd392012-10-23 17:31:56 -07002 * Copyright (C) 2012 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.
fredc0f420372012-04-12 00:02:00 -070015 */
16
17package com.android.server;
18
Zhihai Xu40874a02012-10-08 17:57:03 -070019import android.app.ActivityManager;
fredc0f420372012-04-12 00:02:00 -070020import android.bluetooth.BluetoothAdapter;
21import android.bluetooth.IBluetooth;
Matthew Xieddf7e472013-03-01 18:41:02 -080022import android.bluetooth.IBluetoothGatt;
fredcbf072a72012-05-09 16:52:50 -070023import android.bluetooth.IBluetoothCallback;
fredc0f420372012-04-12 00:02:00 -070024import android.bluetooth.IBluetoothManager;
25import android.bluetooth.IBluetoothManagerCallback;
26import android.bluetooth.IBluetoothStateChangeCallback;
fredc0f420372012-04-12 00:02:00 -070027import android.content.BroadcastReceiver;
28import android.content.ComponentName;
29import android.content.ContentResolver;
30import android.content.Context;
31import android.content.Intent;
32import android.content.IntentFilter;
33import android.content.ServiceConnection;
Zhihai Xu40874a02012-10-08 17:57:03 -070034import android.os.Binder;
fredc0f420372012-04-12 00:02:00 -070035import android.os.Handler;
Zhihai Xu40874a02012-10-08 17:57:03 -070036import android.os.HandlerThread;
fredc0f420372012-04-12 00:02:00 -070037import android.os.IBinder;
Zhihai Xu40874a02012-10-08 17:57:03 -070038import android.os.Looper;
fredc0f420372012-04-12 00:02:00 -070039import android.os.Message;
Zhihai Xu40874a02012-10-08 17:57:03 -070040import android.os.Process;
fredcd6883532012-04-25 17:46:13 -070041import android.os.RemoteCallbackList;
fredc0f420372012-04-12 00:02:00 -070042import android.os.RemoteException;
Zhihai Xu40874a02012-10-08 17:57:03 -070043import android.os.SystemClock;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070044import android.os.UserHandle;
fredc0f420372012-04-12 00:02:00 -070045import android.provider.Settings;
46import android.util.Log;
fredc0f420372012-04-12 00:02:00 -070047class BluetoothManagerService extends IBluetoothManager.Stub {
48 private static final String TAG = "BluetoothManagerService";
49 private static final boolean DBG = true;
50
fredc0f420372012-04-12 00:02:00 -070051 private static final String BLUETOOTH_ADMIN_PERM = android.Manifest.permission.BLUETOOTH_ADMIN;
52 private static final String BLUETOOTH_PERM = android.Manifest.permission.BLUETOOTH;
fredc0f420372012-04-12 00:02:00 -070053 private static final String ACTION_SERVICE_STATE_CHANGED="com.android.bluetooth.btservice.action.STATE_CHANGED";
54 private static final String EXTRA_ACTION="action";
Zhihai Xud31c3222012-10-31 16:08:57 -070055 private static final String SECURE_SETTINGS_BLUETOOTH_ADDR_VALID="bluetooth_addr_valid";
fredc0f420372012-04-12 00:02:00 -070056 private static final String SECURE_SETTINGS_BLUETOOTH_ADDRESS="bluetooth_address";
57 private static final String SECURE_SETTINGS_BLUETOOTH_NAME="bluetooth_name";
fredc0f420372012-04-12 00:02:00 -070058 private static final int TIMEOUT_BIND_MS = 3000; //Maximum msec to wait for a bind
59 private static final int TIMEOUT_SAVE_MS = 500; //Maximum msec to wait for a save
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +053060 //Maximum msec to wait for service restart
61 private static final int SERVICE_RESTART_TIME_MS = 200;
Zhihai Xu40874a02012-10-08 17:57:03 -070062 //Maximum msec to delay MESSAGE_USER_SWITCHED
63 private static final int USER_SWITCHED_TIME_MS = 200;
fredc0f420372012-04-12 00:02:00 -070064
65 private static final int MESSAGE_ENABLE = 1;
66 private static final int MESSAGE_DISABLE = 2;
fredc649fe492012-04-19 01:07:18 -070067 private static final int MESSAGE_REGISTER_ADAPTER = 20;
68 private static final int MESSAGE_UNREGISTER_ADAPTER = 21;
69 private static final int MESSAGE_REGISTER_STATE_CHANGE_CALLBACK = 30;
70 private static final int MESSAGE_UNREGISTER_STATE_CHANGE_CALLBACK = 31;
71 private static final int MESSAGE_BLUETOOTH_SERVICE_CONNECTED = 40;
72 private static final int MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED = 41;
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +053073 private static final int MESSAGE_RESTART_BLUETOOTH_SERVICE = 42;
fredcbf072a72012-05-09 16:52:50 -070074 private static final int MESSAGE_BLUETOOTH_STATE_CHANGE=60;
fredc0f420372012-04-12 00:02:00 -070075 private static final int MESSAGE_TIMEOUT_BIND =100;
76 private static final int MESSAGE_TIMEOUT_UNBIND =101;
77 private static final int MESSAGE_GET_NAME_AND_ADDRESS=200;
78 private static final int MESSAGE_SAVE_NAME_AND_ADDRESS=201;
Zhihai Xu40874a02012-10-08 17:57:03 -070079 private static final int MESSAGE_USER_SWITCHED = 300;
fredc0f420372012-04-12 00:02:00 -070080 private static final int MAX_SAVE_RETRIES=3;
Zhihai Xu401202b2012-12-03 11:36:21 -080081 // Bluetooth persisted setting is off
82 private static final int BLUETOOTH_OFF=0;
83 // Bluetooth persisted setting is on
84 // and Airplane mode won't affect Bluetooth state at start up
85 private static final int BLUETOOTH_ON_BLUETOOTH=1;
86 // Bluetooth persisted setting is on
87 // but Airplane mode will affect Bluetooth state at start up
88 // and Airplane mode will have higher priority.
89 private static final int BLUETOOTH_ON_AIRPLANE=2;
fredc0f420372012-04-12 00:02:00 -070090
Matthew Xieddf7e472013-03-01 18:41:02 -080091 private static final int SERVICE_IBLUETOOTH = 1;
92 private static final int SERVICE_IBLUETOOTHGATT = 2;
93
fredc0f420372012-04-12 00:02:00 -070094 private final Context mContext;
Matthew Xiecdce0b92012-07-12 19:06:15 -070095
96 // Locks are not provided for mName and mAddress.
97 // They are accessed in handler or broadcast receiver, same thread context.
fredc0f420372012-04-12 00:02:00 -070098 private String mAddress;
99 private String mName;
Matthew Xie6fde3092012-07-11 17:10:07 -0700100 private final ContentResolver mContentResolver;
101 private final RemoteCallbackList<IBluetoothManagerCallback> mCallbacks;
102 private final RemoteCallbackList<IBluetoothStateChangeCallback> mStateChangeCallbacks;
fredc649fe492012-04-19 01:07:18 -0700103 private IBluetooth mBluetooth;
Matthew Xieddf7e472013-03-01 18:41:02 -0800104 private IBluetoothGatt mBluetoothGatt;
fredc649fe492012-04-19 01:07:18 -0700105 private boolean mBinding;
106 private boolean mUnbinding;
Zhihai Xu401202b2012-12-03 11:36:21 -0800107 // used inside handler thread
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700108 private boolean mQuietEnable = false;
Zhihai Xu401202b2012-12-03 11:36:21 -0800109 // configuarion from external IBinder call which is used to
110 // synchronize with broadcast receiver.
111 private boolean mQuietEnableExternal;
112 // configuarion from external IBinder call which is used to
113 // synchronize with broadcast receiver.
114 private boolean mEnableExternal;
115 // used inside handler thread
Zhihai Xu40874a02012-10-08 17:57:03 -0700116 private boolean mEnable;
117 private int mState;
118 private HandlerThread mThread;
119 private final BluetoothHandler mHandler;
fredc0f420372012-04-12 00:02:00 -0700120
fredc649fe492012-04-19 01:07:18 -0700121 private void registerForAirplaneMode(IntentFilter filter) {
122 final ContentResolver resolver = mContext.getContentResolver();
Christopher Tatec09cdce2012-09-10 16:50:14 -0700123 final String airplaneModeRadios = Settings.Global.getString(resolver,
124 Settings.Global.AIRPLANE_MODE_RADIOS);
125 final String toggleableRadios = Settings.Global.getString(resolver,
126 Settings.Global.AIRPLANE_MODE_TOGGLEABLE_RADIOS);
fredc649fe492012-04-19 01:07:18 -0700127 boolean mIsAirplaneSensitive = airplaneModeRadios == null ? true :
Christopher Tatec09cdce2012-09-10 16:50:14 -0700128 airplaneModeRadios.contains(Settings.Global.RADIO_BLUETOOTH);
fredc649fe492012-04-19 01:07:18 -0700129 if (mIsAirplaneSensitive) {
130 filter.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED);
131 }
132 }
133
fredcbf072a72012-05-09 16:52:50 -0700134 private final IBluetoothCallback mBluetoothCallback = new IBluetoothCallback.Stub() {
135 @Override
136 public void onBluetoothStateChange(int prevState, int newState) throws RemoteException {
137 Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_STATE_CHANGE,prevState,newState);
138 mHandler.sendMessage(msg);
139 }
140 };
141
142 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
fredc0f420372012-04-12 00:02:00 -0700143 @Override
144 public void onReceive(Context context, Intent intent) {
145 String action = intent.getAction();
fredcbf072a72012-05-09 16:52:50 -0700146 if (BluetoothAdapter.ACTION_LOCAL_NAME_CHANGED.equals(action)) {
fredc0f420372012-04-12 00:02:00 -0700147 String newName = intent.getStringExtra(BluetoothAdapter.EXTRA_LOCAL_NAME);
Freda8c6df02012-07-11 10:25:23 -0700148 if (DBG) Log.d(TAG, "Bluetooth Adapter name changed to " + newName);
fredc0f420372012-04-12 00:02:00 -0700149 if (newName != null) {
150 storeNameAndAddress(newName, null);
151 }
fredc649fe492012-04-19 01:07:18 -0700152 } else if (Intent.ACTION_AIRPLANE_MODE_CHANGED.equals(action)) {
Zhihai Xu401202b2012-12-03 11:36:21 -0800153 synchronized(mReceiver) {
154 if (isBluetoothPersistedStateOn()) {
155 if (isAirplaneModeOn()) {
156 persistBluetoothSetting(BLUETOOTH_ON_AIRPLANE);
157 } else {
158 persistBluetoothSetting(BLUETOOTH_ON_BLUETOOTH);
159 }
160 }
161 if (isAirplaneModeOn()) {
162 // disable without persisting the setting
163 sendDisableMsg();
164 } else if (mEnableExternal) {
165 // enable without persisting the setting
166 sendEnableMsg(mQuietEnableExternal);
167 }
fredc649fe492012-04-19 01:07:18 -0700168 }
Zhihai Xu40874a02012-10-08 17:57:03 -0700169 } else if (Intent.ACTION_USER_SWITCHED.equals(action)) {
170 mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_USER_SWITCHED,
171 intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0), 0));
Zhihai Xu401202b2012-12-03 11:36:21 -0800172 } else if (Intent.ACTION_BOOT_COMPLETED.equals(action)) {
173 synchronized(mReceiver) {
174 if (mEnableExternal && isBluetoothPersistedStateOnBluetooth()) {
175 //Enable
176 if (DBG) Log.d(TAG, "Auto-enabling Bluetooth.");
177 sendEnableMsg(mQuietEnableExternal);
178 }
179 }
180
181 if (!isNameAndAddressSet()) {
182 //Sync the Bluetooth name and address from the Bluetooth Adapter
183 if (DBG) Log.d(TAG,"Retrieving Bluetooth Adapter name and address...");
184 getNameAndAddress();
185 }
fredc0f420372012-04-12 00:02:00 -0700186 }
187 }
188 };
189
190 BluetoothManagerService(Context context) {
Zhihai Xu40874a02012-10-08 17:57:03 -0700191 mThread = new HandlerThread("BluetoothManager");
192 mThread.start();
193 mHandler = new BluetoothHandler(mThread.getLooper());
194
fredc0f420372012-04-12 00:02:00 -0700195 mContext = context;
196 mBluetooth = null;
197 mBinding = false;
198 mUnbinding = false;
Zhihai Xu40874a02012-10-08 17:57:03 -0700199 mEnable = false;
200 mState = BluetoothAdapter.STATE_OFF;
Zhihai Xu401202b2012-12-03 11:36:21 -0800201 mQuietEnableExternal = false;
202 mEnableExternal = false;
fredc0f420372012-04-12 00:02:00 -0700203 mAddress = null;
204 mName = null;
205 mContentResolver = context.getContentResolver();
fredcd6883532012-04-25 17:46:13 -0700206 mCallbacks = new RemoteCallbackList<IBluetoothManagerCallback>();
207 mStateChangeCallbacks = new RemoteCallbackList<IBluetoothStateChangeCallback>();
Zhihai Xu401202b2012-12-03 11:36:21 -0800208 IntentFilter filter = new IntentFilter(Intent.ACTION_BOOT_COMPLETED);
Matthew Xie6fde3092012-07-11 17:10:07 -0700209 filter.addAction(BluetoothAdapter.ACTION_LOCAL_NAME_CHANGED);
Zhihai Xu40874a02012-10-08 17:57:03 -0700210 filter.addAction(Intent.ACTION_USER_SWITCHED);
Matthew Xie6fde3092012-07-11 17:10:07 -0700211 registerForAirplaneMode(filter);
212 mContext.registerReceiver(mReceiver, filter);
fredc0f420372012-04-12 00:02:00 -0700213 loadStoredNameAndAddress();
Zhihai Xu401202b2012-12-03 11:36:21 -0800214 if (isBluetoothPersistedStateOn()) {
215 mEnableExternal = true;
fredc0f420372012-04-12 00:02:00 -0700216 }
217 }
218
fredc649fe492012-04-19 01:07:18 -0700219 /**
220 * Returns true if airplane mode is currently on
221 */
222 private final boolean isAirplaneModeOn() {
Christopher Tatec09cdce2012-09-10 16:50:14 -0700223 return Settings.Global.getInt(mContext.getContentResolver(),
224 Settings.Global.AIRPLANE_MODE_ON, 0) == 1;
fredc649fe492012-04-19 01:07:18 -0700225 }
226
227 /**
228 * Returns true if the Bluetooth saved state is "on"
229 */
230 private final boolean isBluetoothPersistedStateOn() {
Jeff Brownbf6f6f92012-09-25 15:03:20 -0700231 return Settings.Global.getInt(mContentResolver,
Zhihai Xu401202b2012-12-03 11:36:21 -0800232 Settings.Global.BLUETOOTH_ON, 0) != BLUETOOTH_OFF;
233 }
234
235 /**
236 * Returns true if the Bluetooth saved state is BLUETOOTH_ON_BLUETOOTH
237 */
238 private final boolean isBluetoothPersistedStateOnBluetooth() {
239 return Settings.Global.getInt(mContentResolver,
240 Settings.Global.BLUETOOTH_ON, 0) == BLUETOOTH_ON_BLUETOOTH;
fredc649fe492012-04-19 01:07:18 -0700241 }
242
243 /**
244 * Save the Bluetooth on/off state
245 *
246 */
Zhihai Xu401202b2012-12-03 11:36:21 -0800247 private void persistBluetoothSetting(int value) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -0700248 Settings.Global.putInt(mContext.getContentResolver(),
249 Settings.Global.BLUETOOTH_ON,
Zhihai Xu401202b2012-12-03 11:36:21 -0800250 value);
fredc649fe492012-04-19 01:07:18 -0700251 }
252
253 /**
254 * Returns true if the Bluetooth Adapter's name and address is
255 * locally cached
256 * @return
257 */
fredc0f420372012-04-12 00:02:00 -0700258 private boolean isNameAndAddressSet() {
259 return mName !=null && mAddress!= null && mName.length()>0 && mAddress.length()>0;
260 }
261
fredc649fe492012-04-19 01:07:18 -0700262 /**
263 * Retrieve the Bluetooth Adapter's name and address and save it in
264 * in the local cache
265 */
fredc0f420372012-04-12 00:02:00 -0700266 private void loadStoredNameAndAddress() {
267 if (DBG) Log.d(TAG, "Loading stored name and address");
Zhihai Xud31c3222012-10-31 16:08:57 -0700268 if (mContext.getResources().getBoolean
269 (com.android.internal.R.bool.config_bluetooth_address_validation) &&
270 Settings.Secure.getInt(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDR_VALID, 0) == 0) {
271 // if the valid flag is not set, don't load the address and name
272 if (DBG) Log.d(TAG, "invalid bluetooth name and address stored");
273 return;
274 }
fredc0f420372012-04-12 00:02:00 -0700275 mName = Settings.Secure.getString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_NAME);
276 mAddress = Settings.Secure.getString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDRESS);
Zhihai Xud31c3222012-10-31 16:08:57 -0700277 if (DBG) Log.d(TAG, "Stored bluetooth Name=" + mName + ",Address=" + mAddress);
fredc0f420372012-04-12 00:02:00 -0700278 }
279
fredc649fe492012-04-19 01:07:18 -0700280 /**
281 * Save the Bluetooth name and address in the persistent store.
282 * Only non-null values will be saved.
283 * @param name
284 * @param address
285 */
fredc0f420372012-04-12 00:02:00 -0700286 private void storeNameAndAddress(String name, String address) {
287 if (name != null) {
288 Settings.Secure.putString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_NAME, name);
fredc0f420372012-04-12 00:02:00 -0700289 mName = name;
fredc649fe492012-04-19 01:07:18 -0700290 if (DBG) Log.d(TAG,"Stored Bluetooth name: " +
291 Settings.Secure.getString(mContentResolver,SECURE_SETTINGS_BLUETOOTH_NAME));
fredc0f420372012-04-12 00:02:00 -0700292 }
293
294 if (address != null) {
295 Settings.Secure.putString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDRESS, address);
fredc0f420372012-04-12 00:02:00 -0700296 mAddress=address;
fredc649fe492012-04-19 01:07:18 -0700297 if (DBG) Log.d(TAG,"Stored Bluetoothaddress: " +
298 Settings.Secure.getString(mContentResolver,SECURE_SETTINGS_BLUETOOTH_ADDRESS));
fredc0f420372012-04-12 00:02:00 -0700299 }
Zhihai Xud31c3222012-10-31 16:08:57 -0700300
301 if ((name != null) && (address != null)) {
302 Settings.Secure.putInt(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDR_VALID, 1);
303 }
fredc0f420372012-04-12 00:02:00 -0700304 }
305
306 public IBluetooth registerAdapter(IBluetoothManagerCallback callback){
fredc0f420372012-04-12 00:02:00 -0700307 Message msg = mHandler.obtainMessage(MESSAGE_REGISTER_ADAPTER);
308 msg.obj = callback;
309 mHandler.sendMessage(msg);
310 synchronized(mConnection) {
311 return mBluetooth;
312 }
313 }
314
315 public void unregisterAdapter(IBluetoothManagerCallback callback) {
316 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
317 "Need BLUETOOTH permission");
318 Message msg = mHandler.obtainMessage(MESSAGE_UNREGISTER_ADAPTER);
319 msg.obj = callback;
320 mHandler.sendMessage(msg);
321 }
322
323 public void registerStateChangeCallback(IBluetoothStateChangeCallback callback) {
324 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
325 "Need BLUETOOTH permission");
326 Message msg = mHandler.obtainMessage(MESSAGE_REGISTER_STATE_CHANGE_CALLBACK);
327 msg.obj = callback;
328 mHandler.sendMessage(msg);
329 }
330
331 public void unregisterStateChangeCallback(IBluetoothStateChangeCallback callback) {
332 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
333 "Need BLUETOOTH permission");
334 Message msg = mHandler.obtainMessage(MESSAGE_UNREGISTER_STATE_CHANGE_CALLBACK);
335 msg.obj = callback;
336 mHandler.sendMessage(msg);
337 }
338
339 public boolean isEnabled() {
Zhihai Xu6eb76522012-11-29 15:41:04 -0800340 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
341 (!checkIfCallerIsForegroundUser())) {
342 Log.w(TAG,"isEnabled(): not allowed for non-active and non system user");
Zhihai Xu40874a02012-10-08 17:57:03 -0700343 return false;
344 }
345
fredc0f420372012-04-12 00:02:00 -0700346 synchronized(mConnection) {
347 try {
348 return (mBluetooth != null && mBluetooth.isEnabled());
349 } catch (RemoteException e) {
350 Log.e(TAG, "isEnabled()", e);
351 }
352 }
353 return false;
354 }
355
356 public void getNameAndAddress() {
fredcf2458862012-04-16 15:18:27 -0700357 if (DBG) {
Matthew Xiecdce0b92012-07-12 19:06:15 -0700358 Log.d(TAG,"getNameAndAddress(): mBluetooth = " + mBluetooth +
359 " mBinding = " + mBinding);
fredcf2458862012-04-16 15:18:27 -0700360 }
fredc0f420372012-04-12 00:02:00 -0700361 Message msg = mHandler.obtainMessage(MESSAGE_GET_NAME_AND_ADDRESS);
362 mHandler.sendMessage(msg);
363 }
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700364 public boolean enableNoAutoConnect()
365 {
366 mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
367 "Need BLUETOOTH ADMIN permission");
Zhihai Xu40874a02012-10-08 17:57:03 -0700368
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700369 if (DBG) {
370 Log.d(TAG,"enableNoAutoConnect(): mBluetooth =" + mBluetooth +
371 " mBinding = " + mBinding);
372 }
Martijn Coenen8385c5a2012-11-29 10:14:16 -0800373 int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
374
375 if (callingAppId != Process.NFC_UID) {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700376 throw new SecurityException("no permission to enable Bluetooth quietly");
377 }
Martijn Coenen8385c5a2012-11-29 10:14:16 -0800378
Zhihai Xu401202b2012-12-03 11:36:21 -0800379 synchronized(mReceiver) {
380 mQuietEnableExternal = true;
381 mEnableExternal = true;
382 sendEnableMsg(true);
383 }
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700384 return true;
385
386 }
fredc0f420372012-04-12 00:02:00 -0700387 public boolean enable() {
Zhihai Xu6eb76522012-11-29 15:41:04 -0800388 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
389 (!checkIfCallerIsForegroundUser())) {
390 Log.w(TAG,"enable(): not allowed for non-active and non system user");
Zhihai Xu40874a02012-10-08 17:57:03 -0700391 return false;
fredcf2458862012-04-16 15:18:27 -0700392 }
393
Zhihai Xu401202b2012-12-03 11:36:21 -0800394 mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
395 "Need BLUETOOTH ADMIN permission");
396 if (DBG) {
397 Log.d(TAG,"enable(): mBluetooth =" + mBluetooth +
398 " mBinding = " + mBinding);
399 }
400
401 synchronized(mReceiver) {
402 mQuietEnableExternal = false;
403 mEnableExternal = true;
404 // waive WRITE_SECURE_SETTINGS permission check
405 long callingIdentity = Binder.clearCallingIdentity();
406 persistBluetoothSetting(BLUETOOTH_ON_BLUETOOTH);
407 Binder.restoreCallingIdentity(callingIdentity);
408 sendEnableMsg(false);
409 }
410 return true;
fredc0f420372012-04-12 00:02:00 -0700411 }
412
413 public boolean disable(boolean persist) {
414 mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
415 "Need BLUETOOTH ADMIN permissicacheNameAndAddresson");
Zhihai Xu40874a02012-10-08 17:57:03 -0700416
Zhihai Xu6eb76522012-11-29 15:41:04 -0800417 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
418 (!checkIfCallerIsForegroundUser())) {
419 Log.w(TAG,"disable(): not allowed for non-active and non system user");
Zhihai Xu40874a02012-10-08 17:57:03 -0700420 return false;
421 }
422
fredcf2458862012-04-16 15:18:27 -0700423 if (DBG) {
Matthew Xiecdce0b92012-07-12 19:06:15 -0700424 Log.d(TAG,"disable(): mBluetooth = " + mBluetooth +
425 " mBinding = " + mBinding);
426 }
fredcf2458862012-04-16 15:18:27 -0700427
Zhihai Xu401202b2012-12-03 11:36:21 -0800428 synchronized(mReceiver) {
429 if (persist) {
430 // waive WRITE_SECURE_SETTINGS permission check
431 long callingIdentity = Binder.clearCallingIdentity();
432 persistBluetoothSetting(BLUETOOTH_OFF);
433 Binder.restoreCallingIdentity(callingIdentity);
434 }
435 mEnableExternal = false;
436 sendDisableMsg();
437 }
fredc0f420372012-04-12 00:02:00 -0700438 return true;
439 }
440
fredc649fe492012-04-19 01:07:18 -0700441 public void unbindAndFinish() {
fredcf2458862012-04-16 15:18:27 -0700442 if (DBG) {
Matthew Xiecdce0b92012-07-12 19:06:15 -0700443 Log.d(TAG,"unbindAndFinish(): " + mBluetooth +
444 " mBinding = " + mBinding);
fredcf2458862012-04-16 15:18:27 -0700445 }
446
fredc0f420372012-04-12 00:02:00 -0700447 synchronized (mConnection) {
448 if (mUnbinding) return;
449 mUnbinding = true;
Zhihai Xu40874a02012-10-08 17:57:03 -0700450 if (mBluetooth != null) {
fredcbf072a72012-05-09 16:52:50 -0700451 if (!mConnection.isGetNameAddressOnly()) {
452 //Unregister callback object
453 try {
454 mBluetooth.unregisterCallback(mBluetoothCallback);
455 } catch (RemoteException re) {
Zhihai Xu40874a02012-10-08 17:57:03 -0700456 Log.e(TAG, "Unable to unregister BluetoothCallback",re);
fredcbf072a72012-05-09 16:52:50 -0700457 }
458 }
fredc0f420372012-04-12 00:02:00 -0700459 if (DBG) Log.d(TAG, "Sending unbind request.");
fredcd6883532012-04-25 17:46:13 -0700460 mBluetooth = null;
461 //Unbind
fredc0f420372012-04-12 00:02:00 -0700462 mContext.unbindService(mConnection);
fredcd6883532012-04-25 17:46:13 -0700463 mUnbinding = false;
Zhihai Xu40874a02012-10-08 17:57:03 -0700464 mBinding = false;
fredcf2458862012-04-16 15:18:27 -0700465 } else {
466 mUnbinding=false;
fredc0f420372012-04-12 00:02:00 -0700467 }
468 }
469 }
470
Matthew Xieddf7e472013-03-01 18:41:02 -0800471 public IBluetoothGatt getBluetoothGatt() {
472 // sync protection
473 return mBluetoothGatt;
474 }
475
fredcbf072a72012-05-09 16:52:50 -0700476 private void sendBluetoothStateCallback(boolean isUp) {
477 int n = mStateChangeCallbacks.beginBroadcast();
Freda8c6df02012-07-11 10:25:23 -0700478 if (DBG) Log.d(TAG,"Broadcasting onBluetoothStateChange("+isUp+") to " + n + " receivers.");
fredcbf072a72012-05-09 16:52:50 -0700479 for (int i=0; i <n;i++) {
480 try {
481 mStateChangeCallbacks.getBroadcastItem(i).onBluetoothStateChange(isUp);
482 } catch (RemoteException e) {
483 Log.e(TAG, "Unable to call onBluetoothStateChange() on callback #" + i , e);
484 }
485 }
486 mStateChangeCallbacks.finishBroadcast();
487 }
488
489 /**
Zhihai Xu40874a02012-10-08 17:57:03 -0700490 * Inform BluetoothAdapter instances that Adapter service is up
491 */
492 private void sendBluetoothServiceUpCallback() {
493 if (!mConnection.isGetNameAddressOnly()) {
494 if (DBG) Log.d(TAG,"Calling onBluetoothServiceUp callbacks");
495 int n = mCallbacks.beginBroadcast();
496 Log.d(TAG,"Broadcasting onBluetoothServiceUp() to " + n + " receivers.");
497 for (int i=0; i <n;i++) {
498 try {
499 mCallbacks.getBroadcastItem(i).onBluetoothServiceUp(mBluetooth);
500 } catch (RemoteException e) {
501 Log.e(TAG, "Unable to call onBluetoothServiceUp() on callback #" + i, e);
502 }
503 }
504 mCallbacks.finishBroadcast();
505 }
506 }
507 /**
fredcbf072a72012-05-09 16:52:50 -0700508 * Inform BluetoothAdapter instances that Adapter service is down
509 */
510 private void sendBluetoothServiceDownCallback() {
fredcd6883532012-04-25 17:46:13 -0700511 if (!mConnection.isGetNameAddressOnly()) {
512 if (DBG) Log.d(TAG,"Calling onBluetoothServiceDown callbacks");
513 int n = mCallbacks.beginBroadcast();
514 Log.d(TAG,"Broadcasting onBluetoothServiceDown() to " + n + " receivers.");
515 for (int i=0; i <n;i++) {
516 try {
517 mCallbacks.getBroadcastItem(i).onBluetoothServiceDown();
518 } catch (RemoteException e) {
519 Log.e(TAG, "Unable to call onBluetoothServiceDown() on callback #" + i, e);
520 }
521 }
522 mCallbacks.finishBroadcast();
523 }
524 }
fredc0f420372012-04-12 00:02:00 -0700525 public String getAddress() {
Matthew Xieaf5ddbf2012-12-04 10:47:43 -0800526 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
527 "Need BLUETOOTH permission");
Zhihai Xu40874a02012-10-08 17:57:03 -0700528
Zhihai Xu6eb76522012-11-29 15:41:04 -0800529 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
530 (!checkIfCallerIsForegroundUser())) {
531 Log.w(TAG,"getAddress(): not allowed for non-active and non system user");
532 return null;
Zhihai Xu40874a02012-10-08 17:57:03 -0700533 }
534
fredc116d1d462012-04-20 14:47:08 -0700535 synchronized(mConnection) {
536 if (mBluetooth != null) {
537 try {
538 return mBluetooth.getAddress();
539 } catch (RemoteException e) {
540 Log.e(TAG, "getAddress(): Unable to retrieve address remotely..Returning cached address",e);
541 }
542 }
543 }
Matthew Xiecdce0b92012-07-12 19:06:15 -0700544 // mAddress is accessed from outside.
545 // It is alright without a lock. Here, bluetooth is off, no other thread is
546 // changing mAddress
fredc0f420372012-04-12 00:02:00 -0700547 return mAddress;
548 }
fredc649fe492012-04-19 01:07:18 -0700549
fredc0f420372012-04-12 00:02:00 -0700550 public String getName() {
Matthew Xieaf5ddbf2012-12-04 10:47:43 -0800551 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
552 "Need BLUETOOTH permission");
Zhihai Xu40874a02012-10-08 17:57:03 -0700553
Zhihai Xu6eb76522012-11-29 15:41:04 -0800554 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
555 (!checkIfCallerIsForegroundUser())) {
556 Log.w(TAG,"getName(): not allowed for non-active and non system user");
557 return null;
Zhihai Xu40874a02012-10-08 17:57:03 -0700558 }
559
fredc116d1d462012-04-20 14:47:08 -0700560 synchronized(mConnection) {
561 if (mBluetooth != null) {
562 try {
563 return mBluetooth.getName();
564 } catch (RemoteException e) {
565 Log.e(TAG, "getName(): Unable to retrieve name remotely..Returning cached name",e);
566 }
567 }
568 }
Matthew Xiecdce0b92012-07-12 19:06:15 -0700569 // mName is accessed from outside.
570 // It alright without a lock. Here, bluetooth is off, no other thread is
571 // changing mName
fredc0f420372012-04-12 00:02:00 -0700572 return mName;
573 }
574
fredc0f420372012-04-12 00:02:00 -0700575 private class BluetoothServiceConnection implements ServiceConnection {
576
577 private boolean mGetNameAddressOnly;
578
579 public void setGetNameAddressOnly(boolean getOnly) {
580 mGetNameAddressOnly = getOnly;
581 }
582
583 public boolean isGetNameAddressOnly() {
584 return mGetNameAddressOnly;
585 }
586
587 public void onServiceConnected(ComponentName className, IBinder service) {
Matthew Xieddf7e472013-03-01 18:41:02 -0800588 if (DBG) Log.d(TAG, "BluetoothServiceConnection: " + className.getClassName());
fredc0f420372012-04-12 00:02:00 -0700589 Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_SERVICE_CONNECTED);
Matthew Xieddf7e472013-03-01 18:41:02 -0800590 // TBD if (className.getClassName().equals(IBluetooth.class.getName())) {
591 if (className.getClassName().equals("com.android.bluetooth.btservice.AdapterService")) {
592 msg.arg1 = SERVICE_IBLUETOOTH;
593 // } else if (className.getClassName().equals(IBluetoothGatt.class.getName())) {
594 } else if (className.getClassName().equals("com.android.bluetooth.gatt.GattService")) {
595 msg.arg1 = SERVICE_IBLUETOOTHGATT;
596 } else {
597 Log.e(TAG, "Unknown service connected: " + className.getClassName());
598 return;
599 }
fredc0f420372012-04-12 00:02:00 -0700600 msg.obj = service;
601 mHandler.sendMessage(msg);
602 }
603
604 public void onServiceDisconnected(ComponentName className) {
fredc0f420372012-04-12 00:02:00 -0700605 // Called if we unexpected disconnected.
Matthew Xieddf7e472013-03-01 18:41:02 -0800606 if (DBG) Log.d(TAG, "BluetoothServiceConnection, disconnected: " +
607 className.getClassName());
fredc0f420372012-04-12 00:02:00 -0700608 Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED);
Matthew Xieddf7e472013-03-01 18:41:02 -0800609 if (className.getClassName().equals("com.android.bluetooth.btservice.AdapterService")) {
610 msg.arg1 = SERVICE_IBLUETOOTH;
611 } else if (className.getClassName().equals("com.android.bluetooth.gatt.GattService")) {
612 msg.arg1 = SERVICE_IBLUETOOTHGATT;
613 } else {
614 Log.e(TAG, "Unknown service disconnected: " + className.getClassName());
615 return;
616 }
fredc0f420372012-04-12 00:02:00 -0700617 mHandler.sendMessage(msg);
618 }
619 }
620
621 private BluetoothServiceConnection mConnection = new BluetoothServiceConnection();
622
Zhihai Xu40874a02012-10-08 17:57:03 -0700623 private class BluetoothHandler extends Handler {
624 public BluetoothHandler(Looper looper) {
625 super(looper);
626 }
627
fredc0f420372012-04-12 00:02:00 -0700628 @Override
629 public void handleMessage(Message msg) {
630 if (DBG) Log.d (TAG, "Message: " + msg.what);
fredc0f420372012-04-12 00:02:00 -0700631 switch (msg.what) {
632 case MESSAGE_GET_NAME_AND_ADDRESS: {
fredc649fe492012-04-19 01:07:18 -0700633 if (DBG) Log.d(TAG,"MESSAGE_GET_NAME_AND_ADDRESS");
Matthew Xiecdce0b92012-07-12 19:06:15 -0700634 synchronized(mConnection) {
fredc0f420372012-04-12 00:02:00 -0700635 //Start bind request
Zhihai Xu40874a02012-10-08 17:57:03 -0700636 if ((mBluetooth == null) && (!mBinding)) {
fredc0f420372012-04-12 00:02:00 -0700637 if (DBG) Log.d(TAG, "Binding to service to get name and address");
638 mConnection.setGetNameAddressOnly(true);
639 //Start bind timeout and bind
640 Message timeoutMsg = mHandler.obtainMessage(MESSAGE_TIMEOUT_BIND);
641 mHandler.sendMessageDelayed(timeoutMsg,TIMEOUT_BIND_MS);
642 Intent i = new Intent(IBluetooth.class.getName());
Amith Yamasani27b89e62013-01-16 12:30:11 -0800643 if (!mContext.bindServiceAsUser(i, mConnection,
644 Context.BIND_AUTO_CREATE, UserHandle.CURRENT)) {
fredc0f420372012-04-12 00:02:00 -0700645 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
646 Log.e(TAG, "fail to bind to: " + IBluetooth.class.getName());
Zhihai Xu40874a02012-10-08 17:57:03 -0700647 } else {
648 mBinding = true;
fredc0f420372012-04-12 00:02:00 -0700649 }
650 }
Matthew Xiecdce0b92012-07-12 19:06:15 -0700651 else {
652 Message saveMsg= mHandler.obtainMessage(MESSAGE_SAVE_NAME_AND_ADDRESS);
Zhihai Xu40874a02012-10-08 17:57:03 -0700653 saveMsg.arg1 = 0;
654 if (mBluetooth != null) {
655 mHandler.sendMessage(saveMsg);
656 } else {
657 // if enable is also called to bind the service
658 // wait for MESSAGE_BLUETOOTH_SERVICE_CONNECTED
659 mHandler.sendMessageDelayed(saveMsg, TIMEOUT_SAVE_MS);
660 }
Matthew Xiecdce0b92012-07-12 19:06:15 -0700661 }
fredc0f420372012-04-12 00:02:00 -0700662 }
fredc649fe492012-04-19 01:07:18 -0700663 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -0700664 }
fredc0f420372012-04-12 00:02:00 -0700665 case MESSAGE_SAVE_NAME_AND_ADDRESS: {
Zhihai Xud31c3222012-10-31 16:08:57 -0700666 boolean unbind = false;
fredc649fe492012-04-19 01:07:18 -0700667 if (DBG) Log.d(TAG,"MESSAGE_SAVE_NAME_AND_ADDRESS");
Matthew Xiecdce0b92012-07-12 19:06:15 -0700668 synchronized(mConnection) {
Zhihai Xud31c3222012-10-31 16:08:57 -0700669 if (!mEnable && mBluetooth != null) {
670 try {
671 mBluetooth.enable();
672 } catch (RemoteException e) {
673 Log.e(TAG,"Unable to call enable()",e);
674 }
675 }
676 }
677 if (mBluetooth != null) waitForOnOff(true, false);
678 synchronized(mConnection) {
Matthew Xiecdce0b92012-07-12 19:06:15 -0700679 if (mBluetooth != null) {
680 String name = null;
681 String address = null;
682 try {
683 name = mBluetooth.getName();
684 address = mBluetooth.getAddress();
685 } catch (RemoteException re) {
686 Log.e(TAG,"",re);
687 }
fredc0f420372012-04-12 00:02:00 -0700688
Matthew Xiecdce0b92012-07-12 19:06:15 -0700689 if (name != null && address != null) {
690 storeNameAndAddress(name,address);
Zhihai Xu40874a02012-10-08 17:57:03 -0700691 if (mConnection.isGetNameAddressOnly()) {
Zhihai Xud31c3222012-10-31 16:08:57 -0700692 unbind = true;
Zhihai Xu40874a02012-10-08 17:57:03 -0700693 }
Matthew Xiecdce0b92012-07-12 19:06:15 -0700694 } else {
695 if (msg.arg1 < MAX_SAVE_RETRIES) {
696 Message retryMsg = mHandler.obtainMessage(MESSAGE_SAVE_NAME_AND_ADDRESS);
697 retryMsg.arg1= 1+msg.arg1;
698 if (DBG) Log.d(TAG,"Retrying name/address remote retrieval and save.....Retry count =" + retryMsg.arg1);
699 mHandler.sendMessageDelayed(retryMsg, TIMEOUT_SAVE_MS);
700 } else {
701 Log.w(TAG,"Maximum name/address remote retrieval retry exceeded");
Zhihai Xu40874a02012-10-08 17:57:03 -0700702 if (mConnection.isGetNameAddressOnly()) {
Zhihai Xud31c3222012-10-31 16:08:57 -0700703 unbind = true;
Zhihai Xu40874a02012-10-08 17:57:03 -0700704 }
Matthew Xiecdce0b92012-07-12 19:06:15 -0700705 }
fredc0f420372012-04-12 00:02:00 -0700706 }
Zhihai Xud31c3222012-10-31 16:08:57 -0700707 if (!mEnable) {
708 try {
709 mBluetooth.disable();
710 } catch (RemoteException e) {
711 Log.e(TAG,"Unable to call disable()",e);
712 }
713 }
Zhihai Xu40874a02012-10-08 17:57:03 -0700714 } else {
715 // rebind service by Request GET NAME AND ADDRESS
716 // if service is unbinded by disable or
717 // MESSAGE_BLUETOOTH_SERVICE_CONNECTED is not received
718 Message getMsg = mHandler.obtainMessage(MESSAGE_GET_NAME_AND_ADDRESS);
719 mHandler.sendMessage(getMsg);
fredc0f420372012-04-12 00:02:00 -0700720 }
721 }
Zhihai Xud31c3222012-10-31 16:08:57 -0700722 if (!mEnable && mBluetooth != null) waitForOnOff(false, true);
723 if (unbind) {
724 unbindAndFinish();
725 }
fredc649fe492012-04-19 01:07:18 -0700726 break;
fredc649fe492012-04-19 01:07:18 -0700727 }
Matthew Xiecdce0b92012-07-12 19:06:15 -0700728 case MESSAGE_ENABLE:
fredcf2458862012-04-16 15:18:27 -0700729 if (DBG) {
Matthew Xiecdce0b92012-07-12 19:06:15 -0700730 Log.d(TAG, "MESSAGE_ENABLE: mBluetooth = " + mBluetooth);
fredc649fe492012-04-19 01:07:18 -0700731 }
Zhihai Xu40874a02012-10-08 17:57:03 -0700732 mHandler.removeMessages(MESSAGE_RESTART_BLUETOOTH_SERVICE);
733 mEnable = true;
Zhihai Xu401202b2012-12-03 11:36:21 -0800734 handleEnable(msg.arg1 == 1);
fredc649fe492012-04-19 01:07:18 -0700735 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -0700736
fredc0f420372012-04-12 00:02:00 -0700737 case MESSAGE_DISABLE:
Zhihai Xu40874a02012-10-08 17:57:03 -0700738 mHandler.removeMessages(MESSAGE_RESTART_BLUETOOTH_SERVICE);
739 if (mEnable && mBluetooth != null) {
740 waitForOnOff(true, false);
741 mEnable = false;
Zhihai Xu401202b2012-12-03 11:36:21 -0800742 handleDisable();
Zhihai Xu40874a02012-10-08 17:57:03 -0700743 waitForOnOff(false, false);
744 } else {
745 mEnable = false;
Zhihai Xu401202b2012-12-03 11:36:21 -0800746 handleDisable();
Zhihai Xu40874a02012-10-08 17:57:03 -0700747 }
fredc0f420372012-04-12 00:02:00 -0700748 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -0700749
fredc0f420372012-04-12 00:02:00 -0700750 case MESSAGE_REGISTER_ADAPTER:
751 {
752 IBluetoothManagerCallback callback = (IBluetoothManagerCallback) msg.obj;
fredcd6883532012-04-25 17:46:13 -0700753 boolean added = mCallbacks.register(callback);
754 Log.d(TAG,"Added callback: " + (callback == null? "null": callback) +":" +added );
fredc0f420372012-04-12 00:02:00 -0700755 }
756 break;
757 case MESSAGE_UNREGISTER_ADAPTER:
758 {
759 IBluetoothManagerCallback callback = (IBluetoothManagerCallback) msg.obj;
fredcd6883532012-04-25 17:46:13 -0700760 boolean removed = mCallbacks.unregister(callback);
761 Log.d(TAG,"Removed callback: " + (callback == null? "null": callback) +":" + removed);
fredc0f420372012-04-12 00:02:00 -0700762 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -0700763 }
fredc0f420372012-04-12 00:02:00 -0700764 case MESSAGE_REGISTER_STATE_CHANGE_CALLBACK:
765 {
766 IBluetoothStateChangeCallback callback = (IBluetoothStateChangeCallback) msg.obj;
fredcd6883532012-04-25 17:46:13 -0700767 mStateChangeCallbacks.register(callback);
fredc0f420372012-04-12 00:02:00 -0700768 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -0700769 }
fredc0f420372012-04-12 00:02:00 -0700770 case MESSAGE_UNREGISTER_STATE_CHANGE_CALLBACK:
771 {
772 IBluetoothStateChangeCallback callback = (IBluetoothStateChangeCallback) msg.obj;
fredcd6883532012-04-25 17:46:13 -0700773 mStateChangeCallbacks.unregister(callback);
fredc0f420372012-04-12 00:02:00 -0700774 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -0700775 }
fredc0f420372012-04-12 00:02:00 -0700776 case MESSAGE_BLUETOOTH_SERVICE_CONNECTED:
777 {
Matthew Xieddf7e472013-03-01 18:41:02 -0800778 if (DBG) Log.d(TAG,"MESSAGE_BLUETOOTH_SERVICE_CONNECTED: " + msg.arg1);
fredc0f420372012-04-12 00:02:00 -0700779
780 IBinder service = (IBinder) msg.obj;
781 synchronized(mConnection) {
Matthew Xieddf7e472013-03-01 18:41:02 -0800782 if (msg.arg1 == SERVICE_IBLUETOOTHGATT) {
783 mBluetoothGatt = IBluetoothGatt.Stub.asInterface(service);
784 break;
785 } // else must be SERVICE_IBLUETOOTH
786
787 //Remove timeout
788 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
789
fredc0f420372012-04-12 00:02:00 -0700790 mBinding = false;
791 mBluetooth = IBluetooth.Stub.asInterface(service);
fredc0f420372012-04-12 00:02:00 -0700792
Matthew Xiecdce0b92012-07-12 19:06:15 -0700793 if (mConnection.isGetNameAddressOnly()) {
794 //Request GET NAME AND ADDRESS
795 Message getMsg = mHandler.obtainMessage(MESSAGE_GET_NAME_AND_ADDRESS);
796 mHandler.sendMessage(getMsg);
Zhihai Xu40874a02012-10-08 17:57:03 -0700797 if (!mEnable) return;
Matthew Xiecdce0b92012-07-12 19:06:15 -0700798 }
fredc0f420372012-04-12 00:02:00 -0700799
Zhihai Xu40874a02012-10-08 17:57:03 -0700800 mConnection.setGetNameAddressOnly(false);
Matthew Xiecdce0b92012-07-12 19:06:15 -0700801 //Register callback object
fredcbf072a72012-05-09 16:52:50 -0700802 try {
Matthew Xiecdce0b92012-07-12 19:06:15 -0700803 mBluetooth.registerCallback(mBluetoothCallback);
804 } catch (RemoteException re) {
805 Log.e(TAG, "Unable to register BluetoothCallback",re);
fredcbf072a72012-05-09 16:52:50 -0700806 }
Matthew Xiecdce0b92012-07-12 19:06:15 -0700807 //Inform BluetoothAdapter instances that service is up
Zhihai Xu40874a02012-10-08 17:57:03 -0700808 sendBluetoothServiceUpCallback();
809
Matthew Xiecdce0b92012-07-12 19:06:15 -0700810 //Do enable request
811 try {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700812 if (mQuietEnable == false) {
813 if(!mBluetooth.enable()) {
814 Log.e(TAG,"IBluetooth.enable() returned false");
815 }
816 }
817 else
818 {
819 if(!mBluetooth.enableNoAutoConnect()) {
820 Log.e(TAG,"IBluetooth.enableNoAutoConnect() returned false");
821 }
Matthew Xiecdce0b92012-07-12 19:06:15 -0700822 }
823 } catch (RemoteException e) {
824 Log.e(TAG,"Unable to call enable()",e);
825 }
Freda8c6df02012-07-11 10:25:23 -0700826 }
Zhihai Xu40874a02012-10-08 17:57:03 -0700827
828 if (!mEnable) {
829 waitForOnOff(true, false);
Zhihai Xu401202b2012-12-03 11:36:21 -0800830 handleDisable();
Zhihai Xu40874a02012-10-08 17:57:03 -0700831 waitForOnOff(false, false);
832 }
fredc649fe492012-04-19 01:07:18 -0700833 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -0700834 }
fredc649fe492012-04-19 01:07:18 -0700835 case MESSAGE_TIMEOUT_BIND: {
836 Log.e(TAG, "MESSAGE_TIMEOUT_BIND");
fredc0f420372012-04-12 00:02:00 -0700837 synchronized(mConnection) {
838 mBinding = false;
839 }
fredc649fe492012-04-19 01:07:18 -0700840 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -0700841 }
fredcbf072a72012-05-09 16:52:50 -0700842 case MESSAGE_BLUETOOTH_STATE_CHANGE:
fredc0f420372012-04-12 00:02:00 -0700843 {
fredcbf072a72012-05-09 16:52:50 -0700844 int prevState = msg.arg1;
845 int newState = msg.arg2;
846 if (DBG) Log.d(TAG, "MESSAGE_BLUETOOTH_STATE_CHANGE: prevState = " + prevState + ", newState=" + newState);
Zhihai Xu40874a02012-10-08 17:57:03 -0700847 mState = newState;
848 bluetoothStateChangeHandler(prevState, newState);
fredc649fe492012-04-19 01:07:18 -0700849 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -0700850 }
fredc0f420372012-04-12 00:02:00 -0700851 case MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED:
852 {
Matthew Xieddf7e472013-03-01 18:41:02 -0800853 Log.e(TAG, "MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED: " + msg.arg1);
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +0530854 synchronized(mConnection) {
Matthew Xieddf7e472013-03-01 18:41:02 -0800855 if (msg.arg1 == SERVICE_IBLUETOOTH) {
856 // if service is unbinded already, do nothing and return
857 if (mBluetooth == null) break;
858 mBluetooth = null;
859 } else if (msg.arg1 == SERVICE_IBLUETOOTHGATT) {
860 mBluetoothGatt = null;
861 break;
862 } else {
863 Log.e(TAG, "Bad msg.arg1: " + msg.arg1);
864 break;
865 }
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +0530866 }
Zhihai Xu40874a02012-10-08 17:57:03 -0700867
868 if (mEnable) {
869 mEnable = false;
870 // Send a Bluetooth Restart message
871 Message restartMsg = mHandler.obtainMessage(
872 MESSAGE_RESTART_BLUETOOTH_SERVICE);
873 mHandler.sendMessageDelayed(restartMsg,
874 SERVICE_RESTART_TIME_MS);
875 }
876
877 if (!mConnection.isGetNameAddressOnly()) {
878 sendBluetoothServiceDownCallback();
879
880 // Send BT state broadcast to update
881 // the BT icon correctly
Zhihai Xu4e22ad32012-11-13 15:11:26 -0800882 if ((mState == BluetoothAdapter.STATE_TURNING_ON) ||
883 (mState == BluetoothAdapter.STATE_ON)) {
884 bluetoothStateChangeHandler(BluetoothAdapter.STATE_ON,
885 BluetoothAdapter.STATE_TURNING_OFF);
886 mState = BluetoothAdapter.STATE_TURNING_OFF;
887 }
888 if (mState == BluetoothAdapter.STATE_TURNING_OFF) {
889 bluetoothStateChangeHandler(BluetoothAdapter.STATE_TURNING_OFF,
890 BluetoothAdapter.STATE_OFF);
891 }
892
893 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
Zhihai Xu40874a02012-10-08 17:57:03 -0700894 mState = BluetoothAdapter.STATE_OFF;
895 }
fredc649fe492012-04-19 01:07:18 -0700896 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -0700897 }
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +0530898 case MESSAGE_RESTART_BLUETOOTH_SERVICE:
899 {
900 Log.d(TAG, "MESSAGE_RESTART_BLUETOOTH_SERVICE:"
901 +" Restart IBluetooth service");
902 /* Enable without persisting the setting as
903 it doesnt change when IBluetooth
904 service restarts */
Zhihai Xu40874a02012-10-08 17:57:03 -0700905 mEnable = true;
Zhihai Xu401202b2012-12-03 11:36:21 -0800906 handleEnable(mQuietEnable);
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +0530907 break;
908 }
909
fredc0f420372012-04-12 00:02:00 -0700910 case MESSAGE_TIMEOUT_UNBIND:
911 {
fredc649fe492012-04-19 01:07:18 -0700912 Log.e(TAG, "MESSAGE_TIMEOUT_UNBIND");
fredc0f420372012-04-12 00:02:00 -0700913 synchronized(mConnection) {
914 mUnbinding = false;
915 }
fredc649fe492012-04-19 01:07:18 -0700916 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -0700917 }
Zhihai Xu40874a02012-10-08 17:57:03 -0700918
919 case MESSAGE_USER_SWITCHED:
920 {
921 if (DBG) {
922 Log.d(TAG, "MESSAGE_USER_SWITCHED");
923 }
924 mHandler.removeMessages(MESSAGE_USER_SWITCHED);
925 /* disable and enable BT when detect a user switch */
926 if (mEnable && mBluetooth != null) {
927 synchronized (mConnection) {
928 if (mBluetooth != null) {
929 //Unregister callback object
930 try {
931 mBluetooth.unregisterCallback(mBluetoothCallback);
932 } catch (RemoteException re) {
933 Log.e(TAG, "Unable to unregister",re);
934 }
935 }
936 }
Zhihai Xu4e22ad32012-11-13 15:11:26 -0800937
938 if (mState == BluetoothAdapter.STATE_TURNING_OFF) {
939 // MESSAGE_USER_SWITCHED happened right after MESSAGE_ENABLE
940 bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_OFF);
941 mState = BluetoothAdapter.STATE_OFF;
942 }
943 if (mState == BluetoothAdapter.STATE_OFF) {
944 bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_TURNING_ON);
945 mState = BluetoothAdapter.STATE_TURNING_ON;
946 }
Zhihai Xu40874a02012-10-08 17:57:03 -0700947
948 waitForOnOff(true, false);
949
Zhihai Xu4e22ad32012-11-13 15:11:26 -0800950 if (mState == BluetoothAdapter.STATE_TURNING_ON) {
951 bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_ON);
952 }
Zhihai Xu40874a02012-10-08 17:57:03 -0700953
954 // disable
Zhihai Xu401202b2012-12-03 11:36:21 -0800955 handleDisable();
Zhihai Xu4e22ad32012-11-13 15:11:26 -0800956 // Pbap service need receive STATE_TURNING_OFF intent to close
957 bluetoothStateChangeHandler(BluetoothAdapter.STATE_ON,
958 BluetoothAdapter.STATE_TURNING_OFF);
Zhihai Xu40874a02012-10-08 17:57:03 -0700959
960 waitForOnOff(false, true);
961
Zhihai Xu4e22ad32012-11-13 15:11:26 -0800962 bluetoothStateChangeHandler(BluetoothAdapter.STATE_TURNING_OFF,
Zhihai Xu40874a02012-10-08 17:57:03 -0700963 BluetoothAdapter.STATE_OFF);
Zhihai Xu40874a02012-10-08 17:57:03 -0700964 sendBluetoothServiceDownCallback();
965 synchronized (mConnection) {
966 if (mBluetooth != null) {
967 mBluetooth = null;
968 //Unbind
969 mContext.unbindService(mConnection);
970 }
971 }
972 SystemClock.sleep(100);
973
Zhihai Xu4e22ad32012-11-13 15:11:26 -0800974 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
975 mState = BluetoothAdapter.STATE_OFF;
Zhihai Xu40874a02012-10-08 17:57:03 -0700976 // enable
Zhihai Xu401202b2012-12-03 11:36:21 -0800977 handleEnable(mQuietEnable);
Zhihai Xu40874a02012-10-08 17:57:03 -0700978 } else if (mBinding || mBluetooth != null) {
979 Message userMsg = mHandler.obtainMessage(MESSAGE_USER_SWITCHED);
980 userMsg.arg2 = 1 + msg.arg2;
981 // if user is switched when service is being binding
982 // delay sending MESSAGE_USER_SWITCHED
983 mHandler.sendMessageDelayed(userMsg, USER_SWITCHED_TIME_MS);
984 if (DBG) {
985 Log.d(TAG, "delay MESSAGE_USER_SWITCHED " + userMsg.arg2);
986 }
987 }
988 break;
989 }
fredc0f420372012-04-12 00:02:00 -0700990 }
991 }
Zhihai Xu40874a02012-10-08 17:57:03 -0700992 }
Matthew Xiecdce0b92012-07-12 19:06:15 -0700993
Zhihai Xu401202b2012-12-03 11:36:21 -0800994 private void handleEnable(boolean quietMode) {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700995 mQuietEnable = quietMode;
996
Matthew Xiecdce0b92012-07-12 19:06:15 -0700997 synchronized(mConnection) {
Zhihai Xu40874a02012-10-08 17:57:03 -0700998 if ((mBluetooth == null) && (!mBinding)) {
Matthew Xiecdce0b92012-07-12 19:06:15 -0700999 //Start bind timeout and bind
1000 Message timeoutMsg=mHandler.obtainMessage(MESSAGE_TIMEOUT_BIND);
1001 mHandler.sendMessageDelayed(timeoutMsg,TIMEOUT_BIND_MS);
1002 mConnection.setGetNameAddressOnly(false);
1003 Intent i = new Intent(IBluetooth.class.getName());
Amith Yamasani27b89e62013-01-16 12:30:11 -08001004 if (!mContext.bindServiceAsUser(i, mConnection,Context.BIND_AUTO_CREATE,
1005 UserHandle.CURRENT)) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001006 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
1007 Log.e(TAG, "Fail to bind to: " + IBluetooth.class.getName());
Zhihai Xu40874a02012-10-08 17:57:03 -07001008 } else {
1009 mBinding = true;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001010 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001011 } else if (mBluetooth != null) {
1012 if (mConnection.isGetNameAddressOnly()) {
1013 // if GetNameAddressOnly is set, we can clear this flag,
1014 // so the service won't be unbind
1015 // after name and address are saved
1016 mConnection.setGetNameAddressOnly(false);
1017 //Register callback object
1018 try {
1019 mBluetooth.registerCallback(mBluetoothCallback);
1020 } catch (RemoteException re) {
1021 Log.e(TAG, "Unable to register BluetoothCallback",re);
1022 }
1023 //Inform BluetoothAdapter instances that service is up
1024 sendBluetoothServiceUpCallback();
1025 }
1026
Matthew Xiecdce0b92012-07-12 19:06:15 -07001027 //Enable bluetooth
1028 try {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001029 if (!mQuietEnable) {
1030 if(!mBluetooth.enable()) {
1031 Log.e(TAG,"IBluetooth.enable() returned false");
1032 }
1033 }
1034 else {
1035 if(!mBluetooth.enableNoAutoConnect()) {
1036 Log.e(TAG,"IBluetooth.enableNoAutoConnect() returned false");
1037 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001038 }
1039 } catch (RemoteException e) {
1040 Log.e(TAG,"Unable to call enable()",e);
1041 }
1042 }
1043 }
1044 }
1045
Zhihai Xu401202b2012-12-03 11:36:21 -08001046 private void handleDisable() {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001047 synchronized(mConnection) {
Zhihai Xu40874a02012-10-08 17:57:03 -07001048 // don't need to disable if GetNameAddressOnly is set,
1049 // service will be unbinded after Name and Address are saved
1050 if ((mBluetooth != null) && (!mConnection.isGetNameAddressOnly())) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001051 if (DBG) Log.d(TAG,"Sending off request.");
1052
1053 try {
1054 if(!mBluetooth.disable()) {
1055 Log.e(TAG,"IBluetooth.disable() returned false");
1056 }
1057 } catch (RemoteException e) {
1058 Log.e(TAG,"Unable to call disable()",e);
1059 }
1060 }
1061 }
1062 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001063
1064 private boolean checkIfCallerIsForegroundUser() {
1065 int foregroundUser;
1066 int callingUser = UserHandle.getCallingUserId();
Martijn Coenen8385c5a2012-11-29 10:14:16 -08001067 int callingUid = Binder.getCallingUid();
Zhihai Xu40874a02012-10-08 17:57:03 -07001068 long callingIdentity = Binder.clearCallingIdentity();
Martijn Coenen8385c5a2012-11-29 10:14:16 -08001069 int callingAppId = UserHandle.getAppId(callingUid);
Zhihai Xu40874a02012-10-08 17:57:03 -07001070 boolean valid = false;
1071 try {
1072 foregroundUser = ActivityManager.getCurrentUser();
Martijn Coenen8385c5a2012-11-29 10:14:16 -08001073 valid = (callingUser == foregroundUser) ||
1074 callingAppId == Process.NFC_UID;
Zhihai Xu40874a02012-10-08 17:57:03 -07001075 if (DBG) {
1076 Log.d(TAG, "checkIfCallerIsForegroundUser: valid=" + valid
1077 + " callingUser=" + callingUser
1078 + " foregroundUser=" + foregroundUser);
1079 }
1080 } finally {
1081 Binder.restoreCallingIdentity(callingIdentity);
1082 }
1083 return valid;
1084 }
1085
Zhihai Xu40874a02012-10-08 17:57:03 -07001086 private void bluetoothStateChangeHandler(int prevState, int newState) {
1087 if (prevState != newState) {
1088 //Notify all proxy objects first of adapter state change
1089 if (newState == BluetoothAdapter.STATE_ON || newState == BluetoothAdapter.STATE_OFF) {
1090 boolean isUp = (newState==BluetoothAdapter.STATE_ON);
1091 sendBluetoothStateCallback(isUp);
1092
Matthew Xieddf7e472013-03-01 18:41:02 -08001093 if (isUp) {
1094 // connect to GattService
1095 Intent i = new Intent(IBluetoothGatt.class.getName());
1096 if (!mContext.bindServiceAsUser(i, mConnection, Context.BIND_AUTO_CREATE,
1097 UserHandle.CURRENT)) {
1098 Log.e(TAG, "Fail to bind to: " + IBluetoothGatt.class.getName());
1099 }
1100 } else {
1101 //If Bluetooth is off, send service down event to proxy objects, and unbind
1102 if (!isUp && canUnbindBluetoothService()) {
1103 sendBluetoothServiceDownCallback();
1104 unbindAndFinish();
1105 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001106 }
1107 }
1108
1109 //Send broadcast message to everyone else
1110 Intent intent = new Intent(BluetoothAdapter.ACTION_STATE_CHANGED);
1111 intent.putExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE, prevState);
1112 intent.putExtra(BluetoothAdapter.EXTRA_STATE, newState);
1113 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1114 if (DBG) Log.d(TAG,"Bluetooth State Change Intent: " + prevState + " -> " + newState);
1115 mContext.sendBroadcastAsUser(intent, UserHandle.ALL,
1116 BLUETOOTH_PERM);
1117 }
1118 }
1119
1120 /**
1121 * if on is true, wait for state become ON
1122 * if off is true, wait for state become OFF
1123 * if both on and off are false, wait for state not ON
1124 */
1125 private boolean waitForOnOff(boolean on, boolean off) {
1126 int i = 0;
1127 while (i < 10) {
1128 synchronized(mConnection) {
1129 try {
1130 if (mBluetooth == null) break;
1131 if (on) {
1132 if (mBluetooth.getState() == BluetoothAdapter.STATE_ON) return true;
1133 } else if (off) {
1134 if (mBluetooth.getState() == BluetoothAdapter.STATE_OFF) return true;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07001135 } else {
Zhihai Xu40874a02012-10-08 17:57:03 -07001136 if (mBluetooth.getState() != BluetoothAdapter.STATE_ON) return true;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07001137 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001138 } catch (RemoteException e) {
1139 Log.e(TAG, "getState()", e);
1140 break;
1141 }
1142 }
1143 if (on || off) {
1144 SystemClock.sleep(300);
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07001145 } else {
Zhihai Xu40874a02012-10-08 17:57:03 -07001146 SystemClock.sleep(50);
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07001147 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001148 i++;
1149 }
1150 Log.e(TAG,"waitForOnOff time out");
1151 return false;
1152 }
Zhihai Xu681ae7f2012-11-12 15:14:18 -08001153
Zhihai Xu401202b2012-12-03 11:36:21 -08001154 private void sendDisableMsg() {
1155 mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_DISABLE));
1156 }
1157
1158 private void sendEnableMsg(boolean quietMode) {
1159 mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_ENABLE,
1160 quietMode ? 1 : 0, 0));
1161 }
1162
Zhihai Xu681ae7f2012-11-12 15:14:18 -08001163 private boolean canUnbindBluetoothService() {
1164 synchronized(mConnection) {
1165 //Only unbind with mEnable flag not set
1166 //For race condition: disable and enable back-to-back
1167 //Avoid unbind right after enable due to callback from disable
1168 //Only unbind with Bluetooth at OFF state
1169 //Only unbind without any MESSAGE_BLUETOOTH_STATE_CHANGE message
1170 try {
1171 if (mEnable || (mBluetooth == null)) return false;
1172 if (mHandler.hasMessages(MESSAGE_BLUETOOTH_STATE_CHANGE)) return false;
1173 return (mBluetooth.getState() == BluetoothAdapter.STATE_OFF);
1174 } catch (RemoteException e) {
1175 Log.e(TAG, "getState()", e);
1176 }
1177 }
1178 return false;
1179 }
fredc0f420372012-04-12 00:02:00 -07001180}