blob: 2a5b1946b90da119aad1da86d61f4582dc761edb [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
Svet Ganov408abf72015-05-12 19:13:36 -070019import android.Manifest;
Zhihai Xu40874a02012-10-08 17:57:03 -070020import android.app.ActivityManager;
fredc0f420372012-04-12 00:02:00 -070021import android.bluetooth.BluetoothAdapter;
Benjamin Franze8b98922014-11-12 15:57:54 +000022import android.bluetooth.BluetoothProfile;
fredc0f420372012-04-12 00:02:00 -070023import android.bluetooth.IBluetooth;
fredcbf072a72012-05-09 16:52:50 -070024import android.bluetooth.IBluetoothCallback;
Wei Wange4a744b2015-06-11 17:50:29 -070025import android.bluetooth.IBluetoothGatt;
Benjamin Franze8b98922014-11-12 15:57:54 +000026import android.bluetooth.IBluetoothHeadset;
fredc0f420372012-04-12 00:02:00 -070027import android.bluetooth.IBluetoothManager;
28import android.bluetooth.IBluetoothManagerCallback;
Benjamin Franze8b98922014-11-12 15:57:54 +000029import android.bluetooth.IBluetoothProfileServiceConnection;
fredc0f420372012-04-12 00:02:00 -070030import android.bluetooth.IBluetoothStateChangeCallback;
fredc0f420372012-04-12 00:02:00 -070031import android.content.BroadcastReceiver;
32import android.content.ComponentName;
33import android.content.ContentResolver;
34import android.content.Context;
35import android.content.Intent;
36import android.content.IntentFilter;
37import android.content.ServiceConnection;
Svetoslav Ganovf9e2ad02016-06-29 17:31:44 -070038import android.content.pm.ApplicationInfo;
Matthew Xie32ab77b2013-05-08 19:26:57 -070039import android.content.pm.PackageManager;
Benjamin Franze8b98922014-11-12 15:57:54 +000040import android.content.pm.UserInfo;
Wei Wange4a744b2015-06-11 17:50:29 -070041import android.database.ContentObserver;
Zhihai Xu40874a02012-10-08 17:57:03 -070042import android.os.Binder;
Svetoslav Ganovf9e2ad02016-06-29 17:31:44 -070043import android.os.Build;
fredc0f420372012-04-12 00:02:00 -070044import android.os.Handler;
fredc0f420372012-04-12 00:02:00 -070045import android.os.IBinder;
Zhihai Xu40874a02012-10-08 17:57:03 -070046import android.os.Looper;
fredc0f420372012-04-12 00:02:00 -070047import android.os.Message;
Zhihai Xu40874a02012-10-08 17:57:03 -070048import android.os.Process;
fredcd6883532012-04-25 17:46:13 -070049import android.os.RemoteCallbackList;
fredc0f420372012-04-12 00:02:00 -070050import android.os.RemoteException;
Zhihai Xu40874a02012-10-08 17:57:03 -070051import android.os.SystemClock;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070052import android.os.UserHandle;
Benjamin Franze8b98922014-11-12 15:57:54 +000053import android.os.UserManager;
fredc0f420372012-04-12 00:02:00 -070054import android.provider.Settings;
Wei Wang67d84162015-04-26 17:04:29 -070055import android.provider.Settings.SettingNotFoundException;
Jeff Sharkey67609c72016-03-05 14:29:13 -070056import android.util.Slog;
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -070057import java.util.concurrent.locks.ReentrantReadWriteLock;
Mike Lockwood726d4de2014-10-28 14:06:28 -070058
59import java.io.FileDescriptor;
60import java.io.PrintWriter;
Benjamin Franze8b98922014-11-12 15:57:54 +000061import java.util.HashMap;
62import java.util.Map;
Miao Chou658bf2f2015-06-26 17:14:35 -070063
fredc0f420372012-04-12 00:02:00 -070064class BluetoothManagerService extends IBluetoothManager.Stub {
65 private static final String TAG = "BluetoothManagerService";
Pavlin Radoslavov41401112016-06-27 15:25:18 -070066 private static final boolean DBG = true;
fredc0f420372012-04-12 00:02:00 -070067
fredc0f420372012-04-12 00:02:00 -070068 private static final String BLUETOOTH_ADMIN_PERM = android.Manifest.permission.BLUETOOTH_ADMIN;
69 private static final String BLUETOOTH_PERM = android.Manifest.permission.BLUETOOTH;
fredc0f420372012-04-12 00:02:00 -070070 private static final String ACTION_SERVICE_STATE_CHANGED="com.android.bluetooth.btservice.action.STATE_CHANGED";
71 private static final String EXTRA_ACTION="action";
Zhihai Xud31c3222012-10-31 16:08:57 -070072 private static final String SECURE_SETTINGS_BLUETOOTH_ADDR_VALID="bluetooth_addr_valid";
fredc0f420372012-04-12 00:02:00 -070073 private static final String SECURE_SETTINGS_BLUETOOTH_ADDRESS="bluetooth_address";
74 private static final String SECURE_SETTINGS_BLUETOOTH_NAME="bluetooth_name";
fredc0f420372012-04-12 00:02:00 -070075 private static final int TIMEOUT_BIND_MS = 3000; //Maximum msec to wait for a bind
76 private static final int TIMEOUT_SAVE_MS = 500; //Maximum msec to wait for a save
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +053077 //Maximum msec to wait for service restart
78 private static final int SERVICE_RESTART_TIME_MS = 200;
Zhihai Xudd9d17d2013-01-08 17:05:58 -080079 //Maximum msec to wait for restart due to error
80 private static final int ERROR_RESTART_TIME_MS = 3000;
Zhihai Xu40874a02012-10-08 17:57:03 -070081 //Maximum msec to delay MESSAGE_USER_SWITCHED
82 private static final int USER_SWITCHED_TIME_MS = 200;
Benjamin Franze8b98922014-11-12 15:57:54 +000083 // Delay for the addProxy function in msec
84 private static final int ADD_PROXY_DELAY_MS = 100;
fredc0f420372012-04-12 00:02:00 -070085
86 private static final int MESSAGE_ENABLE = 1;
87 private static final int MESSAGE_DISABLE = 2;
fredc649fe492012-04-19 01:07:18 -070088 private static final int MESSAGE_REGISTER_ADAPTER = 20;
89 private static final int MESSAGE_UNREGISTER_ADAPTER = 21;
90 private static final int MESSAGE_REGISTER_STATE_CHANGE_CALLBACK = 30;
91 private static final int MESSAGE_UNREGISTER_STATE_CHANGE_CALLBACK = 31;
92 private static final int MESSAGE_BLUETOOTH_SERVICE_CONNECTED = 40;
93 private static final int MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED = 41;
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +053094 private static final int MESSAGE_RESTART_BLUETOOTH_SERVICE = 42;
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -070095 private static final int MESSAGE_BLUETOOTH_STATE_CHANGE = 60;
96 private static final int MESSAGE_TIMEOUT_BIND = 100;
97 private static final int MESSAGE_TIMEOUT_UNBIND = 101;
Ajay Panicker4bb48302016-03-31 14:14:27 -070098 private static final int MESSAGE_GET_NAME_AND_ADDRESS = 200;
Zhihai Xu40874a02012-10-08 17:57:03 -070099 private static final int MESSAGE_USER_SWITCHED = 300;
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -0700100 private static final int MESSAGE_USER_UNLOCKED = 301;
Benjamin Franze8b98922014-11-12 15:57:54 +0000101 private static final int MESSAGE_ADD_PROXY_DELAYED = 400;
102 private static final int MESSAGE_BIND_PROFILE_SERVICE = 401;
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -0700103 private static final int MAX_SAVE_RETRIES = 3;
104 private static final int MAX_ERROR_RESTART_RETRIES = 6;
Zhihai Xudd9d17d2013-01-08 17:05:58 -0800105
Zhihai Xu401202b2012-12-03 11:36:21 -0800106 // Bluetooth persisted setting is off
107 private static final int BLUETOOTH_OFF=0;
108 // Bluetooth persisted setting is on
109 // and Airplane mode won't affect Bluetooth state at start up
110 private static final int BLUETOOTH_ON_BLUETOOTH=1;
111 // Bluetooth persisted setting is on
112 // but Airplane mode will affect Bluetooth state at start up
113 // and Airplane mode will have higher priority.
114 private static final int BLUETOOTH_ON_AIRPLANE=2;
fredc0f420372012-04-12 00:02:00 -0700115
Matthew Xieddf7e472013-03-01 18:41:02 -0800116 private static final int SERVICE_IBLUETOOTH = 1;
117 private static final int SERVICE_IBLUETOOTHGATT = 2;
118
fredc0f420372012-04-12 00:02:00 -0700119 private final Context mContext;
Nitin Arorad055adb2015-03-02 15:03:51 -0800120 private static int mBleAppCount = 0;
Matthew Xiecdce0b92012-07-12 19:06:15 -0700121
122 // Locks are not provided for mName and mAddress.
123 // They are accessed in handler or broadcast receiver, same thread context.
fredc0f420372012-04-12 00:02:00 -0700124 private String mAddress;
125 private String mName;
Matthew Xie6fde3092012-07-11 17:10:07 -0700126 private final ContentResolver mContentResolver;
127 private final RemoteCallbackList<IBluetoothManagerCallback> mCallbacks;
128 private final RemoteCallbackList<IBluetoothStateChangeCallback> mStateChangeCallbacks;
Marie Janssen9db28eb2016-01-12 16:05:15 -0800129 private IBinder mBluetoothBinder;
fredc649fe492012-04-19 01:07:18 -0700130 private IBluetooth mBluetooth;
Matthew Xieddf7e472013-03-01 18:41:02 -0800131 private IBluetoothGatt mBluetoothGatt;
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700132 private final ReentrantReadWriteLock mBluetoothLock =
133 new ReentrantReadWriteLock();
fredc649fe492012-04-19 01:07:18 -0700134 private boolean mBinding;
135 private boolean mUnbinding;
Zhihai Xu401202b2012-12-03 11:36:21 -0800136 // used inside handler thread
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700137 private boolean mQuietEnable = false;
Zhihai Xu401202b2012-12-03 11:36:21 -0800138 // configuarion from external IBinder call which is used to
139 // synchronize with broadcast receiver.
140 private boolean mQuietEnableExternal;
141 // configuarion from external IBinder call which is used to
142 // synchronize with broadcast receiver.
143 private boolean mEnableExternal;
144 // used inside handler thread
Zhihai Xu40874a02012-10-08 17:57:03 -0700145 private boolean mEnable;
146 private int mState;
Zhihai Xu40874a02012-10-08 17:57:03 -0700147 private final BluetoothHandler mHandler;
Zhihai Xudd9d17d2013-01-08 17:05:58 -0800148 private int mErrorRecoveryRetryCounter;
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200149 private final int mSystemUiUid;
fredc0f420372012-04-12 00:02:00 -0700150
Benjamin Franze8b98922014-11-12 15:57:54 +0000151 // Save a ProfileServiceConnections object for each of the bound
152 // bluetooth profile services
153 private final Map <Integer, ProfileServiceConnections> mProfileServices =
154 new HashMap <Integer, ProfileServiceConnections>();
155
Svetoslav Ganovf9e2ad02016-06-29 17:31:44 -0700156 private final boolean mPermissionReviewRequired;
157
fredc649fe492012-04-19 01:07:18 -0700158 private void registerForAirplaneMode(IntentFilter filter) {
159 final ContentResolver resolver = mContext.getContentResolver();
Christopher Tatec09cdce2012-09-10 16:50:14 -0700160 final String airplaneModeRadios = Settings.Global.getString(resolver,
161 Settings.Global.AIRPLANE_MODE_RADIOS);
162 final String toggleableRadios = Settings.Global.getString(resolver,
163 Settings.Global.AIRPLANE_MODE_TOGGLEABLE_RADIOS);
fredc649fe492012-04-19 01:07:18 -0700164 boolean mIsAirplaneSensitive = airplaneModeRadios == null ? true :
Christopher Tatec09cdce2012-09-10 16:50:14 -0700165 airplaneModeRadios.contains(Settings.Global.RADIO_BLUETOOTH);
fredc649fe492012-04-19 01:07:18 -0700166 if (mIsAirplaneSensitive) {
167 filter.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED);
168 }
169 }
170
fredcbf072a72012-05-09 16:52:50 -0700171 private final IBluetoothCallback mBluetoothCallback = new IBluetoothCallback.Stub() {
172 @Override
173 public void onBluetoothStateChange(int prevState, int newState) throws RemoteException {
174 Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_STATE_CHANGE,prevState,newState);
175 mHandler.sendMessage(msg);
176 }
177 };
178
179 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
fredc0f420372012-04-12 00:02:00 -0700180 @Override
181 public void onReceive(Context context, Intent intent) {
182 String action = intent.getAction();
fredcbf072a72012-05-09 16:52:50 -0700183 if (BluetoothAdapter.ACTION_LOCAL_NAME_CHANGED.equals(action)) {
fredc0f420372012-04-12 00:02:00 -0700184 String newName = intent.getStringExtra(BluetoothAdapter.EXTRA_LOCAL_NAME);
Jeff Sharkey67609c72016-03-05 14:29:13 -0700185 if (DBG) Slog.d(TAG, "Bluetooth Adapter name changed to " + newName);
fredc0f420372012-04-12 00:02:00 -0700186 if (newName != null) {
187 storeNameAndAddress(newName, null);
188 }
fredc649fe492012-04-19 01:07:18 -0700189 } else if (Intent.ACTION_AIRPLANE_MODE_CHANGED.equals(action)) {
Zhihai Xu401202b2012-12-03 11:36:21 -0800190 synchronized(mReceiver) {
191 if (isBluetoothPersistedStateOn()) {
192 if (isAirplaneModeOn()) {
193 persistBluetoothSetting(BLUETOOTH_ON_AIRPLANE);
194 } else {
195 persistBluetoothSetting(BLUETOOTH_ON_BLUETOOTH);
196 }
197 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800198
199 int st = BluetoothAdapter.STATE_OFF;
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700200 try {
201 mBluetoothLock.readLock().lock();
202 if (mBluetooth != null) {
Nitin Arorad055adb2015-03-02 15:03:51 -0800203 st = mBluetooth.getState();
Nitin Arorad055adb2015-03-02 15:03:51 -0800204 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700205 } catch (RemoteException e) {
206 Slog.e(TAG, "Unable to call getState", e);
207 } finally {
208 mBluetoothLock.readLock().unlock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800209 }
Jeff Sharkey67609c72016-03-05 14:29:13 -0700210 Slog.d(TAG, "state" + st);
Nitin Arorad055adb2015-03-02 15:03:51 -0800211
Zhihai Xu401202b2012-12-03 11:36:21 -0800212 if (isAirplaneModeOn()) {
Nitin Arorad055adb2015-03-02 15:03:51 -0800213 // Clear registered LE apps to force shut-off
214 synchronized (this) {
215 mBleAppCount = 0;
Nitin Arora11f83882015-05-07 18:45:44 -0700216 mBleApps.clear();
Nitin Arorad055adb2015-03-02 15:03:51 -0800217 }
218 if (st == BluetoothAdapter.STATE_BLE_ON) {
219 //if state is BLE_ON make sure you trigger disableBLE part
220 try {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700221 mBluetoothLock.readLock().lock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800222 if (mBluetooth != null) {
223 mBluetooth.onBrEdrDown();
Marie Janssen6a383a72016-10-25 10:47:51 -0700224 mEnable = false;
Nitin Arorad055adb2015-03-02 15:03:51 -0800225 mEnableExternal = false;
226 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700227 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700228 Slog.e(TAG,"Unable to call onBrEdrDown", e);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700229 } finally {
Pavlin Radoslavov7ee53be2016-06-09 12:58:07 -0700230 mBluetoothLock.readLock().unlock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800231 }
232 } else if (st == BluetoothAdapter.STATE_ON){
233 // disable without persisting the setting
Jeff Sharkey67609c72016-03-05 14:29:13 -0700234 Slog.d(TAG, "Calling disable");
Nitin Arorad055adb2015-03-02 15:03:51 -0800235 sendDisableMsg();
236 }
Zhihai Xu401202b2012-12-03 11:36:21 -0800237 } else if (mEnableExternal) {
238 // enable without persisting the setting
Jeff Sharkey67609c72016-03-05 14:29:13 -0700239 Slog.d(TAG, "Calling enable");
Zhihai Xu401202b2012-12-03 11:36:21 -0800240 sendEnableMsg(mQuietEnableExternal);
241 }
fredc649fe492012-04-19 01:07:18 -0700242 }
fredc0f420372012-04-12 00:02:00 -0700243 }
244 }
245 };
246
247 BluetoothManagerService(Context context) {
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700248 mHandler = new BluetoothHandler(IoThread.get().getLooper());
Zhihai Xu40874a02012-10-08 17:57:03 -0700249
fredc0f420372012-04-12 00:02:00 -0700250 mContext = context;
Svetoslav Ganovf9e2ad02016-06-29 17:31:44 -0700251
252 mPermissionReviewRequired = Build.PERMISSIONS_REVIEW_REQUIRED
253 || context.getResources().getBoolean(
254 com.android.internal.R.bool.config_permissionReviewRequired);
255
fredc0f420372012-04-12 00:02:00 -0700256 mBluetooth = null;
Marie Janssen9db28eb2016-01-12 16:05:15 -0800257 mBluetoothBinder = null;
Nitin Arorad055adb2015-03-02 15:03:51 -0800258 mBluetoothGatt = null;
fredc0f420372012-04-12 00:02:00 -0700259 mBinding = false;
260 mUnbinding = false;
Zhihai Xu40874a02012-10-08 17:57:03 -0700261 mEnable = false;
262 mState = BluetoothAdapter.STATE_OFF;
Zhihai Xu401202b2012-12-03 11:36:21 -0800263 mQuietEnableExternal = false;
264 mEnableExternal = false;
fredc0f420372012-04-12 00:02:00 -0700265 mAddress = null;
266 mName = null;
Zhihai Xudd9d17d2013-01-08 17:05:58 -0800267 mErrorRecoveryRetryCounter = 0;
fredc0f420372012-04-12 00:02:00 -0700268 mContentResolver = context.getContentResolver();
Wei Wange4a744b2015-06-11 17:50:29 -0700269 // Observe BLE scan only mode settings change.
270 registerForBleScanModeChange();
fredcd6883532012-04-25 17:46:13 -0700271 mCallbacks = new RemoteCallbackList<IBluetoothManagerCallback>();
272 mStateChangeCallbacks = new RemoteCallbackList<IBluetoothStateChangeCallback>();
Miao Chou658bf2f2015-06-26 17:14:35 -0700273 IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_LOCAL_NAME_CHANGED);
Matthew Xie6fde3092012-07-11 17:10:07 -0700274 registerForAirplaneMode(filter);
Dianne Hackbornd83a0962014-05-02 16:28:33 -0700275 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
Matthew Xie6fde3092012-07-11 17:10:07 -0700276 mContext.registerReceiver(mReceiver, filter);
fredc0f420372012-04-12 00:02:00 -0700277 loadStoredNameAndAddress();
Zhihai Xu401202b2012-12-03 11:36:21 -0800278 if (isBluetoothPersistedStateOn()) {
279 mEnableExternal = true;
fredc0f420372012-04-12 00:02:00 -0700280 }
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200281
282 int sysUiUid = -1;
283 try {
Jeff Sharkeye06b4d12016-01-06 14:51:50 -0700284 sysUiUid = mContext.getPackageManager().getPackageUidAsUser("com.android.systemui",
Jeff Sharkeyc5967e92016-01-07 18:50:29 -0700285 PackageManager.MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM);
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200286 } catch (PackageManager.NameNotFoundException e) {
Joe LaPennaacddf2b2015-09-04 12:52:42 -0700287 // Some platforms, such as wearables do not have a system ui.
Jeff Sharkey67609c72016-03-05 14:29:13 -0700288 Slog.w(TAG, "Unable to resolve SystemUI's UID.", e);
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200289 }
290 mSystemUiUid = sysUiUid;
fredc0f420372012-04-12 00:02:00 -0700291 }
292
fredc649fe492012-04-19 01:07:18 -0700293 /**
294 * Returns true if airplane mode is currently on
295 */
296 private final boolean isAirplaneModeOn() {
Christopher Tatec09cdce2012-09-10 16:50:14 -0700297 return Settings.Global.getInt(mContext.getContentResolver(),
298 Settings.Global.AIRPLANE_MODE_ON, 0) == 1;
fredc649fe492012-04-19 01:07:18 -0700299 }
300
301 /**
302 * Returns true if the Bluetooth saved state is "on"
303 */
304 private final boolean isBluetoothPersistedStateOn() {
Jeff Brownbf6f6f92012-09-25 15:03:20 -0700305 return Settings.Global.getInt(mContentResolver,
Zhihai Xu401202b2012-12-03 11:36:21 -0800306 Settings.Global.BLUETOOTH_ON, 0) != BLUETOOTH_OFF;
307 }
308
309 /**
310 * Returns true if the Bluetooth saved state is BLUETOOTH_ON_BLUETOOTH
311 */
312 private final boolean isBluetoothPersistedStateOnBluetooth() {
313 return Settings.Global.getInt(mContentResolver,
314 Settings.Global.BLUETOOTH_ON, 0) == BLUETOOTH_ON_BLUETOOTH;
fredc649fe492012-04-19 01:07:18 -0700315 }
316
317 /**
318 * Save the Bluetooth on/off state
319 *
320 */
Zhihai Xu401202b2012-12-03 11:36:21 -0800321 private void persistBluetoothSetting(int value) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -0700322 Settings.Global.putInt(mContext.getContentResolver(),
323 Settings.Global.BLUETOOTH_ON,
Zhihai Xu401202b2012-12-03 11:36:21 -0800324 value);
fredc649fe492012-04-19 01:07:18 -0700325 }
326
327 /**
328 * Returns true if the Bluetooth Adapter's name and address is
329 * locally cached
330 * @return
331 */
fredc0f420372012-04-12 00:02:00 -0700332 private boolean isNameAndAddressSet() {
333 return mName !=null && mAddress!= null && mName.length()>0 && mAddress.length()>0;
334 }
335
fredc649fe492012-04-19 01:07:18 -0700336 /**
337 * Retrieve the Bluetooth Adapter's name and address and save it in
338 * in the local cache
339 */
fredc0f420372012-04-12 00:02:00 -0700340 private void loadStoredNameAndAddress() {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700341 if (DBG) Slog.d(TAG, "Loading stored name and address");
Zhihai Xud31c3222012-10-31 16:08:57 -0700342 if (mContext.getResources().getBoolean
343 (com.android.internal.R.bool.config_bluetooth_address_validation) &&
344 Settings.Secure.getInt(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDR_VALID, 0) == 0) {
345 // if the valid flag is not set, don't load the address and name
Jeff Sharkey67609c72016-03-05 14:29:13 -0700346 if (DBG) Slog.d(TAG, "invalid bluetooth name and address stored");
Zhihai Xud31c3222012-10-31 16:08:57 -0700347 return;
348 }
fredc0f420372012-04-12 00:02:00 -0700349 mName = Settings.Secure.getString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_NAME);
350 mAddress = Settings.Secure.getString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDRESS);
Jeff Sharkey67609c72016-03-05 14:29:13 -0700351 if (DBG) Slog.d(TAG, "Stored bluetooth Name=" + mName + ",Address=" + mAddress);
fredc0f420372012-04-12 00:02:00 -0700352 }
353
fredc649fe492012-04-19 01:07:18 -0700354 /**
355 * Save the Bluetooth name and address in the persistent store.
356 * Only non-null values will be saved.
357 * @param name
358 * @param address
359 */
fredc0f420372012-04-12 00:02:00 -0700360 private void storeNameAndAddress(String name, String address) {
361 if (name != null) {
362 Settings.Secure.putString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_NAME, name);
fredc0f420372012-04-12 00:02:00 -0700363 mName = name;
Jeff Sharkey67609c72016-03-05 14:29:13 -0700364 if (DBG) Slog.d(TAG,"Stored Bluetooth name: " +
fredc649fe492012-04-19 01:07:18 -0700365 Settings.Secure.getString(mContentResolver,SECURE_SETTINGS_BLUETOOTH_NAME));
fredc0f420372012-04-12 00:02:00 -0700366 }
367
368 if (address != null) {
369 Settings.Secure.putString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDRESS, address);
fredc0f420372012-04-12 00:02:00 -0700370 mAddress=address;
Jeff Sharkey67609c72016-03-05 14:29:13 -0700371 if (DBG) Slog.d(TAG,"Stored Bluetoothaddress: " +
fredc649fe492012-04-19 01:07:18 -0700372 Settings.Secure.getString(mContentResolver,SECURE_SETTINGS_BLUETOOTH_ADDRESS));
fredc0f420372012-04-12 00:02:00 -0700373 }
Zhihai Xud31c3222012-10-31 16:08:57 -0700374
375 if ((name != null) && (address != null)) {
376 Settings.Secure.putInt(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDR_VALID, 1);
377 }
fredc0f420372012-04-12 00:02:00 -0700378 }
379
380 public IBluetooth registerAdapter(IBluetoothManagerCallback callback){
Natalie Silvanovich55db6462014-05-01 16:12:23 -0700381 if (callback == null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700382 Slog.w(TAG, "Callback is null in registerAdapter");
Natalie Silvanovich55db6462014-05-01 16:12:23 -0700383 return null;
384 }
fredc0f420372012-04-12 00:02:00 -0700385 Message msg = mHandler.obtainMessage(MESSAGE_REGISTER_ADAPTER);
386 msg.obj = callback;
387 mHandler.sendMessage(msg);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700388
389 return mBluetooth;
fredc0f420372012-04-12 00:02:00 -0700390 }
391
392 public void unregisterAdapter(IBluetoothManagerCallback callback) {
Natalie Silvanovich55db6462014-05-01 16:12:23 -0700393 if (callback == null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700394 Slog.w(TAG, "Callback is null in unregisterAdapter");
Natalie Silvanovich55db6462014-05-01 16:12:23 -0700395 return;
396 }
fredc0f420372012-04-12 00:02:00 -0700397 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
398 "Need BLUETOOTH permission");
399 Message msg = mHandler.obtainMessage(MESSAGE_UNREGISTER_ADAPTER);
400 msg.obj = callback;
401 mHandler.sendMessage(msg);
402 }
403
404 public void registerStateChangeCallback(IBluetoothStateChangeCallback callback) {
405 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
406 "Need BLUETOOTH permission");
407 Message msg = mHandler.obtainMessage(MESSAGE_REGISTER_STATE_CHANGE_CALLBACK);
408 msg.obj = callback;
409 mHandler.sendMessage(msg);
410 }
411
412 public void unregisterStateChangeCallback(IBluetoothStateChangeCallback callback) {
413 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
414 "Need BLUETOOTH permission");
415 Message msg = mHandler.obtainMessage(MESSAGE_UNREGISTER_STATE_CHANGE_CALLBACK);
416 msg.obj = callback;
417 mHandler.sendMessage(msg);
418 }
419
420 public boolean isEnabled() {
Zhihai Xu6eb76522012-11-29 15:41:04 -0800421 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
422 (!checkIfCallerIsForegroundUser())) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700423 Slog.w(TAG,"isEnabled(): not allowed for non-active and non system user");
Zhihai Xu40874a02012-10-08 17:57:03 -0700424 return false;
425 }
426
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700427 try {
428 mBluetoothLock.readLock().lock();
429 if (mBluetooth != null) return mBluetooth.isEnabled();
430 } catch (RemoteException e) {
431 Slog.e(TAG, "isEnabled()", e);
432 } finally {
433 mBluetoothLock.readLock().unlock();
fredc0f420372012-04-12 00:02:00 -0700434 }
435 return false;
436 }
437
Nitin Arorad055adb2015-03-02 15:03:51 -0800438 class ClientDeathRecipient implements IBinder.DeathRecipient {
439 public void binderDied() {
Marie Janssen6a383a72016-10-25 10:47:51 -0700440 if (DBG) Slog.d(TAG, "Binder is dead - unregister Ble App");
Nitin Arorad055adb2015-03-02 15:03:51 -0800441 if (mBleAppCount > 0) --mBleAppCount;
442
443 if (mBleAppCount == 0) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700444 if (DBG) Slog.d(TAG, "Disabling LE only mode after application crash");
Nitin Arorad055adb2015-03-02 15:03:51 -0800445 try {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700446 mBluetoothLock.readLock().lock();
Marie Janssen6a383a72016-10-25 10:47:51 -0700447 if (mBluetooth != null &&
448 mBluetooth.getState() == BluetoothAdapter.STATE_BLE_ON) {
449 mEnable = false;
Nitin Arorad055adb2015-03-02 15:03:51 -0800450 mBluetooth.onBrEdrDown();
451 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700452 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700453 Slog.e(TAG,"Unable to call onBrEdrDown", e);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700454 } finally {
455 mBluetoothLock.readLock().unlock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800456 }
457 }
458 }
459 }
460
461 /** Internal death rec list */
462 Map<IBinder, ClientDeathRecipient> mBleApps = new HashMap<IBinder, ClientDeathRecipient>();
463
Wei Wang67d84162015-04-26 17:04:29 -0700464 @Override
465 public boolean isBleScanAlwaysAvailable() {
Marie Janssen6a383a72016-10-25 10:47:51 -0700466 if (isAirplaneModeOn() && !mEnable) {
467 return false;
468 }
Wei Wang67d84162015-04-26 17:04:29 -0700469 try {
470 return (Settings.Global.getInt(mContentResolver,
471 Settings.Global.BLE_SCAN_ALWAYS_AVAILABLE)) != 0;
472 } catch (SettingNotFoundException e) {
473 }
474 return false;
475 }
476
Wei Wange4a744b2015-06-11 17:50:29 -0700477 // Monitor change of BLE scan only mode settings.
478 private void registerForBleScanModeChange() {
479 ContentObserver contentObserver = new ContentObserver(null) {
480 @Override
481 public void onChange(boolean selfChange) {
482 if (!isBleScanAlwaysAvailable()) {
483 disableBleScanMode();
484 clearBleApps();
485 try {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700486 mBluetoothLock.readLock().lock();
Wei Wange4a744b2015-06-11 17:50:29 -0700487 if (mBluetooth != null) mBluetooth.onBrEdrDown();
488 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700489 Slog.e(TAG, "error when disabling bluetooth", e);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700490 } finally {
491 mBluetoothLock.readLock().unlock();
Wei Wange4a744b2015-06-11 17:50:29 -0700492 }
493 }
494 }
495 };
496
497 mContentResolver.registerContentObserver(
498 Settings.Global.getUriFor(Settings.Global.BLE_SCAN_ALWAYS_AVAILABLE),
499 false, contentObserver);
500 }
501
502 // Disable ble scan only mode.
503 private void disableBleScanMode() {
504 try {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700505 mBluetoothLock.writeLock().lock();
Wei Wange4a744b2015-06-11 17:50:29 -0700506 if (mBluetooth != null && (mBluetooth.getState() != BluetoothAdapter.STATE_ON)) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700507 if (DBG) Slog.d(TAG, "Reseting the mEnable flag for clean disable");
Wei Wange4a744b2015-06-11 17:50:29 -0700508 mEnable = false;
509 }
510 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700511 Slog.e(TAG, "getState()", e);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700512 } finally {
513 mBluetoothLock.writeLock().unlock();
Wei Wange4a744b2015-06-11 17:50:29 -0700514 }
515 }
516
Nitin Arorad055adb2015-03-02 15:03:51 -0800517 public int updateBleAppCount(IBinder token, boolean enable) {
518 if (enable) {
519 ClientDeathRecipient r = mBleApps.get(token);
520 if (r == null) {
521 ClientDeathRecipient deathRec = new ClientDeathRecipient();
522 try {
523 token.linkToDeath(deathRec, 0);
524 } catch (RemoteException ex) {
525 throw new IllegalArgumentException("Wake lock is already dead.");
526 }
527 mBleApps.put(token, deathRec);
528 synchronized (this) {
529 ++mBleAppCount;
530 }
Jeff Sharkey67609c72016-03-05 14:29:13 -0700531 if (DBG) Slog.d(TAG, "Registered for death Notification");
Nitin Arorad055adb2015-03-02 15:03:51 -0800532 }
533
534 } else {
535 ClientDeathRecipient r = mBleApps.get(token);
536 if (r != null) {
Wei Wange4a744b2015-06-11 17:50:29 -0700537 // Unregister death recipient as the app goes away.
538 token.unlinkToDeath(r, 0);
Nitin Arorad055adb2015-03-02 15:03:51 -0800539 mBleApps.remove(token);
540 synchronized (this) {
541 if (mBleAppCount > 0) --mBleAppCount;
542 }
Jeff Sharkey67609c72016-03-05 14:29:13 -0700543 if (DBG) Slog.d(TAG, "Unregistered for death Notification");
Nitin Arorad055adb2015-03-02 15:03:51 -0800544 }
545 }
Jeff Sharkey67609c72016-03-05 14:29:13 -0700546 if (DBG) Slog.d(TAG, "Updated BleAppCount" + mBleAppCount);
Nitin Arorad055adb2015-03-02 15:03:51 -0800547 if (mBleAppCount == 0 && mEnable) {
Wei Wange4a744b2015-06-11 17:50:29 -0700548 disableBleScanMode();
Nitin Arorad055adb2015-03-02 15:03:51 -0800549 }
550 return mBleAppCount;
551 }
552
Wei Wange4a744b2015-06-11 17:50:29 -0700553 // Clear all apps using BLE scan only mode.
554 private void clearBleApps() {
555 synchronized (this) {
556 mBleApps.clear();
557 mBleAppCount = 0;
558 }
559 }
560
Nitin Arorad055adb2015-03-02 15:03:51 -0800561 /** @hide*/
562 public boolean isBleAppPresent() {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700563 if (DBG) Slog.d(TAG, "isBleAppPresent() count: " + mBleAppCount);
Nitin Arorad055adb2015-03-02 15:03:51 -0800564 return (mBleAppCount > 0);
565 }
566
567 /**
568 * Action taken when GattService is turned off
569 */
570 private void onBluetoothGattServiceUp() {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700571 if (DBG) Slog.d(TAG,"BluetoothGatt Service is Up");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700572 try {
573 mBluetoothLock.readLock().lock();
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700574 if (isBleAppPresent() == false && mBluetooth != null
575 && mBluetooth.getState() == BluetoothAdapter.STATE_BLE_ON) {
Nitin Arorad055adb2015-03-02 15:03:51 -0800576 mBluetooth.onLeServiceUp();
577
578 // waive WRITE_SECURE_SETTINGS permission check
579 long callingIdentity = Binder.clearCallingIdentity();
580 persistBluetoothSetting(BLUETOOTH_ON_BLUETOOTH);
581 Binder.restoreCallingIdentity(callingIdentity);
582 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700583 } catch (RemoteException e) {
584 Slog.e(TAG,"Unable to call onServiceUp", e);
585 } finally {
586 mBluetoothLock.readLock().unlock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800587 }
588 }
589
590 /**
591 * Inform BluetoothAdapter instances that BREDR part is down
592 * and turn off all service and stack if no LE app needs it
593 */
594 private void sendBrEdrDownCallback() {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700595 if (DBG) Slog.d(TAG,"Calling sendBrEdrDownCallback callbacks");
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700596
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700597 if (mBluetooth == null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700598 Slog.w(TAG, "Bluetooth handle is null");
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700599 return;
600 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800601
602 if (isBleAppPresent() == false) {
603 try {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700604 mBluetoothLock.readLock().lock();
605 if (mBluetooth != null) mBluetooth.onBrEdrDown();
606 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700607 Slog.e(TAG, "Call to onBrEdrDown() failed.", e);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700608 } finally {
609 mBluetoothLock.readLock().unlock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800610 }
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700611 } else {
612 // Need to stay at BLE ON. Disconnect all Gatt connections
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700613 try {
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700614 mBluetoothGatt.unregAll();
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700615 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700616 Slog.e(TAG, "Unable to disconnect all apps.", e);
Nitin Arorad055adb2015-03-02 15:03:51 -0800617 }
618 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800619 }
620
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700621 public boolean enableNoAutoConnect()
622 {
623 mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
624 "Need BLUETOOTH ADMIN permission");
Zhihai Xu40874a02012-10-08 17:57:03 -0700625
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700626 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700627 Slog.d(TAG,"enableNoAutoConnect(): mBluetooth =" + mBluetooth +
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700628 " mBinding = " + mBinding);
629 }
Martijn Coenen8385c5a2012-11-29 10:14:16 -0800630 int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
631
632 if (callingAppId != Process.NFC_UID) {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700633 throw new SecurityException("no permission to enable Bluetooth quietly");
634 }
Martijn Coenen8385c5a2012-11-29 10:14:16 -0800635
Zhihai Xu401202b2012-12-03 11:36:21 -0800636 synchronized(mReceiver) {
637 mQuietEnableExternal = true;
638 mEnableExternal = true;
639 sendEnableMsg(true);
640 }
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700641 return true;
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700642 }
Ajay Panicker4bb48302016-03-31 14:14:27 -0700643
Svetoslav Ganovf9e2ad02016-06-29 17:31:44 -0700644 public boolean enable(String packageName) throws RemoteException {
645 final int callingUid = Binder.getCallingUid();
646 final boolean callerSystem = UserHandle.getAppId(callingUid) == Process.SYSTEM_UID;
647
648 if (!callerSystem) {
649 if (!checkIfCallerIsForegroundUser()) {
650 Slog.w(TAG, "enable(): not allowed for non-active and non system user");
651 return false;
652 }
653
654 mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
655 "Need BLUETOOTH ADMIN permission");
656
657 if (!isEnabled() && mPermissionReviewRequired
658 && startConsentUiIfNeeded(packageName, callingUid,
659 BluetoothAdapter.ACTION_REQUEST_ENABLE)) {
660 return false;
661 }
fredcf2458862012-04-16 15:18:27 -0700662 }
663
Zhihai Xu401202b2012-12-03 11:36:21 -0800664 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700665 Slog.d(TAG,"enable(): mBluetooth =" + mBluetooth +
Sanket Agarwal090bf552016-04-21 14:10:55 -0700666 " mBinding = " + mBinding + " mState = " + mState);
667 }
Zhihai Xu401202b2012-12-03 11:36:21 -0800668
669 synchronized(mReceiver) {
670 mQuietEnableExternal = false;
671 mEnableExternal = true;
672 // waive WRITE_SECURE_SETTINGS permission check
Zhihai Xu401202b2012-12-03 11:36:21 -0800673 sendEnableMsg(false);
674 }
Jeff Sharkey67609c72016-03-05 14:29:13 -0700675 if (DBG) Slog.d(TAG, "enable returning");
Zhihai Xu401202b2012-12-03 11:36:21 -0800676 return true;
fredc0f420372012-04-12 00:02:00 -0700677 }
678
Svetoslav Ganovf9e2ad02016-06-29 17:31:44 -0700679 public boolean disable(String packageName, boolean persist) throws RemoteException {
680 final int callingUid = Binder.getCallingUid();
681 final boolean callerSystem = UserHandle.getAppId(callingUid) == Process.SYSTEM_UID;
Zhihai Xu40874a02012-10-08 17:57:03 -0700682
Svetoslav Ganovf9e2ad02016-06-29 17:31:44 -0700683 if (!callerSystem) {
684 if (!checkIfCallerIsForegroundUser()) {
685 Slog.w(TAG, "disable(): not allowed for non-active and non system user");
686 return false;
687 }
688
689 mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
690 "Need BLUETOOTH ADMIN permission");
691
692 if (isEnabled() && mPermissionReviewRequired
693 && startConsentUiIfNeeded(packageName, callingUid,
694 BluetoothAdapter.ACTION_REQUEST_DISABLE)) {
695 return false;
696 }
Zhihai Xu40874a02012-10-08 17:57:03 -0700697 }
698
fredcf2458862012-04-16 15:18:27 -0700699 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700700 Slog.d(TAG,"disable(): mBluetooth = " + mBluetooth +
Matthew Xiecdce0b92012-07-12 19:06:15 -0700701 " mBinding = " + mBinding);
702 }
fredcf2458862012-04-16 15:18:27 -0700703
Zhihai Xu401202b2012-12-03 11:36:21 -0800704 synchronized(mReceiver) {
705 if (persist) {
706 // waive WRITE_SECURE_SETTINGS permission check
707 long callingIdentity = Binder.clearCallingIdentity();
708 persistBluetoothSetting(BLUETOOTH_OFF);
709 Binder.restoreCallingIdentity(callingIdentity);
710 }
711 mEnableExternal = false;
712 sendDisableMsg();
713 }
fredc0f420372012-04-12 00:02:00 -0700714 return true;
715 }
716
Svetoslav Ganovf9e2ad02016-06-29 17:31:44 -0700717 private boolean startConsentUiIfNeeded(String packageName,
718 int callingUid, String intentAction) throws RemoteException {
719 try {
720 // Validate the package only if we are going to use it
721 ApplicationInfo applicationInfo = mContext.getPackageManager()
722 .getApplicationInfoAsUser(packageName,
723 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
724 UserHandle.getUserId(callingUid));
725 if (applicationInfo.uid != callingUid) {
726 throw new SecurityException("Package " + callingUid
727 + " not in uid " + callingUid);
728 }
729
730 // Legacy apps in permission review mode trigger a user prompt
731 if (applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
732 Intent intent = new Intent(intentAction);
733 mContext.startActivity(intent);
734 return true;
735 }
736 } catch (PackageManager.NameNotFoundException e) {
737 throw new RemoteException(e.getMessage());
738 }
739 return false;
740 }
741
fredc649fe492012-04-19 01:07:18 -0700742 public void unbindAndFinish() {
fredcf2458862012-04-16 15:18:27 -0700743 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700744 Slog.d(TAG,"unbindAndFinish(): " + mBluetooth +
Matthew Xiecdce0b92012-07-12 19:06:15 -0700745 " mBinding = " + mBinding);
fredcf2458862012-04-16 15:18:27 -0700746 }
747
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700748 try {
749 mBluetoothLock.writeLock().lock();
fredc0f420372012-04-12 00:02:00 -0700750 if (mUnbinding) return;
751 mUnbinding = true;
Pavlin Radoslavove47ec142016-06-01 22:25:18 -0700752 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
Pavlin Radoslavov74f60c02016-09-21 17:28:11 -0700753 mHandler.removeMessages(MESSAGE_BIND_PROFILE_SERVICE);
Zhihai Xu40874a02012-10-08 17:57:03 -0700754 if (mBluetooth != null) {
Andre Eisenbach305fdab2015-11-11 21:43:26 -0800755 //Unregister callback object
756 try {
757 mBluetooth.unregisterCallback(mBluetoothCallback);
758 } catch (RemoteException re) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700759 Slog.e(TAG, "Unable to unregister BluetoothCallback",re);
fredcbf072a72012-05-09 16:52:50 -0700760 }
Andre Eisenbach305fdab2015-11-11 21:43:26 -0800761
Jeff Sharkey67609c72016-03-05 14:29:13 -0700762 if (DBG) Slog.d(TAG, "Sending unbind request.");
Marie Janssen9db28eb2016-01-12 16:05:15 -0800763 mBluetoothBinder = null;
fredcd6883532012-04-25 17:46:13 -0700764 mBluetooth = null;
765 //Unbind
fredc0f420372012-04-12 00:02:00 -0700766 mContext.unbindService(mConnection);
fredcd6883532012-04-25 17:46:13 -0700767 mUnbinding = false;
Zhihai Xu40874a02012-10-08 17:57:03 -0700768 mBinding = false;
fredcf2458862012-04-16 15:18:27 -0700769 } else {
770 mUnbinding=false;
fredc0f420372012-04-12 00:02:00 -0700771 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800772 mBluetoothGatt = null;
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700773 } finally {
774 mBluetoothLock.writeLock().unlock();
fredc0f420372012-04-12 00:02:00 -0700775 }
776 }
777
Matthew Xieddf7e472013-03-01 18:41:02 -0800778 public IBluetoothGatt getBluetoothGatt() {
779 // sync protection
780 return mBluetoothGatt;
781 }
782
Benjamin Franze8b98922014-11-12 15:57:54 +0000783 @Override
784 public boolean bindBluetoothProfileService(int bluetoothProfile,
785 IBluetoothProfileServiceConnection proxy) {
786 if (!mEnable) {
787 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700788 Slog.d(TAG, "Trying to bind to profile: " + bluetoothProfile +
Benjamin Franze8b98922014-11-12 15:57:54 +0000789 ", while Bluetooth was disabled");
790 }
791 return false;
792 }
793 synchronized (mProfileServices) {
794 ProfileServiceConnections psc = mProfileServices.get(new Integer(bluetoothProfile));
795 if (psc == null) {
796 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700797 Slog.d(TAG, "Creating new ProfileServiceConnections object for"
Benjamin Franze8b98922014-11-12 15:57:54 +0000798 + " profile: " + bluetoothProfile);
799 }
Benjamin Franz5b614592014-12-09 18:58:45 +0000800
801 if (bluetoothProfile != BluetoothProfile.HEADSET) return false;
802
803 Intent intent = new Intent(IBluetoothHeadset.class.getName());
Benjamin Franze8b98922014-11-12 15:57:54 +0000804 psc = new ProfileServiceConnections(intent);
Benjamin Franz5b614592014-12-09 18:58:45 +0000805 if (!psc.bindService()) return false;
806
Benjamin Franze8b98922014-11-12 15:57:54 +0000807 mProfileServices.put(new Integer(bluetoothProfile), psc);
Benjamin Franze8b98922014-11-12 15:57:54 +0000808 }
809 }
810
811 // Introducing a delay to give the client app time to prepare
812 Message addProxyMsg = mHandler.obtainMessage(MESSAGE_ADD_PROXY_DELAYED);
813 addProxyMsg.arg1 = bluetoothProfile;
814 addProxyMsg.obj = proxy;
815 mHandler.sendMessageDelayed(addProxyMsg, ADD_PROXY_DELAY_MS);
816 return true;
817 }
818
819 @Override
820 public void unbindBluetoothProfileService(int bluetoothProfile,
821 IBluetoothProfileServiceConnection proxy) {
822 synchronized (mProfileServices) {
823 ProfileServiceConnections psc = mProfileServices.get(new Integer(bluetoothProfile));
824 if (psc == null) {
825 return;
826 }
827 psc.removeProxy(proxy);
828 }
829 }
830
831 private void unbindAllBluetoothProfileServices() {
832 synchronized (mProfileServices) {
833 for (Integer i : mProfileServices.keySet()) {
834 ProfileServiceConnections psc = mProfileServices.get(i);
Benjamin Franz5b614592014-12-09 18:58:45 +0000835 try {
836 mContext.unbindService(psc);
837 } catch (IllegalArgumentException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700838 Slog.e(TAG, "Unable to unbind service with intent: " + psc.mIntent, e);
Benjamin Franz5b614592014-12-09 18:58:45 +0000839 }
Benjamin Franze8b98922014-11-12 15:57:54 +0000840 psc.removeAllProxies();
841 }
842 mProfileServices.clear();
843 }
844 }
845
846 /**
Miao Chou658bf2f2015-06-26 17:14:35 -0700847 * Send enable message and set adapter name and address. Called when the boot phase becomes
848 * PHASE_SYSTEM_SERVICES_READY.
849 */
850 public void handleOnBootPhase() {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700851 if (DBG) Slog.d(TAG, "Bluetooth boot completed");
Miao Chou658bf2f2015-06-26 17:14:35 -0700852 if (mEnableExternal && isBluetoothPersistedStateOnBluetooth()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700853 if (DBG) Slog.d(TAG, "Auto-enabling Bluetooth.");
Miao Chou658bf2f2015-06-26 17:14:35 -0700854 sendEnableMsg(mQuietEnableExternal);
Ajay Panickerbf796d82016-03-11 13:47:20 -0800855 } else if (!isNameAndAddressSet()) {
856 if (DBG) Slog.d(TAG, "Getting adapter name and address");
Ajay Panicker4bb48302016-03-31 14:14:27 -0700857 Message getMsg = mHandler.obtainMessage(MESSAGE_GET_NAME_AND_ADDRESS);
858 mHandler.sendMessage(getMsg);
Miao Chou658bf2f2015-06-26 17:14:35 -0700859 }
Miao Chou658bf2f2015-06-26 17:14:35 -0700860 }
861
862 /**
863 * Called when switching to a different foreground user.
864 */
865 public void handleOnSwitchUser(int userHandle) {
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -0700866 if (DBG) Slog.d(TAG, "User " + userHandle + " switched");
867 mHandler.obtainMessage(MESSAGE_USER_SWITCHED, userHandle, 0).sendToTarget();
868 }
869
870 /**
871 * Called when user is unlocked.
872 */
873 public void handleOnUnlockUser(int userHandle) {
874 if (DBG) Slog.d(TAG, "User " + userHandle + " unlocked");
875 mHandler.obtainMessage(MESSAGE_USER_UNLOCKED, userHandle, 0).sendToTarget();
Miao Chou658bf2f2015-06-26 17:14:35 -0700876 }
877
878 /**
Benjamin Franze8b98922014-11-12 15:57:54 +0000879 * This class manages the clients connected to a given ProfileService
880 * and maintains the connection with that service.
881 */
882 final private class ProfileServiceConnections implements ServiceConnection,
883 IBinder.DeathRecipient {
884 final RemoteCallbackList<IBluetoothProfileServiceConnection> mProxies =
885 new RemoteCallbackList <IBluetoothProfileServiceConnection>();
886 IBinder mService;
887 ComponentName mClassName;
888 Intent mIntent;
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700889 boolean mInvokingProxyCallbacks = false;
Benjamin Franze8b98922014-11-12 15:57:54 +0000890
891 ProfileServiceConnections(Intent intent) {
892 mService = null;
893 mClassName = null;
894 mIntent = intent;
895 }
896
Benjamin Franz5b614592014-12-09 18:58:45 +0000897 private boolean bindService() {
898 if (mIntent != null && mService == null &&
899 doBind(mIntent, this, 0, UserHandle.CURRENT_OR_SELF)) {
Benjamin Franze8b98922014-11-12 15:57:54 +0000900 Message msg = mHandler.obtainMessage(MESSAGE_BIND_PROFILE_SERVICE);
901 msg.obj = this;
902 mHandler.sendMessageDelayed(msg, TIMEOUT_BIND_MS);
Benjamin Franz5b614592014-12-09 18:58:45 +0000903 return true;
Benjamin Franze8b98922014-11-12 15:57:54 +0000904 }
Jeff Sharkey67609c72016-03-05 14:29:13 -0700905 Slog.w(TAG, "Unable to bind with intent: " + mIntent);
Benjamin Franz5b614592014-12-09 18:58:45 +0000906 return false;
Benjamin Franze8b98922014-11-12 15:57:54 +0000907 }
908
909 private void addProxy(IBluetoothProfileServiceConnection proxy) {
910 mProxies.register(proxy);
911 if (mService != null) {
912 try{
913 proxy.onServiceConnected(mClassName, mService);
914 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700915 Slog.e(TAG, "Unable to connect to proxy", e);
Benjamin Franze8b98922014-11-12 15:57:54 +0000916 }
917 } else {
918 if (!mHandler.hasMessages(MESSAGE_BIND_PROFILE_SERVICE, this)) {
919 Message msg = mHandler.obtainMessage(MESSAGE_BIND_PROFILE_SERVICE);
920 msg.obj = this;
921 mHandler.sendMessage(msg);
922 }
923 }
924 }
925
926 private void removeProxy(IBluetoothProfileServiceConnection proxy) {
927 if (proxy != null) {
928 if (mProxies.unregister(proxy)) {
929 try {
930 proxy.onServiceDisconnected(mClassName);
931 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700932 Slog.e(TAG, "Unable to disconnect proxy", e);
Benjamin Franze8b98922014-11-12 15:57:54 +0000933 }
934 }
935 } else {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700936 Slog.w(TAG, "Trying to remove a null proxy");
Benjamin Franze8b98922014-11-12 15:57:54 +0000937 }
938 }
939
940 private void removeAllProxies() {
941 onServiceDisconnected(mClassName);
942 mProxies.kill();
943 }
944
945 @Override
946 public void onServiceConnected(ComponentName className, IBinder service) {
947 // remove timeout message
948 mHandler.removeMessages(MESSAGE_BIND_PROFILE_SERVICE, this);
949 mService = service;
950 mClassName = className;
951 try {
952 mService.linkToDeath(this, 0);
953 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700954 Slog.e(TAG, "Unable to linkToDeath", e);
Benjamin Franze8b98922014-11-12 15:57:54 +0000955 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700956
957 if (mInvokingProxyCallbacks) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700958 Slog.e(TAG, "Proxy callbacks already in progress.");
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700959 return;
Benjamin Franze8b98922014-11-12 15:57:54 +0000960 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700961 mInvokingProxyCallbacks = true;
962
963 final int n = mProxies.beginBroadcast();
964 try {
965 for (int i = 0; i < n; i++) {
966 try {
967 mProxies.getBroadcastItem(i).onServiceConnected(className, service);
968 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700969 Slog.e(TAG, "Unable to connect to proxy", e);
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700970 }
971 }
972 } finally {
973 mProxies.finishBroadcast();
974 mInvokingProxyCallbacks = false;
975 }
Benjamin Franze8b98922014-11-12 15:57:54 +0000976 }
977
978 @Override
979 public void onServiceDisconnected(ComponentName className) {
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700980 if (mService == null) return;
Benjamin Franze8b98922014-11-12 15:57:54 +0000981 mService.unlinkToDeath(this, 0);
982 mService = null;
983 mClassName = null;
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700984
985 if (mInvokingProxyCallbacks) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700986 Slog.e(TAG, "Proxy callbacks already in progress.");
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700987 return;
Benjamin Franze8b98922014-11-12 15:57:54 +0000988 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700989 mInvokingProxyCallbacks = true;
990
991 final int n = mProxies.beginBroadcast();
992 try {
993 for (int i = 0; i < n; i++) {
994 try {
995 mProxies.getBroadcastItem(i).onServiceDisconnected(className);
996 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700997 Slog.e(TAG, "Unable to disconnect from proxy", e);
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700998 }
999 }
1000 } finally {
1001 mProxies.finishBroadcast();
1002 mInvokingProxyCallbacks = false;
1003 }
Benjamin Franze8b98922014-11-12 15:57:54 +00001004 }
1005
1006 @Override
1007 public void binderDied() {
1008 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001009 Slog.w(TAG, "Profile service for profile: " + mClassName
Benjamin Franze8b98922014-11-12 15:57:54 +00001010 + " died.");
1011 }
1012 onServiceDisconnected(mClassName);
1013 // Trigger rebind
1014 Message msg = mHandler.obtainMessage(MESSAGE_BIND_PROFILE_SERVICE);
1015 msg.obj = this;
1016 mHandler.sendMessageDelayed(msg, TIMEOUT_BIND_MS);
1017 }
1018 }
1019
fredcbf072a72012-05-09 16:52:50 -07001020 private void sendBluetoothStateCallback(boolean isUp) {
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001021 try {
1022 int n = mStateChangeCallbacks.beginBroadcast();
Jeff Sharkey67609c72016-03-05 14:29:13 -07001023 if (DBG) Slog.d(TAG,"Broadcasting onBluetoothStateChange("+isUp+") to " + n + " receivers.");
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001024 for (int i=0; i <n;i++) {
1025 try {
1026 mStateChangeCallbacks.getBroadcastItem(i).onBluetoothStateChange(isUp);
1027 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001028 Slog.e(TAG, "Unable to call onBluetoothStateChange() on callback #" + i , e);
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001029 }
fredcbf072a72012-05-09 16:52:50 -07001030 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001031 } finally {
1032 mStateChangeCallbacks.finishBroadcast();
fredcbf072a72012-05-09 16:52:50 -07001033 }
fredcbf072a72012-05-09 16:52:50 -07001034 }
1035
1036 /**
Zhihai Xu40874a02012-10-08 17:57:03 -07001037 * Inform BluetoothAdapter instances that Adapter service is up
1038 */
1039 private void sendBluetoothServiceUpCallback() {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001040 if (DBG) Slog.d(TAG,"Calling onBluetoothServiceUp callbacks");
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001041 try {
1042 int n = mCallbacks.beginBroadcast();
Jeff Sharkey67609c72016-03-05 14:29:13 -07001043 Slog.d(TAG,"Broadcasting onBluetoothServiceUp() to " + n + " receivers.");
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001044 for (int i=0; i <n;i++) {
1045 try {
1046 mCallbacks.getBroadcastItem(i).onBluetoothServiceUp(mBluetooth);
1047 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001048 Slog.e(TAG, "Unable to call onBluetoothServiceUp() on callback #" + i, e);
Zhihai Xu40874a02012-10-08 17:57:03 -07001049 }
1050 }
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001051 } finally {
1052 mCallbacks.finishBroadcast();
Zhihai Xu40874a02012-10-08 17:57:03 -07001053 }
1054 }
1055 /**
fredcbf072a72012-05-09 16:52:50 -07001056 * Inform BluetoothAdapter instances that Adapter service is down
1057 */
1058 private void sendBluetoothServiceDownCallback() {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001059 if (DBG) Slog.d(TAG,"Calling onBluetoothServiceDown callbacks");
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001060 try {
1061 int n = mCallbacks.beginBroadcast();
Jeff Sharkey67609c72016-03-05 14:29:13 -07001062 Slog.d(TAG,"Broadcasting onBluetoothServiceDown() to " + n + " receivers.");
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001063 for (int i=0; i <n;i++) {
1064 try {
1065 mCallbacks.getBroadcastItem(i).onBluetoothServiceDown();
1066 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001067 Slog.e(TAG, "Unable to call onBluetoothServiceDown() on callback #" + i, e);
fredcd6883532012-04-25 17:46:13 -07001068 }
1069 }
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001070 } finally {
1071 mCallbacks.finishBroadcast();
fredcd6883532012-04-25 17:46:13 -07001072 }
1073 }
Svet Ganov408abf72015-05-12 19:13:36 -07001074
fredc0f420372012-04-12 00:02:00 -07001075 public String getAddress() {
Matthew Xieaf5ddbf2012-12-04 10:47:43 -08001076 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
Svet Ganov408abf72015-05-12 19:13:36 -07001077 "Need BLUETOOTH permission");
Zhihai Xu40874a02012-10-08 17:57:03 -07001078
Zhihai Xu6eb76522012-11-29 15:41:04 -08001079 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
Svet Ganov408abf72015-05-12 19:13:36 -07001080 (!checkIfCallerIsForegroundUser())) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001081 Slog.w(TAG,"getAddress(): not allowed for non-active and non system user");
Zhihai Xu6eb76522012-11-29 15:41:04 -08001082 return null;
Zhihai Xu40874a02012-10-08 17:57:03 -07001083 }
1084
Svet Ganov408abf72015-05-12 19:13:36 -07001085 if (mContext.checkCallingOrSelfPermission(Manifest.permission.LOCAL_MAC_ADDRESS)
1086 != PackageManager.PERMISSION_GRANTED) {
1087 return BluetoothAdapter.DEFAULT_MAC_ADDRESS;
1088 }
1089
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001090 try {
1091 mBluetoothLock.readLock().lock();
1092 if (mBluetooth != null) return mBluetooth.getAddress();
1093 } catch (RemoteException e) {
1094 Slog.e(TAG, "getAddress(): Unable to retrieve address remotely. Returning cached address", e);
1095 } finally {
1096 mBluetoothLock.readLock().unlock();
fredc116d1d462012-04-20 14:47:08 -07001097 }
Ajay Panickerbf796d82016-03-11 13:47:20 -08001098
Matthew Xiecdce0b92012-07-12 19:06:15 -07001099 // mAddress is accessed from outside.
1100 // It is alright without a lock. Here, bluetooth is off, no other thread is
1101 // changing mAddress
fredc0f420372012-04-12 00:02:00 -07001102 return mAddress;
1103 }
fredc649fe492012-04-19 01:07:18 -07001104
fredc0f420372012-04-12 00:02:00 -07001105 public String getName() {
Matthew Xieaf5ddbf2012-12-04 10:47:43 -08001106 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
1107 "Need BLUETOOTH permission");
Zhihai Xu40874a02012-10-08 17:57:03 -07001108
Zhihai Xu6eb76522012-11-29 15:41:04 -08001109 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
1110 (!checkIfCallerIsForegroundUser())) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001111 Slog.w(TAG,"getName(): not allowed for non-active and non system user");
Zhihai Xu6eb76522012-11-29 15:41:04 -08001112 return null;
Zhihai Xu40874a02012-10-08 17:57:03 -07001113 }
1114
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001115 try {
1116 mBluetoothLock.readLock().lock();
1117 if (mBluetooth != null) return mBluetooth.getName();
1118 } catch (RemoteException e) {
1119 Slog.e(TAG, "getName(): Unable to retrieve name remotely. Returning cached name", e);
1120 } finally {
1121 mBluetoothLock.readLock().unlock();
fredc116d1d462012-04-20 14:47:08 -07001122 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001123
Matthew Xiecdce0b92012-07-12 19:06:15 -07001124 // mName is accessed from outside.
1125 // It alright without a lock. Here, bluetooth is off, no other thread is
1126 // changing mName
fredc0f420372012-04-12 00:02:00 -07001127 return mName;
1128 }
1129
fredc0f420372012-04-12 00:02:00 -07001130 private class BluetoothServiceConnection implements ServiceConnection {
fredc0f420372012-04-12 00:02:00 -07001131 public void onServiceConnected(ComponentName className, IBinder service) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001132 if (DBG) Slog.d(TAG, "BluetoothServiceConnection: " + className.getClassName());
fredc0f420372012-04-12 00:02:00 -07001133 Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_SERVICE_CONNECTED);
Matthew Xieddf7e472013-03-01 18:41:02 -08001134 // TBD if (className.getClassName().equals(IBluetooth.class.getName())) {
1135 if (className.getClassName().equals("com.android.bluetooth.btservice.AdapterService")) {
1136 msg.arg1 = SERVICE_IBLUETOOTH;
1137 // } else if (className.getClassName().equals(IBluetoothGatt.class.getName())) {
1138 } else if (className.getClassName().equals("com.android.bluetooth.gatt.GattService")) {
1139 msg.arg1 = SERVICE_IBLUETOOTHGATT;
1140 } else {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001141 Slog.e(TAG, "Unknown service connected: " + className.getClassName());
Matthew Xieddf7e472013-03-01 18:41:02 -08001142 return;
1143 }
fredc0f420372012-04-12 00:02:00 -07001144 msg.obj = service;
1145 mHandler.sendMessage(msg);
1146 }
1147
1148 public void onServiceDisconnected(ComponentName className) {
fredc0f420372012-04-12 00:02:00 -07001149 // Called if we unexpected disconnected.
Jeff Sharkey67609c72016-03-05 14:29:13 -07001150 if (DBG) Slog.d(TAG, "BluetoothServiceConnection, disconnected: " +
Matthew Xieddf7e472013-03-01 18:41:02 -08001151 className.getClassName());
fredc0f420372012-04-12 00:02:00 -07001152 Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED);
Matthew Xieddf7e472013-03-01 18:41:02 -08001153 if (className.getClassName().equals("com.android.bluetooth.btservice.AdapterService")) {
1154 msg.arg1 = SERVICE_IBLUETOOTH;
1155 } else if (className.getClassName().equals("com.android.bluetooth.gatt.GattService")) {
1156 msg.arg1 = SERVICE_IBLUETOOTHGATT;
1157 } else {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001158 Slog.e(TAG, "Unknown service disconnected: " + className.getClassName());
Matthew Xieddf7e472013-03-01 18:41:02 -08001159 return;
1160 }
fredc0f420372012-04-12 00:02:00 -07001161 mHandler.sendMessage(msg);
1162 }
1163 }
1164
1165 private BluetoothServiceConnection mConnection = new BluetoothServiceConnection();
1166
Zhihai Xu40874a02012-10-08 17:57:03 -07001167 private class BluetoothHandler extends Handler {
Ajay Panicker4bb48302016-03-31 14:14:27 -07001168 boolean mGetNameAddressOnly = false;
1169
Zhihai Xu40874a02012-10-08 17:57:03 -07001170 public BluetoothHandler(Looper looper) {
1171 super(looper);
1172 }
1173
fredc0f420372012-04-12 00:02:00 -07001174 @Override
1175 public void handleMessage(Message msg) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001176 if (DBG) Slog.d (TAG, "Message: " + msg.what);
fredc0f420372012-04-12 00:02:00 -07001177 switch (msg.what) {
Ajay Panicker4bb48302016-03-31 14:14:27 -07001178 case MESSAGE_GET_NAME_AND_ADDRESS:
1179 if (DBG) Slog.d(TAG, "MESSAGE_GET_NAME_AND_ADDRESS");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001180 try {
1181 mBluetoothLock.writeLock().lock();
Ajay Panicker4bb48302016-03-31 14:14:27 -07001182 if ((mBluetooth == null) && (!mBinding)) {
1183 if (DBG) Slog.d(TAG, "Binding to service to get name and address");
1184 mGetNameAddressOnly = true;
1185 Message timeoutMsg = mHandler.obtainMessage(MESSAGE_TIMEOUT_BIND);
1186 mHandler.sendMessageDelayed(timeoutMsg, TIMEOUT_BIND_MS);
1187 Intent i = new Intent(IBluetooth.class.getName());
1188 if (!doBind(i, mConnection,
1189 Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT,
1190 UserHandle.CURRENT)) {
1191 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
1192 } else {
1193 mBinding = true;
1194 }
1195 } else if (mBluetooth != null) {
1196 try {
1197 storeNameAndAddress(mBluetooth.getName(),
1198 mBluetooth.getAddress());
1199 } catch (RemoteException re) {
1200 Slog.e(TAG, "Unable to grab names", re);
1201 }
1202 if (mGetNameAddressOnly && !mEnable) {
1203 unbindAndFinish();
1204 }
1205 mGetNameAddressOnly = false;
1206 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001207 } finally {
1208 mBluetoothLock.writeLock().unlock();
Ajay Panicker4bb48302016-03-31 14:14:27 -07001209 }
1210 break;
1211
Matthew Xiecdce0b92012-07-12 19:06:15 -07001212 case MESSAGE_ENABLE:
fredcf2458862012-04-16 15:18:27 -07001213 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001214 Slog.d(TAG, "MESSAGE_ENABLE: mBluetooth = " + mBluetooth);
fredc649fe492012-04-19 01:07:18 -07001215 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001216 mHandler.removeMessages(MESSAGE_RESTART_BLUETOOTH_SERVICE);
1217 mEnable = true;
Calvin Ona0b91d72016-06-15 17:58:23 -07001218
1219 // Use service interface to get the exact state
1220 try {
1221 mBluetoothLock.readLock().lock();
1222 if (mBluetooth != null) {
1223 int state = mBluetooth.getState();
1224 if (state == BluetoothAdapter.STATE_BLE_ON) {
1225 Slog.w(TAG, "BT is in BLE_ON State");
1226 mBluetooth.onLeServiceUp();
1227 break;
1228 }
1229 }
1230 } catch (RemoteException e) {
1231 Slog.e(TAG, "", e);
1232 } finally {
1233 mBluetoothLock.readLock().unlock();
1234 }
1235
1236 mQuietEnable = (msg.arg1 == 1);
Pavlin Radoslavove47ec142016-06-01 22:25:18 -07001237 if (mBluetooth == null) {
Calvin Ona0b91d72016-06-15 17:58:23 -07001238 handleEnable(mQuietEnable);
Pavlin Radoslavove47ec142016-06-01 22:25:18 -07001239 } else {
1240 //
1241 // We need to wait until transitioned to STATE_OFF and
1242 // the previous Bluetooth process has exited. The
1243 // waiting period has three components:
1244 // (a) Wait until the local state is STATE_OFF. This
1245 // is accomplished by "waitForOnOff(false, true)".
1246 // (b) Wait until the STATE_OFF state is updated to
1247 // all components.
1248 // (c) Wait until the Bluetooth process exits, and
1249 // ActivityManager detects it.
1250 // The waiting for (b) and (c) is accomplished by
1251 // delaying the MESSAGE_RESTART_BLUETOOTH_SERVICE
1252 // message. On slower devices, that delay needs to be
1253 // on the order of (2 * SERVICE_RESTART_TIME_MS).
1254 //
1255 waitForOnOff(false, true);
Pavlin Radoslavove47ec142016-06-01 22:25:18 -07001256 Message restartMsg = mHandler.obtainMessage(
1257 MESSAGE_RESTART_BLUETOOTH_SERVICE);
1258 mHandler.sendMessageDelayed(restartMsg,
1259 2 * SERVICE_RESTART_TIME_MS);
1260 }
fredc649fe492012-04-19 01:07:18 -07001261 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001262
fredc0f420372012-04-12 00:02:00 -07001263 case MESSAGE_DISABLE:
Zhihai Xu40874a02012-10-08 17:57:03 -07001264 mHandler.removeMessages(MESSAGE_RESTART_BLUETOOTH_SERVICE);
1265 if (mEnable && mBluetooth != null) {
1266 waitForOnOff(true, false);
1267 mEnable = false;
Zhihai Xu401202b2012-12-03 11:36:21 -08001268 handleDisable();
Zhihai Xu40874a02012-10-08 17:57:03 -07001269 waitForOnOff(false, false);
1270 } else {
1271 mEnable = false;
Zhihai Xu401202b2012-12-03 11:36:21 -08001272 handleDisable();
Zhihai Xu40874a02012-10-08 17:57:03 -07001273 }
fredc0f420372012-04-12 00:02:00 -07001274 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001275
fredc0f420372012-04-12 00:02:00 -07001276 case MESSAGE_REGISTER_ADAPTER:
1277 {
1278 IBluetoothManagerCallback callback = (IBluetoothManagerCallback) msg.obj;
fredcd6883532012-04-25 17:46:13 -07001279 boolean added = mCallbacks.register(callback);
Jeff Sharkey67609c72016-03-05 14:29:13 -07001280 Slog.d(TAG,"Added callback: " + (callback == null? "null": callback) +":" +added );
fredc0f420372012-04-12 00:02:00 -07001281 }
1282 break;
1283 case MESSAGE_UNREGISTER_ADAPTER:
1284 {
1285 IBluetoothManagerCallback callback = (IBluetoothManagerCallback) msg.obj;
fredcd6883532012-04-25 17:46:13 -07001286 boolean removed = mCallbacks.unregister(callback);
Jeff Sharkey67609c72016-03-05 14:29:13 -07001287 Slog.d(TAG,"Removed callback: " + (callback == null? "null": callback) +":" + removed);
fredc0f420372012-04-12 00:02:00 -07001288 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001289 }
fredc0f420372012-04-12 00:02:00 -07001290 case MESSAGE_REGISTER_STATE_CHANGE_CALLBACK:
1291 {
1292 IBluetoothStateChangeCallback callback = (IBluetoothStateChangeCallback) msg.obj;
Matthew Xie9b693992013-10-10 11:21:40 -07001293 if (callback != null) {
1294 mStateChangeCallbacks.register(callback);
1295 }
fredc0f420372012-04-12 00:02:00 -07001296 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001297 }
fredc0f420372012-04-12 00:02:00 -07001298 case MESSAGE_UNREGISTER_STATE_CHANGE_CALLBACK:
1299 {
1300 IBluetoothStateChangeCallback callback = (IBluetoothStateChangeCallback) msg.obj;
Matthew Xie9b693992013-10-10 11:21:40 -07001301 if (callback != null) {
1302 mStateChangeCallbacks.unregister(callback);
1303 }
fredc0f420372012-04-12 00:02:00 -07001304 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001305 }
Benjamin Franze8b98922014-11-12 15:57:54 +00001306 case MESSAGE_ADD_PROXY_DELAYED:
1307 {
1308 ProfileServiceConnections psc = mProfileServices.get(
1309 new Integer(msg.arg1));
1310 if (psc == null) {
1311 break;
1312 }
1313 IBluetoothProfileServiceConnection proxy =
1314 (IBluetoothProfileServiceConnection) msg.obj;
1315 psc.addProxy(proxy);
1316 break;
1317 }
1318 case MESSAGE_BIND_PROFILE_SERVICE:
1319 {
1320 ProfileServiceConnections psc = (ProfileServiceConnections) msg.obj;
1321 removeMessages(MESSAGE_BIND_PROFILE_SERVICE, msg.obj);
1322 if (psc == null) {
1323 break;
1324 }
1325 psc.bindService();
1326 break;
1327 }
fredc0f420372012-04-12 00:02:00 -07001328 case MESSAGE_BLUETOOTH_SERVICE_CONNECTED:
1329 {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001330 if (DBG) Slog.d(TAG,"MESSAGE_BLUETOOTH_SERVICE_CONNECTED: " + msg.arg1);
fredc0f420372012-04-12 00:02:00 -07001331
1332 IBinder service = (IBinder) msg.obj;
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001333 try {
1334 mBluetoothLock.writeLock().lock();
Matthew Xieddf7e472013-03-01 18:41:02 -08001335 if (msg.arg1 == SERVICE_IBLUETOOTHGATT) {
1336 mBluetoothGatt = IBluetoothGatt.Stub.asInterface(service);
Nitin Arorad055adb2015-03-02 15:03:51 -08001337 onBluetoothGattServiceUp();
Matthew Xieddf7e472013-03-01 18:41:02 -08001338 break;
1339 } // else must be SERVICE_IBLUETOOTH
1340
1341 //Remove timeout
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001342 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
Matthew Xieddf7e472013-03-01 18:41:02 -08001343
fredc0f420372012-04-12 00:02:00 -07001344 mBinding = false;
Marie Janssen9db28eb2016-01-12 16:05:15 -08001345 mBluetoothBinder = service;
fredc0f420372012-04-12 00:02:00 -07001346 mBluetooth = IBluetooth.Stub.asInterface(service);
fredc0f420372012-04-12 00:02:00 -07001347
Ajay Panicker4bb48302016-03-31 14:14:27 -07001348 if (!isNameAndAddressSet()) {
1349 Message getMsg = mHandler.obtainMessage(MESSAGE_GET_NAME_AND_ADDRESS);
1350 mHandler.sendMessage(getMsg);
1351 if (mGetNameAddressOnly) return;
1352 }
1353
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001354 try {
1355 boolean enableHciSnoopLog = (Settings.Secure.getInt(mContentResolver,
1356 Settings.Secure.BLUETOOTH_HCI_LOG, 0) == 1);
1357 if (!mBluetooth.configHciSnoopLog(enableHciSnoopLog)) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001358 Slog.e(TAG,"IBluetooth.configHciSnoopLog return false");
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001359 }
1360 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001361 Slog.e(TAG,"Unable to call configHciSnoopLog", e);
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001362 }
1363
Matthew Xiecdce0b92012-07-12 19:06:15 -07001364 //Register callback object
fredcbf072a72012-05-09 16:52:50 -07001365 try {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001366 mBluetooth.registerCallback(mBluetoothCallback);
1367 } catch (RemoteException re) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001368 Slog.e(TAG, "Unable to register BluetoothCallback",re);
fredcbf072a72012-05-09 16:52:50 -07001369 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001370 //Inform BluetoothAdapter instances that service is up
Zhihai Xu40874a02012-10-08 17:57:03 -07001371 sendBluetoothServiceUpCallback();
1372
Matthew Xiecdce0b92012-07-12 19:06:15 -07001373 //Do enable request
1374 try {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001375 if (mQuietEnable == false) {
1376 if(!mBluetooth.enable()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001377 Slog.e(TAG,"IBluetooth.enable() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001378 }
1379 }
1380 else
1381 {
1382 if(!mBluetooth.enableNoAutoConnect()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001383 Slog.e(TAG,"IBluetooth.enableNoAutoConnect() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001384 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001385 }
1386 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001387 Slog.e(TAG,"Unable to call enable()",e);
Matthew Xiecdce0b92012-07-12 19:06:15 -07001388 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001389 } finally {
1390 mBluetoothLock.writeLock().unlock();
Freda8c6df02012-07-11 10:25:23 -07001391 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001392
1393 if (!mEnable) {
1394 waitForOnOff(true, false);
Zhihai Xu401202b2012-12-03 11:36:21 -08001395 handleDisable();
Zhihai Xu40874a02012-10-08 17:57:03 -07001396 waitForOnOff(false, false);
1397 }
fredc649fe492012-04-19 01:07:18 -07001398 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001399 }
fredc649fe492012-04-19 01:07:18 -07001400 case MESSAGE_TIMEOUT_BIND: {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001401 Slog.e(TAG, "MESSAGE_TIMEOUT_BIND");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001402 mBluetoothLock.writeLock().lock();
1403 mBinding = false;
1404 mBluetoothLock.writeLock().unlock();
1405
fredc649fe492012-04-19 01:07:18 -07001406 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001407 }
fredcbf072a72012-05-09 16:52:50 -07001408 case MESSAGE_BLUETOOTH_STATE_CHANGE:
fredc0f420372012-04-12 00:02:00 -07001409 {
fredcbf072a72012-05-09 16:52:50 -07001410 int prevState = msg.arg1;
1411 int newState = msg.arg2;
Jeff Sharkey67609c72016-03-05 14:29:13 -07001412 if (DBG) Slog.d(TAG, "MESSAGE_BLUETOOTH_STATE_CHANGE: prevState = " + prevState + ", newState=" + newState);
Zhihai Xu40874a02012-10-08 17:57:03 -07001413 mState = newState;
1414 bluetoothStateChangeHandler(prevState, newState);
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001415 // handle error state transition case from TURNING_ON to OFF
1416 // unbind and rebind bluetooth service and enable bluetooth
Nitin Arorad055adb2015-03-02 15:03:51 -08001417 if ((prevState == BluetoothAdapter.STATE_BLE_TURNING_ON) &&
Calvin Ona0b91d72016-06-15 17:58:23 -07001418 (newState == BluetoothAdapter.STATE_OFF) &&
1419 (mBluetooth != null) && mEnable) {
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001420 recoverBluetoothServiceFromError();
1421 }
Nitin Arorad055adb2015-03-02 15:03:51 -08001422 if ((prevState == BluetoothAdapter.STATE_TURNING_ON) &&
Calvin Ona0b91d72016-06-15 17:58:23 -07001423 (newState == BluetoothAdapter.STATE_BLE_ON) &&
1424 (mBluetooth != null) && mEnable) {
Nitin Arorad055adb2015-03-02 15:03:51 -08001425 recoverBluetoothServiceFromError();
1426 }
Calvin Ona0b91d72016-06-15 17:58:23 -07001427 // If we tried to enable BT while BT was in the process of shutting down,
1428 // wait for the BT process to fully tear down and then force a restart
1429 // here. This is a bit of a hack (b/29363429).
1430 if ((prevState == BluetoothAdapter.STATE_BLE_TURNING_OFF) &&
1431 (newState == BluetoothAdapter.STATE_OFF)) {
1432 if (mEnable) {
1433 Slog.d(TAG, "Entering STATE_OFF but mEnabled is true; restarting.");
1434 waitForOnOff(false, true);
1435 Message restartMsg = mHandler.obtainMessage(
1436 MESSAGE_RESTART_BLUETOOTH_SERVICE);
1437 mHandler.sendMessageDelayed(restartMsg, 2 * SERVICE_RESTART_TIME_MS);
1438 }
1439 }
Nitin Arorad055adb2015-03-02 15:03:51 -08001440 if (newState == BluetoothAdapter.STATE_ON ||
Calvin Ona0b91d72016-06-15 17:58:23 -07001441 newState == BluetoothAdapter.STATE_BLE_ON) {
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001442 // bluetooth is working, reset the counter
1443 if (mErrorRecoveryRetryCounter != 0) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001444 Slog.w(TAG, "bluetooth is recovered from error");
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001445 mErrorRecoveryRetryCounter = 0;
1446 }
1447 }
fredc649fe492012-04-19 01:07:18 -07001448 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001449 }
fredc0f420372012-04-12 00:02:00 -07001450 case MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED:
1451 {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001452 Slog.e(TAG, "MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED: " + msg.arg1);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001453 try {
1454 mBluetoothLock.writeLock().lock();
Matthew Xieddf7e472013-03-01 18:41:02 -08001455 if (msg.arg1 == SERVICE_IBLUETOOTH) {
1456 // if service is unbinded already, do nothing and return
1457 if (mBluetooth == null) break;
1458 mBluetooth = null;
1459 } else if (msg.arg1 == SERVICE_IBLUETOOTHGATT) {
1460 mBluetoothGatt = null;
1461 break;
1462 } else {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001463 Slog.e(TAG, "Bad msg.arg1: " + msg.arg1);
Matthew Xieddf7e472013-03-01 18:41:02 -08001464 break;
1465 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001466 } finally {
1467 mBluetoothLock.writeLock().unlock();
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301468 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001469
1470 if (mEnable) {
1471 mEnable = false;
1472 // Send a Bluetooth Restart message
1473 Message restartMsg = mHandler.obtainMessage(
1474 MESSAGE_RESTART_BLUETOOTH_SERVICE);
1475 mHandler.sendMessageDelayed(restartMsg,
1476 SERVICE_RESTART_TIME_MS);
1477 }
1478
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001479 sendBluetoothServiceDownCallback();
Zhihai Xu40874a02012-10-08 17:57:03 -07001480
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001481 // Send BT state broadcast to update
1482 // the BT icon correctly
1483 if ((mState == BluetoothAdapter.STATE_TURNING_ON) ||
Calvin Ona0b91d72016-06-15 17:58:23 -07001484 (mState == BluetoothAdapter.STATE_ON)) {
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001485 bluetoothStateChangeHandler(BluetoothAdapter.STATE_ON,
1486 BluetoothAdapter.STATE_TURNING_OFF);
1487 mState = BluetoothAdapter.STATE_TURNING_OFF;
Zhihai Xu40874a02012-10-08 17:57:03 -07001488 }
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001489 if (mState == BluetoothAdapter.STATE_TURNING_OFF) {
1490 bluetoothStateChangeHandler(BluetoothAdapter.STATE_TURNING_OFF,
1491 BluetoothAdapter.STATE_OFF);
1492 }
1493
1494 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
1495 mState = BluetoothAdapter.STATE_OFF;
fredc649fe492012-04-19 01:07:18 -07001496 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001497 }
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301498 case MESSAGE_RESTART_BLUETOOTH_SERVICE:
1499 {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001500 Slog.d(TAG, "MESSAGE_RESTART_BLUETOOTH_SERVICE:"
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301501 +" Restart IBluetooth service");
1502 /* Enable without persisting the setting as
1503 it doesnt change when IBluetooth
1504 service restarts */
Zhihai Xu40874a02012-10-08 17:57:03 -07001505 mEnable = true;
Zhihai Xu401202b2012-12-03 11:36:21 -08001506 handleEnable(mQuietEnable);
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301507 break;
1508 }
1509
fredc0f420372012-04-12 00:02:00 -07001510 case MESSAGE_TIMEOUT_UNBIND:
1511 {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001512 Slog.e(TAG, "MESSAGE_TIMEOUT_UNBIND");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001513 mBluetoothLock.writeLock().lock();
1514 mUnbinding = false;
1515 mBluetoothLock.writeLock().unlock();
fredc649fe492012-04-19 01:07:18 -07001516 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001517 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001518
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001519 case MESSAGE_USER_SWITCHED: {
1520 if (DBG) Slog.d(TAG, "MESSAGE_USER_SWITCHED");
Zhihai Xu40874a02012-10-08 17:57:03 -07001521 mHandler.removeMessages(MESSAGE_USER_SWITCHED);
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001522
Zhihai Xu40874a02012-10-08 17:57:03 -07001523 /* disable and enable BT when detect a user switch */
1524 if (mEnable && mBluetooth != null) {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001525 try {
1526 mBluetoothLock.readLock().lock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001527 if (mBluetooth != null) {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001528 mBluetooth.unregisterCallback(mBluetoothCallback);
Zhihai Xu40874a02012-10-08 17:57:03 -07001529 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001530 } catch (RemoteException re) {
1531 Slog.e(TAG, "Unable to unregister", re);
1532 } finally {
1533 mBluetoothLock.readLock().unlock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001534 }
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001535
1536 if (mState == BluetoothAdapter.STATE_TURNING_OFF) {
1537 // MESSAGE_USER_SWITCHED happened right after MESSAGE_ENABLE
1538 bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_OFF);
1539 mState = BluetoothAdapter.STATE_OFF;
1540 }
1541 if (mState == BluetoothAdapter.STATE_OFF) {
1542 bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_TURNING_ON);
1543 mState = BluetoothAdapter.STATE_TURNING_ON;
1544 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001545
1546 waitForOnOff(true, false);
1547
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001548 if (mState == BluetoothAdapter.STATE_TURNING_ON) {
1549 bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_ON);
1550 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001551
Benjamin Franze8b98922014-11-12 15:57:54 +00001552 unbindAllBluetoothProfileServices();
Zhihai Xu40874a02012-10-08 17:57:03 -07001553 // disable
Zhihai Xu401202b2012-12-03 11:36:21 -08001554 handleDisable();
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001555 // Pbap service need receive STATE_TURNING_OFF intent to close
1556 bluetoothStateChangeHandler(BluetoothAdapter.STATE_ON,
1557 BluetoothAdapter.STATE_TURNING_OFF);
Zhihai Xu40874a02012-10-08 17:57:03 -07001558
Pavlin Radoslavov41401112016-06-27 15:25:18 -07001559 boolean didDisableTimeout = !waitForOnOff(false, true);
Zhihai Xu40874a02012-10-08 17:57:03 -07001560
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001561 bluetoothStateChangeHandler(BluetoothAdapter.STATE_TURNING_OFF,
Zhihai Xu40874a02012-10-08 17:57:03 -07001562 BluetoothAdapter.STATE_OFF);
Zhihai Xu40874a02012-10-08 17:57:03 -07001563 sendBluetoothServiceDownCallback();
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001564
Pavlin Radoslavove957a8a2016-05-24 15:28:41 -07001565 try {
1566 mBluetoothLock.writeLock().lock();
1567 if (mBluetooth != null) {
1568 mBluetooth = null;
1569 // Unbind
1570 mContext.unbindService(mConnection);
1571 }
1572 mBluetoothGatt = null;
1573 } finally {
1574 mBluetoothLock.writeLock().unlock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001575 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001576
Pavlin Radoslavov41401112016-06-27 15:25:18 -07001577 //
1578 // If disabling Bluetooth times out, wait for an
1579 // additional amount of time to ensure the process is
1580 // shut down completely before attempting to restart.
1581 //
1582 if (didDisableTimeout) {
1583 SystemClock.sleep(3000);
1584 } else {
1585 SystemClock.sleep(100);
1586 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001587
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001588 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
1589 mState = BluetoothAdapter.STATE_OFF;
Zhihai Xu40874a02012-10-08 17:57:03 -07001590 // enable
Zhihai Xu401202b2012-12-03 11:36:21 -08001591 handleEnable(mQuietEnable);
John Spurlock8a985d22014-02-25 09:40:05 -05001592 } else if (mBinding || mBluetooth != null) {
Zhihai Xu40874a02012-10-08 17:57:03 -07001593 Message userMsg = mHandler.obtainMessage(MESSAGE_USER_SWITCHED);
1594 userMsg.arg2 = 1 + msg.arg2;
1595 // if user is switched when service is being binding
1596 // delay sending MESSAGE_USER_SWITCHED
1597 mHandler.sendMessageDelayed(userMsg, USER_SWITCHED_TIME_MS);
1598 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001599 Slog.d(TAG, "delay MESSAGE_USER_SWITCHED " + userMsg.arg2);
Zhihai Xu40874a02012-10-08 17:57:03 -07001600 }
John Spurlock8a985d22014-02-25 09:40:05 -05001601 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001602 break;
1603 }
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001604 case MESSAGE_USER_UNLOCKED: {
1605 if (DBG) Slog.d(TAG, "MESSAGE_USER_UNLOCKED");
1606 mHandler.removeMessages(MESSAGE_USER_SWITCHED);
1607
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001608 if (mEnable && !mBinding && (mBluetooth == null)) {
1609 // We should be connected, but we gave up for some
1610 // reason; maybe the Bluetooth service wasn't encryption
1611 // aware, so try binding again.
1612 if (DBG) Slog.d(TAG, "Enabled but not bound; retrying after unlock");
1613 handleEnable(mQuietEnable);
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001614 }
1615 }
fredc0f420372012-04-12 00:02:00 -07001616 }
1617 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001618 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001619
Zhihai Xu401202b2012-12-03 11:36:21 -08001620 private void handleEnable(boolean quietMode) {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001621 mQuietEnable = quietMode;
1622
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001623 try {
1624 mBluetoothLock.writeLock().lock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001625 if ((mBluetooth == null) && (!mBinding)) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001626 //Start bind timeout and bind
1627 Message timeoutMsg=mHandler.obtainMessage(MESSAGE_TIMEOUT_BIND);
1628 mHandler.sendMessageDelayed(timeoutMsg,TIMEOUT_BIND_MS);
Matthew Xiecdce0b92012-07-12 19:06:15 -07001629 Intent i = new Intent(IBluetooth.class.getName());
Dianne Hackbornce09f5a2014-10-10 15:03:13 -07001630 if (!doBind(i, mConnection,Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT,
1631 UserHandle.CURRENT)) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001632 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
Zhihai Xu40874a02012-10-08 17:57:03 -07001633 } else {
1634 mBinding = true;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001635 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001636 } else if (mBluetooth != null) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001637 //Enable bluetooth
1638 try {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001639 if (!mQuietEnable) {
1640 if(!mBluetooth.enable()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001641 Slog.e(TAG,"IBluetooth.enable() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001642 }
1643 }
1644 else {
1645 if(!mBluetooth.enableNoAutoConnect()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001646 Slog.e(TAG,"IBluetooth.enableNoAutoConnect() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001647 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001648 }
1649 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001650 Slog.e(TAG,"Unable to call enable()",e);
Matthew Xiecdce0b92012-07-12 19:06:15 -07001651 }
1652 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001653 } finally {
1654 mBluetoothLock.writeLock().unlock();
Matthew Xiecdce0b92012-07-12 19:06:15 -07001655 }
1656 }
1657
Dianne Hackborn221ea892013-08-04 16:50:16 -07001658 boolean doBind(Intent intent, ServiceConnection conn, int flags, UserHandle user) {
1659 ComponentName comp = intent.resolveSystemService(mContext.getPackageManager(), 0);
1660 intent.setComponent(comp);
1661 if (comp == null || !mContext.bindServiceAsUser(intent, conn, flags, user)) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001662 Slog.e(TAG, "Fail to bind to: " + intent);
Dianne Hackborn221ea892013-08-04 16:50:16 -07001663 return false;
1664 }
1665 return true;
1666 }
1667
Zhihai Xu401202b2012-12-03 11:36:21 -08001668 private void handleDisable() {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001669 try {
1670 mBluetoothLock.readLock().lock();
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001671 if (mBluetooth != null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001672 if (DBG) Slog.d(TAG,"Sending off request.");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001673 if (!mBluetooth.disable()) {
1674 Slog.e(TAG,"IBluetooth.disable() returned false");
Matthew Xiecdce0b92012-07-12 19:06:15 -07001675 }
1676 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001677 } catch (RemoteException e) {
1678 Slog.e(TAG,"Unable to call disable()",e);
1679 } finally {
1680 mBluetoothLock.readLock().unlock();
Matthew Xiecdce0b92012-07-12 19:06:15 -07001681 }
1682 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001683
1684 private boolean checkIfCallerIsForegroundUser() {
1685 int foregroundUser;
1686 int callingUser = UserHandle.getCallingUserId();
Martijn Coenen8385c5a2012-11-29 10:14:16 -08001687 int callingUid = Binder.getCallingUid();
Zhihai Xu40874a02012-10-08 17:57:03 -07001688 long callingIdentity = Binder.clearCallingIdentity();
Benjamin Franze8b98922014-11-12 15:57:54 +00001689 UserManager um = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
1690 UserInfo ui = um.getProfileParent(callingUser);
1691 int parentUser = (ui != null) ? ui.id : UserHandle.USER_NULL;
Martijn Coenen8385c5a2012-11-29 10:14:16 -08001692 int callingAppId = UserHandle.getAppId(callingUid);
Zhihai Xu40874a02012-10-08 17:57:03 -07001693 boolean valid = false;
1694 try {
1695 foregroundUser = ActivityManager.getCurrentUser();
Martijn Coenen8385c5a2012-11-29 10:14:16 -08001696 valid = (callingUser == foregroundUser) ||
Benjamin Franze8b98922014-11-12 15:57:54 +00001697 parentUser == foregroundUser ||
Adrian Roosbd9a9a52014-08-18 15:31:57 +02001698 callingAppId == Process.NFC_UID ||
1699 callingAppId == mSystemUiUid;
Zhihai Xu40874a02012-10-08 17:57:03 -07001700 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001701 Slog.d(TAG, "checkIfCallerIsForegroundUser: valid=" + valid
Zhihai Xu40874a02012-10-08 17:57:03 -07001702 + " callingUser=" + callingUser
Benjamin Franze8b98922014-11-12 15:57:54 +00001703 + " parentUser=" + parentUser
Zhihai Xu40874a02012-10-08 17:57:03 -07001704 + " foregroundUser=" + foregroundUser);
1705 }
1706 } finally {
1707 Binder.restoreCallingIdentity(callingIdentity);
1708 }
1709 return valid;
1710 }
1711
Nitin Arorad055adb2015-03-02 15:03:51 -08001712 private void sendBleStateChanged(int prevState, int newState) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001713 if (DBG) Slog.d(TAG,"BLE State Change Intent: " + prevState + " -> " + newState);
Nitin Arorad055adb2015-03-02 15:03:51 -08001714 // Send broadcast message to everyone else
1715 Intent intent = new Intent(BluetoothAdapter.ACTION_BLE_STATE_CHANGED);
1716 intent.putExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE, prevState);
1717 intent.putExtra(BluetoothAdapter.EXTRA_STATE, newState);
1718 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1719 mContext.sendBroadcastAsUser(intent, UserHandle.ALL, BLUETOOTH_PERM);
1720 }
1721
Zhihai Xu40874a02012-10-08 17:57:03 -07001722 private void bluetoothStateChangeHandler(int prevState, int newState) {
Nitin Arorad055adb2015-03-02 15:03:51 -08001723 boolean isStandardBroadcast = true;
Zhihai Xu40874a02012-10-08 17:57:03 -07001724 if (prevState != newState) {
1725 //Notify all proxy objects first of adapter state change
Calvin Ona0b91d72016-06-15 17:58:23 -07001726 if (newState == BluetoothAdapter.STATE_BLE_ON ||
1727 newState == BluetoothAdapter.STATE_OFF) {
Nitin Arorad055adb2015-03-02 15:03:51 -08001728 boolean intermediate_off = (prevState == BluetoothAdapter.STATE_TURNING_OFF
1729 && newState == BluetoothAdapter.STATE_BLE_ON);
Zhihai Xu40874a02012-10-08 17:57:03 -07001730
Nitin Arorad055adb2015-03-02 15:03:51 -08001731 if (newState == BluetoothAdapter.STATE_OFF) {
1732 // If Bluetooth is off, send service down event to proxy objects, and unbind
Jeff Sharkey67609c72016-03-05 14:29:13 -07001733 if (DBG) Slog.d(TAG, "Bluetooth is complete turn off");
Pavlin Radoslavove47ec142016-06-01 22:25:18 -07001734 sendBluetoothServiceDownCallback();
1735 unbindAndFinish();
1736 sendBleStateChanged(prevState, newState);
1737 // Don't broadcast as it has already been broadcast before
1738 isStandardBroadcast = false;
Nitin Arorad055adb2015-03-02 15:03:51 -08001739
1740 } else if (!intermediate_off) {
1741 // connect to GattService
Jeff Sharkey67609c72016-03-05 14:29:13 -07001742 if (DBG) Slog.d(TAG, "Bluetooth is in LE only mode");
Nitin Arorad055adb2015-03-02 15:03:51 -08001743 if (mBluetoothGatt != null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001744 if (DBG) Slog.d(TAG, "Calling BluetoothGattServiceUp");
Nitin Arorad055adb2015-03-02 15:03:51 -08001745 onBluetoothGattServiceUp();
1746 } else {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001747 if (DBG) Slog.d(TAG, "Binding Bluetooth GATT service");
Nitin Arorad055adb2015-03-02 15:03:51 -08001748 if (mContext.getPackageManager().hasSystemFeature(
1749 PackageManager.FEATURE_BLUETOOTH_LE)) {
1750 Intent i = new Intent(IBluetoothGatt.class.getName());
1751 doBind(i, mConnection, Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT, UserHandle.CURRENT);
1752 }
1753 }
1754 sendBleStateChanged(prevState, newState);
1755 //Don't broadcase this as std intent
1756 isStandardBroadcast = false;
1757
1758 } else if (intermediate_off){
Jeff Sharkey67609c72016-03-05 14:29:13 -07001759 if (DBG) Slog.d(TAG, "Intermediate off, back to LE only mode");
Nitin Arorad055adb2015-03-02 15:03:51 -08001760 // For LE only mode, broadcast as is
1761 sendBleStateChanged(prevState, newState);
1762 sendBluetoothStateCallback(false); // BT is OFF for general users
1763 // Broadcast as STATE_OFF
1764 newState = BluetoothAdapter.STATE_OFF;
1765 sendBrEdrDownCallback();
Zhihai Xu40874a02012-10-08 17:57:03 -07001766 }
Nitin Arorad055adb2015-03-02 15:03:51 -08001767 } else if (newState == BluetoothAdapter.STATE_ON) {
1768 boolean isUp = (newState==BluetoothAdapter.STATE_ON);
1769 sendBluetoothStateCallback(isUp);
1770 sendBleStateChanged(prevState, newState);
1771
Calvin Ona0b91d72016-06-15 17:58:23 -07001772 } else if (newState == BluetoothAdapter.STATE_BLE_TURNING_ON ||
1773 newState == BluetoothAdapter.STATE_BLE_TURNING_OFF ) {
Nitin Arorad055adb2015-03-02 15:03:51 -08001774 sendBleStateChanged(prevState, newState);
1775 isStandardBroadcast = false;
1776
Calvin Ona0b91d72016-06-15 17:58:23 -07001777 } else if (newState == BluetoothAdapter.STATE_TURNING_ON ||
1778 newState == BluetoothAdapter.STATE_TURNING_OFF) {
Nitin Arorad055adb2015-03-02 15:03:51 -08001779 sendBleStateChanged(prevState, newState);
Zhihai Xu40874a02012-10-08 17:57:03 -07001780 }
1781
Nitin Arorad055adb2015-03-02 15:03:51 -08001782 if (isStandardBroadcast) {
1783 if (prevState == BluetoothAdapter.STATE_BLE_ON) {
1784 // Show prevState of BLE_ON as OFF to standard users
1785 prevState = BluetoothAdapter.STATE_OFF;
1786 }
1787 Intent intent = new Intent(BluetoothAdapter.ACTION_STATE_CHANGED);
1788 intent.putExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE, prevState);
1789 intent.putExtra(BluetoothAdapter.EXTRA_STATE, newState);
1790 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1791 mContext.sendBroadcastAsUser(intent, UserHandle.ALL, BLUETOOTH_PERM);
1792 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001793 }
1794 }
1795
1796 /**
1797 * if on is true, wait for state become ON
1798 * if off is true, wait for state become OFF
1799 * if both on and off are false, wait for state not ON
1800 */
1801 private boolean waitForOnOff(boolean on, boolean off) {
1802 int i = 0;
1803 while (i < 10) {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001804 try {
1805 mBluetoothLock.readLock().lock();
1806 if (mBluetooth == null) break;
1807 if (on) {
1808 if (mBluetooth.getState() == BluetoothAdapter.STATE_ON) return true;
1809 } else if (off) {
1810 if (mBluetooth.getState() == BluetoothAdapter.STATE_OFF) return true;
1811 } else {
1812 if (mBluetooth.getState() != BluetoothAdapter.STATE_ON) return true;
Zhihai Xu40874a02012-10-08 17:57:03 -07001813 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001814 } catch (RemoteException e) {
1815 Slog.e(TAG, "getState()", e);
1816 break;
1817 } finally {
1818 mBluetoothLock.readLock().unlock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001819 }
1820 if (on || off) {
1821 SystemClock.sleep(300);
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07001822 } else {
Zhihai Xu40874a02012-10-08 17:57:03 -07001823 SystemClock.sleep(50);
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07001824 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001825 i++;
1826 }
Jeff Sharkey67609c72016-03-05 14:29:13 -07001827 Slog.e(TAG,"waitForOnOff time out");
Zhihai Xu40874a02012-10-08 17:57:03 -07001828 return false;
1829 }
Zhihai Xu681ae7f2012-11-12 15:14:18 -08001830
Zhihai Xu401202b2012-12-03 11:36:21 -08001831 private void sendDisableMsg() {
1832 mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_DISABLE));
1833 }
1834
1835 private void sendEnableMsg(boolean quietMode) {
1836 mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_ENABLE,
1837 quietMode ? 1 : 0, 0));
1838 }
1839
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001840 private void recoverBluetoothServiceFromError() {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001841 Slog.e(TAG,"recoverBluetoothServiceFromError");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001842 try {
1843 mBluetoothLock.readLock().lock();
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001844 if (mBluetooth != null) {
1845 //Unregister callback object
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001846 mBluetooth.unregisterCallback(mBluetoothCallback);
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001847 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001848 } catch (RemoteException re) {
1849 Slog.e(TAG, "Unable to unregister", re);
1850 } finally {
1851 mBluetoothLock.readLock().unlock();
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001852 }
1853
1854 SystemClock.sleep(500);
1855
1856 // disable
1857 handleDisable();
1858
1859 waitForOnOff(false, true);
1860
1861 sendBluetoothServiceDownCallback();
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001862
Pavlin Radoslavove957a8a2016-05-24 15:28:41 -07001863 try {
1864 mBluetoothLock.writeLock().lock();
1865 if (mBluetooth != null) {
1866 mBluetooth = null;
1867 // Unbind
1868 mContext.unbindService(mConnection);
1869 }
1870 mBluetoothGatt = null;
1871 } finally {
1872 mBluetoothLock.writeLock().unlock();
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001873 }
1874
1875 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
1876 mState = BluetoothAdapter.STATE_OFF;
1877
1878 mEnable = false;
1879
1880 if (mErrorRecoveryRetryCounter++ < MAX_ERROR_RESTART_RETRIES) {
1881 // Send a Bluetooth Restart message to reenable bluetooth
1882 Message restartMsg = mHandler.obtainMessage(
1883 MESSAGE_RESTART_BLUETOOTH_SERVICE);
1884 mHandler.sendMessageDelayed(restartMsg, ERROR_RESTART_TIME_MS);
1885 } else {
1886 // todo: notify user to power down and power up phone to make bluetooth work.
1887 }
1888 }
Mike Lockwood726d4de2014-10-28 14:06:28 -07001889
1890 @Override
Pavlin Radoslavov6e8faff2016-02-23 11:54:37 -08001891 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1892 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DUMP, TAG);
1893 String errorMsg = null;
1894 if (mBluetoothBinder == null) {
1895 errorMsg = "Bluetooth Service not connected";
1896 } else {
1897 try {
1898 mBluetoothBinder.dump(fd, args);
1899 } catch (RemoteException re) {
1900 errorMsg = "RemoteException while calling Bluetooth Service";
1901 }
Mike Lockwood726d4de2014-10-28 14:06:28 -07001902 }
Pavlin Radoslavov6e8faff2016-02-23 11:54:37 -08001903 if (errorMsg != null) {
1904 // Silently return if we are extracting metrics in Protobuf format
1905 if ((args.length > 0) && args[0].startsWith("--proto"))
1906 return;
1907 writer.println(errorMsg);
1908 }
Mike Lockwood726d4de2014-10-28 14:06:28 -07001909 }
fredc0f420372012-04-12 00:02:00 -07001910}