blob: 75b2dd494b68a3fa9a17f1bd931c888b3f1c2b6d [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;
Matthew Xie32ab77b2013-05-08 19:26:57 -070038import android.content.pm.PackageManager;
Benjamin Franze8b98922014-11-12 15:57:54 +000039import android.content.pm.UserInfo;
Wei Wange4a744b2015-06-11 17:50:29 -070040import android.database.ContentObserver;
Zhihai Xu40874a02012-10-08 17:57:03 -070041import android.os.Binder;
Lenka Trochtova13a05192016-12-02 12:19:39 +010042import android.os.Bundle;
fredc0f420372012-04-12 00:02:00 -070043import android.os.Handler;
fredc0f420372012-04-12 00:02:00 -070044import android.os.IBinder;
Zhihai Xu40874a02012-10-08 17:57:03 -070045import android.os.Looper;
fredc0f420372012-04-12 00:02:00 -070046import android.os.Message;
Zhihai Xu40874a02012-10-08 17:57:03 -070047import android.os.Process;
fredcd6883532012-04-25 17:46:13 -070048import android.os.RemoteCallbackList;
fredc0f420372012-04-12 00:02:00 -070049import android.os.RemoteException;
Zhihai Xu40874a02012-10-08 17:57:03 -070050import android.os.SystemClock;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070051import android.os.UserHandle;
Benjamin Franze8b98922014-11-12 15:57:54 +000052import android.os.UserManager;
Lenka Trochtova13a05192016-12-02 12:19:39 +010053import android.os.UserManagerInternal;
54import android.os.UserManagerInternal.UserRestrictionsListener;
fredc0f420372012-04-12 00:02:00 -070055import android.provider.Settings;
Wei Wang67d84162015-04-26 17:04:29 -070056import android.provider.Settings.SettingNotFoundException;
Jeff Sharkey67609c72016-03-05 14:29:13 -070057import android.util.Slog;
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -070058import java.util.concurrent.locks.ReentrantReadWriteLock;
Mike Lockwood726d4de2014-10-28 14:06:28 -070059
60import java.io.FileDescriptor;
61import java.io.PrintWriter;
Marie Janssen2977c3e2016-11-09 12:01:24 -080062import java.util.concurrent.ConcurrentHashMap;
Benjamin Franze8b98922014-11-12 15:57:54 +000063import java.util.HashMap;
64import java.util.Map;
Miao Chou658bf2f2015-06-26 17:14:35 -070065
fredc0f420372012-04-12 00:02:00 -070066class BluetoothManagerService extends IBluetoothManager.Stub {
67 private static final String TAG = "BluetoothManagerService";
Pavlin Radoslavov41401112016-06-27 15:25:18 -070068 private static final boolean DBG = true;
fredc0f420372012-04-12 00:02:00 -070069
fredc0f420372012-04-12 00:02:00 -070070 private static final String BLUETOOTH_ADMIN_PERM = android.Manifest.permission.BLUETOOTH_ADMIN;
71 private static final String BLUETOOTH_PERM = android.Manifest.permission.BLUETOOTH;
fredc0f420372012-04-12 00:02:00 -070072 private static final String ACTION_SERVICE_STATE_CHANGED="com.android.bluetooth.btservice.action.STATE_CHANGED";
73 private static final String EXTRA_ACTION="action";
Zhihai Xud31c3222012-10-31 16:08:57 -070074 private static final String SECURE_SETTINGS_BLUETOOTH_ADDR_VALID="bluetooth_addr_valid";
fredc0f420372012-04-12 00:02:00 -070075 private static final String SECURE_SETTINGS_BLUETOOTH_ADDRESS="bluetooth_address";
76 private static final String SECURE_SETTINGS_BLUETOOTH_NAME="bluetooth_name";
fredc0f420372012-04-12 00:02:00 -070077 private static final int TIMEOUT_BIND_MS = 3000; //Maximum msec to wait for a bind
78 private static final int TIMEOUT_SAVE_MS = 500; //Maximum msec to wait for a save
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +053079 //Maximum msec to wait for service restart
80 private static final int SERVICE_RESTART_TIME_MS = 200;
Zhihai Xudd9d17d2013-01-08 17:05:58 -080081 //Maximum msec to wait for restart due to error
82 private static final int ERROR_RESTART_TIME_MS = 3000;
Zhihai Xu40874a02012-10-08 17:57:03 -070083 //Maximum msec to delay MESSAGE_USER_SWITCHED
84 private static final int USER_SWITCHED_TIME_MS = 200;
Benjamin Franze8b98922014-11-12 15:57:54 +000085 // Delay for the addProxy function in msec
86 private static final int ADD_PROXY_DELAY_MS = 100;
fredc0f420372012-04-12 00:02:00 -070087
88 private static final int MESSAGE_ENABLE = 1;
89 private static final int MESSAGE_DISABLE = 2;
fredc649fe492012-04-19 01:07:18 -070090 private static final int MESSAGE_REGISTER_ADAPTER = 20;
91 private static final int MESSAGE_UNREGISTER_ADAPTER = 21;
92 private static final int MESSAGE_REGISTER_STATE_CHANGE_CALLBACK = 30;
93 private static final int MESSAGE_UNREGISTER_STATE_CHANGE_CALLBACK = 31;
94 private static final int MESSAGE_BLUETOOTH_SERVICE_CONNECTED = 40;
95 private static final int MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED = 41;
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +053096 private static final int MESSAGE_RESTART_BLUETOOTH_SERVICE = 42;
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -070097 private static final int MESSAGE_BLUETOOTH_STATE_CHANGE = 60;
98 private static final int MESSAGE_TIMEOUT_BIND = 100;
99 private static final int MESSAGE_TIMEOUT_UNBIND = 101;
Ajay Panicker4bb48302016-03-31 14:14:27 -0700100 private static final int MESSAGE_GET_NAME_AND_ADDRESS = 200;
Zhihai Xu40874a02012-10-08 17:57:03 -0700101 private static final int MESSAGE_USER_SWITCHED = 300;
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -0700102 private static final int MESSAGE_USER_UNLOCKED = 301;
Benjamin Franze8b98922014-11-12 15:57:54 +0000103 private static final int MESSAGE_ADD_PROXY_DELAYED = 400;
104 private static final int MESSAGE_BIND_PROFILE_SERVICE = 401;
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -0700105 private static final int MAX_SAVE_RETRIES = 3;
106 private static final int MAX_ERROR_RESTART_RETRIES = 6;
Zhihai Xudd9d17d2013-01-08 17:05:58 -0800107
Zhihai Xu401202b2012-12-03 11:36:21 -0800108 // Bluetooth persisted setting is off
109 private static final int BLUETOOTH_OFF=0;
110 // Bluetooth persisted setting is on
111 // and Airplane mode won't affect Bluetooth state at start up
112 private static final int BLUETOOTH_ON_BLUETOOTH=1;
113 // Bluetooth persisted setting is on
114 // but Airplane mode will affect Bluetooth state at start up
115 // and Airplane mode will have higher priority.
116 private static final int BLUETOOTH_ON_AIRPLANE=2;
fredc0f420372012-04-12 00:02:00 -0700117
Matthew Xieddf7e472013-03-01 18:41:02 -0800118 private static final int SERVICE_IBLUETOOTH = 1;
119 private static final int SERVICE_IBLUETOOTHGATT = 2;
120
fredc0f420372012-04-12 00:02:00 -0700121 private final Context mContext;
Matthew Xiecdce0b92012-07-12 19:06:15 -0700122
123 // Locks are not provided for mName and mAddress.
124 // They are accessed in handler or broadcast receiver, same thread context.
fredc0f420372012-04-12 00:02:00 -0700125 private String mAddress;
126 private String mName;
Matthew Xie6fde3092012-07-11 17:10:07 -0700127 private final ContentResolver mContentResolver;
128 private final RemoteCallbackList<IBluetoothManagerCallback> mCallbacks;
129 private final RemoteCallbackList<IBluetoothStateChangeCallback> mStateChangeCallbacks;
Marie Janssen9db28eb2016-01-12 16:05:15 -0800130 private IBinder mBluetoothBinder;
fredc649fe492012-04-19 01:07:18 -0700131 private IBluetooth mBluetooth;
Matthew Xieddf7e472013-03-01 18:41:02 -0800132 private IBluetoothGatt mBluetoothGatt;
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700133 private final ReentrantReadWriteLock mBluetoothLock =
134 new ReentrantReadWriteLock();
fredc649fe492012-04-19 01:07:18 -0700135 private boolean mBinding;
136 private boolean mUnbinding;
Zhihai Xu401202b2012-12-03 11:36:21 -0800137 // used inside handler thread
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700138 private boolean mQuietEnable = false;
Zhihai Xu401202b2012-12-03 11:36:21 -0800139 // configuarion from external IBinder call which is used to
140 // synchronize with broadcast receiver.
141 private boolean mQuietEnableExternal;
142 // configuarion from external IBinder call which is used to
143 // synchronize with broadcast receiver.
144 private boolean mEnableExternal;
145 // used inside handler thread
Zhihai Xu40874a02012-10-08 17:57:03 -0700146 private boolean mEnable;
147 private int mState;
Zhihai Xu40874a02012-10-08 17:57:03 -0700148 private final BluetoothHandler mHandler;
Zhihai Xudd9d17d2013-01-08 17:05:58 -0800149 private int mErrorRecoveryRetryCounter;
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200150 private final int mSystemUiUid;
fredc0f420372012-04-12 00:02:00 -0700151
Benjamin Franze8b98922014-11-12 15:57:54 +0000152 // Save a ProfileServiceConnections object for each of the bound
153 // bluetooth profile services
154 private final Map <Integer, ProfileServiceConnections> mProfileServices =
155 new HashMap <Integer, ProfileServiceConnections>();
156
fredc649fe492012-04-19 01:07:18 -0700157 private void registerForAirplaneMode(IntentFilter filter) {
158 final ContentResolver resolver = mContext.getContentResolver();
Christopher Tatec09cdce2012-09-10 16:50:14 -0700159 final String airplaneModeRadios = Settings.Global.getString(resolver,
160 Settings.Global.AIRPLANE_MODE_RADIOS);
161 final String toggleableRadios = Settings.Global.getString(resolver,
162 Settings.Global.AIRPLANE_MODE_TOGGLEABLE_RADIOS);
fredc649fe492012-04-19 01:07:18 -0700163 boolean mIsAirplaneSensitive = airplaneModeRadios == null ? true :
Christopher Tatec09cdce2012-09-10 16:50:14 -0700164 airplaneModeRadios.contains(Settings.Global.RADIO_BLUETOOTH);
fredc649fe492012-04-19 01:07:18 -0700165 if (mIsAirplaneSensitive) {
166 filter.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED);
167 }
168 }
169
fredcbf072a72012-05-09 16:52:50 -0700170 private final IBluetoothCallback mBluetoothCallback = new IBluetoothCallback.Stub() {
171 @Override
172 public void onBluetoothStateChange(int prevState, int newState) throws RemoteException {
173 Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_STATE_CHANGE,prevState,newState);
174 mHandler.sendMessage(msg);
175 }
176 };
177
Lenka Trochtova13a05192016-12-02 12:19:39 +0100178 private final UserRestrictionsListener mUserRestrictionsListener =
179 new UserRestrictionsListener() {
180 @Override
181 public void onUserRestrictionsChanged(int userId, Bundle newRestrictions,
182 Bundle prevRestrictions) {
183 final boolean bluetoothDisallowed =
184 newRestrictions.getBoolean(UserManager.DISALLOW_BLUETOOTH);
185 if ((mEnable || mEnableExternal) && bluetoothDisallowed) {
186 disable(true);
187 }
188 }
189 };
190
fredcbf072a72012-05-09 16:52:50 -0700191 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
fredc0f420372012-04-12 00:02:00 -0700192 @Override
193 public void onReceive(Context context, Intent intent) {
194 String action = intent.getAction();
fredcbf072a72012-05-09 16:52:50 -0700195 if (BluetoothAdapter.ACTION_LOCAL_NAME_CHANGED.equals(action)) {
fredc0f420372012-04-12 00:02:00 -0700196 String newName = intent.getStringExtra(BluetoothAdapter.EXTRA_LOCAL_NAME);
Jeff Sharkey67609c72016-03-05 14:29:13 -0700197 if (DBG) Slog.d(TAG, "Bluetooth Adapter name changed to " + newName);
fredc0f420372012-04-12 00:02:00 -0700198 if (newName != null) {
199 storeNameAndAddress(newName, null);
200 }
fredc649fe492012-04-19 01:07:18 -0700201 } else if (Intent.ACTION_AIRPLANE_MODE_CHANGED.equals(action)) {
Zhihai Xu401202b2012-12-03 11:36:21 -0800202 synchronized(mReceiver) {
203 if (isBluetoothPersistedStateOn()) {
204 if (isAirplaneModeOn()) {
205 persistBluetoothSetting(BLUETOOTH_ON_AIRPLANE);
206 } else {
207 persistBluetoothSetting(BLUETOOTH_ON_BLUETOOTH);
208 }
209 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800210
211 int st = BluetoothAdapter.STATE_OFF;
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700212 try {
213 mBluetoothLock.readLock().lock();
214 if (mBluetooth != null) {
Nitin Arorad055adb2015-03-02 15:03:51 -0800215 st = mBluetooth.getState();
Nitin Arorad055adb2015-03-02 15:03:51 -0800216 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700217 } catch (RemoteException e) {
218 Slog.e(TAG, "Unable to call getState", e);
219 } finally {
220 mBluetoothLock.readLock().unlock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800221 }
Jeff Sharkey67609c72016-03-05 14:29:13 -0700222 Slog.d(TAG, "state" + st);
Nitin Arorad055adb2015-03-02 15:03:51 -0800223
Zhihai Xu401202b2012-12-03 11:36:21 -0800224 if (isAirplaneModeOn()) {
Nitin Arorad055adb2015-03-02 15:03:51 -0800225 // Clear registered LE apps to force shut-off
Marie Janssen2977c3e2016-11-09 12:01:24 -0800226 clearBleApps();
Nitin Arorad055adb2015-03-02 15:03:51 -0800227 if (st == BluetoothAdapter.STATE_BLE_ON) {
228 //if state is BLE_ON make sure you trigger disableBLE part
229 try {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700230 mBluetoothLock.readLock().lock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800231 if (mBluetooth != null) {
232 mBluetooth.onBrEdrDown();
Marie Janssen6a383a72016-10-25 10:47:51 -0700233 mEnable = false;
Nitin Arorad055adb2015-03-02 15:03:51 -0800234 mEnableExternal = false;
235 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700236 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700237 Slog.e(TAG,"Unable to call onBrEdrDown", e);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700238 } finally {
Pavlin Radoslavov7ee53be2016-06-09 12:58:07 -0700239 mBluetoothLock.readLock().unlock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800240 }
241 } else if (st == BluetoothAdapter.STATE_ON){
242 // disable without persisting the setting
Jeff Sharkey67609c72016-03-05 14:29:13 -0700243 Slog.d(TAG, "Calling disable");
Nitin Arorad055adb2015-03-02 15:03:51 -0800244 sendDisableMsg();
245 }
Zhihai Xu401202b2012-12-03 11:36:21 -0800246 } else if (mEnableExternal) {
247 // enable without persisting the setting
Jeff Sharkey67609c72016-03-05 14:29:13 -0700248 Slog.d(TAG, "Calling enable");
Zhihai Xu401202b2012-12-03 11:36:21 -0800249 sendEnableMsg(mQuietEnableExternal);
250 }
fredc649fe492012-04-19 01:07:18 -0700251 }
fredc0f420372012-04-12 00:02:00 -0700252 }
253 }
254 };
255
256 BluetoothManagerService(Context context) {
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700257 mHandler = new BluetoothHandler(IoThread.get().getLooper());
Zhihai Xu40874a02012-10-08 17:57:03 -0700258
fredc0f420372012-04-12 00:02:00 -0700259 mContext = context;
260 mBluetooth = null;
Marie Janssen9db28eb2016-01-12 16:05:15 -0800261 mBluetoothBinder = null;
Nitin Arorad055adb2015-03-02 15:03:51 -0800262 mBluetoothGatt = null;
fredc0f420372012-04-12 00:02:00 -0700263 mBinding = false;
264 mUnbinding = false;
Zhihai Xu40874a02012-10-08 17:57:03 -0700265 mEnable = false;
266 mState = BluetoothAdapter.STATE_OFF;
Zhihai Xu401202b2012-12-03 11:36:21 -0800267 mQuietEnableExternal = false;
268 mEnableExternal = false;
fredc0f420372012-04-12 00:02:00 -0700269 mAddress = null;
270 mName = null;
Zhihai Xudd9d17d2013-01-08 17:05:58 -0800271 mErrorRecoveryRetryCounter = 0;
fredc0f420372012-04-12 00:02:00 -0700272 mContentResolver = context.getContentResolver();
Wei Wange4a744b2015-06-11 17:50:29 -0700273 // Observe BLE scan only mode settings change.
274 registerForBleScanModeChange();
fredcd6883532012-04-25 17:46:13 -0700275 mCallbacks = new RemoteCallbackList<IBluetoothManagerCallback>();
276 mStateChangeCallbacks = new RemoteCallbackList<IBluetoothStateChangeCallback>();
Miao Chou658bf2f2015-06-26 17:14:35 -0700277 IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_LOCAL_NAME_CHANGED);
Matthew Xie6fde3092012-07-11 17:10:07 -0700278 registerForAirplaneMode(filter);
Dianne Hackbornd83a0962014-05-02 16:28:33 -0700279 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
Matthew Xie6fde3092012-07-11 17:10:07 -0700280 mContext.registerReceiver(mReceiver, filter);
fredc0f420372012-04-12 00:02:00 -0700281 loadStoredNameAndAddress();
Zhihai Xu401202b2012-12-03 11:36:21 -0800282 if (isBluetoothPersistedStateOn()) {
283 mEnableExternal = true;
fredc0f420372012-04-12 00:02:00 -0700284 }
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200285
286 int sysUiUid = -1;
287 try {
Jeff Sharkeye06b4d12016-01-06 14:51:50 -0700288 sysUiUid = mContext.getPackageManager().getPackageUidAsUser("com.android.systemui",
Jeff Sharkeyc5967e92016-01-07 18:50:29 -0700289 PackageManager.MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM);
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200290 } catch (PackageManager.NameNotFoundException e) {
Joe LaPennaacddf2b2015-09-04 12:52:42 -0700291 // Some platforms, such as wearables do not have a system ui.
Jeff Sharkey67609c72016-03-05 14:29:13 -0700292 Slog.w(TAG, "Unable to resolve SystemUI's UID.", e);
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200293 }
294 mSystemUiUid = sysUiUid;
fredc0f420372012-04-12 00:02:00 -0700295 }
296
fredc649fe492012-04-19 01:07:18 -0700297 /**
298 * Returns true if airplane mode is currently on
299 */
300 private final boolean isAirplaneModeOn() {
Christopher Tatec09cdce2012-09-10 16:50:14 -0700301 return Settings.Global.getInt(mContext.getContentResolver(),
302 Settings.Global.AIRPLANE_MODE_ON, 0) == 1;
fredc649fe492012-04-19 01:07:18 -0700303 }
304
305 /**
306 * Returns true if the Bluetooth saved state is "on"
307 */
308 private final boolean isBluetoothPersistedStateOn() {
Jeff Brownbf6f6f92012-09-25 15:03:20 -0700309 return Settings.Global.getInt(mContentResolver,
Andre Eisenbach8c184312016-09-06 18:03:10 -0700310 Settings.Global.BLUETOOTH_ON, BLUETOOTH_ON_BLUETOOTH) != BLUETOOTH_OFF;
Zhihai Xu401202b2012-12-03 11:36:21 -0800311 }
312
313 /**
314 * Returns true if the Bluetooth saved state is BLUETOOTH_ON_BLUETOOTH
315 */
316 private final boolean isBluetoothPersistedStateOnBluetooth() {
317 return Settings.Global.getInt(mContentResolver,
Andre Eisenbach8c184312016-09-06 18:03:10 -0700318 Settings.Global.BLUETOOTH_ON, BLUETOOTH_ON_BLUETOOTH) == BLUETOOTH_ON_BLUETOOTH;
fredc649fe492012-04-19 01:07:18 -0700319 }
320
321 /**
322 * Save the Bluetooth on/off state
323 *
324 */
Zhihai Xu401202b2012-12-03 11:36:21 -0800325 private void persistBluetoothSetting(int value) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -0700326 Settings.Global.putInt(mContext.getContentResolver(),
327 Settings.Global.BLUETOOTH_ON,
Zhihai Xu401202b2012-12-03 11:36:21 -0800328 value);
fredc649fe492012-04-19 01:07:18 -0700329 }
330
331 /**
332 * Returns true if the Bluetooth Adapter's name and address is
333 * locally cached
334 * @return
335 */
fredc0f420372012-04-12 00:02:00 -0700336 private boolean isNameAndAddressSet() {
337 return mName !=null && mAddress!= null && mName.length()>0 && mAddress.length()>0;
338 }
339
fredc649fe492012-04-19 01:07:18 -0700340 /**
341 * Retrieve the Bluetooth Adapter's name and address and save it in
342 * in the local cache
343 */
fredc0f420372012-04-12 00:02:00 -0700344 private void loadStoredNameAndAddress() {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700345 if (DBG) Slog.d(TAG, "Loading stored name and address");
Zhihai Xud31c3222012-10-31 16:08:57 -0700346 if (mContext.getResources().getBoolean
347 (com.android.internal.R.bool.config_bluetooth_address_validation) &&
348 Settings.Secure.getInt(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDR_VALID, 0) == 0) {
349 // if the valid flag is not set, don't load the address and name
Jeff Sharkey67609c72016-03-05 14:29:13 -0700350 if (DBG) Slog.d(TAG, "invalid bluetooth name and address stored");
Zhihai Xud31c3222012-10-31 16:08:57 -0700351 return;
352 }
fredc0f420372012-04-12 00:02:00 -0700353 mName = Settings.Secure.getString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_NAME);
354 mAddress = Settings.Secure.getString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDRESS);
Jeff Sharkey67609c72016-03-05 14:29:13 -0700355 if (DBG) Slog.d(TAG, "Stored bluetooth Name=" + mName + ",Address=" + mAddress);
fredc0f420372012-04-12 00:02:00 -0700356 }
357
fredc649fe492012-04-19 01:07:18 -0700358 /**
359 * Save the Bluetooth name and address in the persistent store.
360 * Only non-null values will be saved.
361 * @param name
362 * @param address
363 */
fredc0f420372012-04-12 00:02:00 -0700364 private void storeNameAndAddress(String name, String address) {
365 if (name != null) {
366 Settings.Secure.putString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_NAME, name);
fredc0f420372012-04-12 00:02:00 -0700367 mName = name;
Jeff Sharkey67609c72016-03-05 14:29:13 -0700368 if (DBG) Slog.d(TAG,"Stored Bluetooth name: " +
fredc649fe492012-04-19 01:07:18 -0700369 Settings.Secure.getString(mContentResolver,SECURE_SETTINGS_BLUETOOTH_NAME));
fredc0f420372012-04-12 00:02:00 -0700370 }
371
372 if (address != null) {
373 Settings.Secure.putString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDRESS, address);
fredc0f420372012-04-12 00:02:00 -0700374 mAddress=address;
Jeff Sharkey67609c72016-03-05 14:29:13 -0700375 if (DBG) Slog.d(TAG,"Stored Bluetoothaddress: " +
fredc649fe492012-04-19 01:07:18 -0700376 Settings.Secure.getString(mContentResolver,SECURE_SETTINGS_BLUETOOTH_ADDRESS));
fredc0f420372012-04-12 00:02:00 -0700377 }
Zhihai Xud31c3222012-10-31 16:08:57 -0700378
379 if ((name != null) && (address != null)) {
380 Settings.Secure.putInt(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDR_VALID, 1);
381 }
fredc0f420372012-04-12 00:02:00 -0700382 }
383
384 public IBluetooth registerAdapter(IBluetoothManagerCallback callback){
Natalie Silvanovich55db6462014-05-01 16:12:23 -0700385 if (callback == null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700386 Slog.w(TAG, "Callback is null in registerAdapter");
Natalie Silvanovich55db6462014-05-01 16:12:23 -0700387 return null;
388 }
fredc0f420372012-04-12 00:02:00 -0700389 Message msg = mHandler.obtainMessage(MESSAGE_REGISTER_ADAPTER);
390 msg.obj = callback;
391 mHandler.sendMessage(msg);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700392
393 return mBluetooth;
fredc0f420372012-04-12 00:02:00 -0700394 }
395
396 public void unregisterAdapter(IBluetoothManagerCallback callback) {
Natalie Silvanovich55db6462014-05-01 16:12:23 -0700397 if (callback == null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700398 Slog.w(TAG, "Callback is null in unregisterAdapter");
Natalie Silvanovich55db6462014-05-01 16:12:23 -0700399 return;
400 }
fredc0f420372012-04-12 00:02:00 -0700401 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
402 "Need BLUETOOTH permission");
403 Message msg = mHandler.obtainMessage(MESSAGE_UNREGISTER_ADAPTER);
404 msg.obj = callback;
405 mHandler.sendMessage(msg);
406 }
407
408 public void registerStateChangeCallback(IBluetoothStateChangeCallback callback) {
409 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
410 "Need BLUETOOTH permission");
411 Message msg = mHandler.obtainMessage(MESSAGE_REGISTER_STATE_CHANGE_CALLBACK);
412 msg.obj = callback;
413 mHandler.sendMessage(msg);
414 }
415
416 public void unregisterStateChangeCallback(IBluetoothStateChangeCallback callback) {
417 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
418 "Need BLUETOOTH permission");
419 Message msg = mHandler.obtainMessage(MESSAGE_UNREGISTER_STATE_CHANGE_CALLBACK);
420 msg.obj = callback;
421 mHandler.sendMessage(msg);
422 }
423
424 public boolean isEnabled() {
Zhihai Xu6eb76522012-11-29 15:41:04 -0800425 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
426 (!checkIfCallerIsForegroundUser())) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700427 Slog.w(TAG,"isEnabled(): not allowed for non-active and non system user");
Zhihai Xu40874a02012-10-08 17:57:03 -0700428 return false;
429 }
430
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700431 try {
432 mBluetoothLock.readLock().lock();
433 if (mBluetooth != null) return mBluetooth.isEnabled();
434 } catch (RemoteException e) {
435 Slog.e(TAG, "isEnabled()", e);
436 } finally {
437 mBluetoothLock.readLock().unlock();
fredc0f420372012-04-12 00:02:00 -0700438 }
439 return false;
440 }
441
Christine Hallstrom995c90a2016-05-25 15:49:08 -0700442 public int getState() {
443 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
444 (!checkIfCallerIsForegroundUser())) {
445 Slog.w(TAG, "getState(): not allowed for non-active and non system user");
446 return BluetoothAdapter.STATE_OFF;
447 }
448
449 try {
450 mBluetoothLock.readLock().lock();
451 if (mBluetooth != null) return mBluetooth.getState();
452 } catch (RemoteException e) {
453 Slog.e(TAG, "getState()", e);
454 } finally {
455 mBluetoothLock.readLock().unlock();
456 }
457 return BluetoothAdapter.STATE_OFF;
458 }
459
Nitin Arorad055adb2015-03-02 15:03:51 -0800460 class ClientDeathRecipient implements IBinder.DeathRecipient {
461 public void binderDied() {
Marie Janssen6a383a72016-10-25 10:47:51 -0700462 if (DBG) Slog.d(TAG, "Binder is dead - unregister Ble App");
Marie Janssen2977c3e2016-11-09 12:01:24 -0800463 if (isBleAppPresent()) {
464 // Nothing to do, another app is here.
465 return;
466 }
467 if (DBG) Slog.d(TAG, "Disabling LE only mode after application crash");
468 try {
469 mBluetoothLock.readLock().lock();
470 if (mBluetooth != null &&
471 mBluetooth.getState() == BluetoothAdapter.STATE_BLE_ON) {
472 mEnable = false;
473 mBluetooth.onBrEdrDown();
Nitin Arorad055adb2015-03-02 15:03:51 -0800474 }
Marie Janssen2977c3e2016-11-09 12:01:24 -0800475 } catch (RemoteException e) {
476 Slog.e(TAG,"Unable to call onBrEdrDown", e);
477 } finally {
478 mBluetoothLock.readLock().unlock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800479 }
480 }
481 }
482
483 /** Internal death rec list */
Marie Janssen2977c3e2016-11-09 12:01:24 -0800484 Map<IBinder, ClientDeathRecipient> mBleApps = new ConcurrentHashMap<IBinder, ClientDeathRecipient>();
Nitin Arorad055adb2015-03-02 15:03:51 -0800485
Wei Wang67d84162015-04-26 17:04:29 -0700486 @Override
487 public boolean isBleScanAlwaysAvailable() {
Marie Janssen6a383a72016-10-25 10:47:51 -0700488 if (isAirplaneModeOn() && !mEnable) {
489 return false;
490 }
Wei Wang67d84162015-04-26 17:04:29 -0700491 try {
492 return (Settings.Global.getInt(mContentResolver,
493 Settings.Global.BLE_SCAN_ALWAYS_AVAILABLE)) != 0;
494 } catch (SettingNotFoundException e) {
495 }
496 return false;
497 }
498
Wei Wange4a744b2015-06-11 17:50:29 -0700499 // Monitor change of BLE scan only mode settings.
500 private void registerForBleScanModeChange() {
501 ContentObserver contentObserver = new ContentObserver(null) {
502 @Override
503 public void onChange(boolean selfChange) {
Marie Janssen2977c3e2016-11-09 12:01:24 -0800504 if (isBleScanAlwaysAvailable()) {
505 // Nothing to do
506 return;
507 }
508 // BLE scan is not available.
509 disableBleScanMode();
510 clearBleApps();
511 try {
512 mBluetoothLock.readLock().lock();
513 if (mBluetooth != null) mBluetooth.onBrEdrDown();
514 } catch (RemoteException e) {
515 Slog.e(TAG, "error when disabling bluetooth", e);
516 } finally {
517 mBluetoothLock.readLock().unlock();
Wei Wange4a744b2015-06-11 17:50:29 -0700518 }
519 }
520 };
521
522 mContentResolver.registerContentObserver(
523 Settings.Global.getUriFor(Settings.Global.BLE_SCAN_ALWAYS_AVAILABLE),
524 false, contentObserver);
525 }
526
527 // Disable ble scan only mode.
528 private void disableBleScanMode() {
529 try {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700530 mBluetoothLock.writeLock().lock();
Wei Wange4a744b2015-06-11 17:50:29 -0700531 if (mBluetooth != null && (mBluetooth.getState() != BluetoothAdapter.STATE_ON)) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700532 if (DBG) Slog.d(TAG, "Reseting the mEnable flag for clean disable");
Wei Wange4a744b2015-06-11 17:50:29 -0700533 mEnable = false;
534 }
535 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700536 Slog.e(TAG, "getState()", e);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700537 } finally {
538 mBluetoothLock.writeLock().unlock();
Wei Wange4a744b2015-06-11 17:50:29 -0700539 }
540 }
541
Nitin Arorad055adb2015-03-02 15:03:51 -0800542 public int updateBleAppCount(IBinder token, boolean enable) {
543 if (enable) {
544 ClientDeathRecipient r = mBleApps.get(token);
545 if (r == null) {
546 ClientDeathRecipient deathRec = new ClientDeathRecipient();
547 try {
548 token.linkToDeath(deathRec, 0);
549 } catch (RemoteException ex) {
550 throw new IllegalArgumentException("Wake lock is already dead.");
551 }
552 mBleApps.put(token, deathRec);
Jeff Sharkey67609c72016-03-05 14:29:13 -0700553 if (DBG) Slog.d(TAG, "Registered for death Notification");
Nitin Arorad055adb2015-03-02 15:03:51 -0800554 }
555
556 } else {
557 ClientDeathRecipient r = mBleApps.get(token);
558 if (r != null) {
Wei Wange4a744b2015-06-11 17:50:29 -0700559 // Unregister death recipient as the app goes away.
560 token.unlinkToDeath(r, 0);
Nitin Arorad055adb2015-03-02 15:03:51 -0800561 mBleApps.remove(token);
Jeff Sharkey67609c72016-03-05 14:29:13 -0700562 if (DBG) Slog.d(TAG, "Unregistered for death Notification");
Nitin Arorad055adb2015-03-02 15:03:51 -0800563 }
564 }
Marie Janssen2977c3e2016-11-09 12:01:24 -0800565 int appCount = mBleApps.size();
566 if (DBG) Slog.d(TAG, appCount + " registered Ble Apps");
567 if (appCount == 0 && mEnable) {
Wei Wange4a744b2015-06-11 17:50:29 -0700568 disableBleScanMode();
Nitin Arorad055adb2015-03-02 15:03:51 -0800569 }
Marie Janssen2977c3e2016-11-09 12:01:24 -0800570 return appCount;
Nitin Arorad055adb2015-03-02 15:03:51 -0800571 }
572
Wei Wange4a744b2015-06-11 17:50:29 -0700573 // Clear all apps using BLE scan only mode.
574 private void clearBleApps() {
Marie Janssen2977c3e2016-11-09 12:01:24 -0800575 mBleApps.clear();
Wei Wange4a744b2015-06-11 17:50:29 -0700576 }
577
Nitin Arorad055adb2015-03-02 15:03:51 -0800578 /** @hide*/
579 public boolean isBleAppPresent() {
Marie Janssen2977c3e2016-11-09 12:01:24 -0800580 if (DBG) Slog.d(TAG, "isBleAppPresent() count: " + mBleApps.size());
581 return mBleApps.size() > 0;
Nitin Arorad055adb2015-03-02 15:03:51 -0800582 }
583
584 /**
585 * Action taken when GattService is turned off
586 */
587 private void onBluetoothGattServiceUp() {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700588 if (DBG) Slog.d(TAG,"BluetoothGatt Service is Up");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700589 try {
590 mBluetoothLock.readLock().lock();
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700591 if (isBleAppPresent() == false && mBluetooth != null
592 && mBluetooth.getState() == BluetoothAdapter.STATE_BLE_ON) {
Nitin Arorad055adb2015-03-02 15:03:51 -0800593 mBluetooth.onLeServiceUp();
594
595 // waive WRITE_SECURE_SETTINGS permission check
596 long callingIdentity = Binder.clearCallingIdentity();
597 persistBluetoothSetting(BLUETOOTH_ON_BLUETOOTH);
598 Binder.restoreCallingIdentity(callingIdentity);
599 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700600 } catch (RemoteException e) {
601 Slog.e(TAG,"Unable to call onServiceUp", e);
602 } finally {
603 mBluetoothLock.readLock().unlock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800604 }
605 }
606
607 /**
608 * Inform BluetoothAdapter instances that BREDR part is down
609 * and turn off all service and stack if no LE app needs it
610 */
611 private void sendBrEdrDownCallback() {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700612 if (DBG) Slog.d(TAG,"Calling sendBrEdrDownCallback callbacks");
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700613
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700614 if (mBluetooth == null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700615 Slog.w(TAG, "Bluetooth handle is null");
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700616 return;
617 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800618
619 if (isBleAppPresent() == false) {
620 try {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700621 mBluetoothLock.readLock().lock();
622 if (mBluetooth != null) mBluetooth.onBrEdrDown();
623 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700624 Slog.e(TAG, "Call to onBrEdrDown() failed.", e);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700625 } finally {
626 mBluetoothLock.readLock().unlock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800627 }
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700628 } else {
629 // Need to stay at BLE ON. Disconnect all Gatt connections
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700630 try {
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700631 mBluetoothGatt.unregAll();
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700632 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700633 Slog.e(TAG, "Unable to disconnect all apps.", e);
Nitin Arorad055adb2015-03-02 15:03:51 -0800634 }
635 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800636 }
637
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700638 public boolean enableNoAutoConnect()
639 {
Lenka Trochtova13a05192016-12-02 12:19:39 +0100640 if (isBluetoothDisallowed()) {
641 if (DBG) {
642 Slog.d(TAG, "enableNoAutoConnect(): not enabling - bluetooth disallowed");
643 }
644 return false;
645 }
646
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700647 mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
648 "Need BLUETOOTH ADMIN permission");
Zhihai Xu40874a02012-10-08 17:57:03 -0700649
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700650 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700651 Slog.d(TAG,"enableNoAutoConnect(): mBluetooth =" + mBluetooth +
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700652 " mBinding = " + mBinding);
653 }
Martijn Coenen8385c5a2012-11-29 10:14:16 -0800654 int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
655
656 if (callingAppId != Process.NFC_UID) {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700657 throw new SecurityException("no permission to enable Bluetooth quietly");
658 }
Martijn Coenen8385c5a2012-11-29 10:14:16 -0800659
Zhihai Xu401202b2012-12-03 11:36:21 -0800660 synchronized(mReceiver) {
661 mQuietEnableExternal = true;
662 mEnableExternal = true;
663 sendEnableMsg(true);
664 }
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700665 return true;
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700666 }
Ajay Panicker4bb48302016-03-31 14:14:27 -0700667
fredc0f420372012-04-12 00:02:00 -0700668 public boolean enable() {
Lenka Trochtova13a05192016-12-02 12:19:39 +0100669 if (isBluetoothDisallowed()) {
670 if (DBG) {
671 Slog.d(TAG,"enable(): not enabling - bluetooth disallowed");
672 }
673 return false;
674 }
675
Zhihai Xu6eb76522012-11-29 15:41:04 -0800676 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
677 (!checkIfCallerIsForegroundUser())) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700678 Slog.w(TAG,"enable(): not allowed for non-active and non system user");
Zhihai Xu40874a02012-10-08 17:57:03 -0700679 return false;
fredcf2458862012-04-16 15:18:27 -0700680 }
681
Zhihai Xu401202b2012-12-03 11:36:21 -0800682 mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
683 "Need BLUETOOTH ADMIN permission");
684 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700685 Slog.d(TAG,"enable(): mBluetooth =" + mBluetooth +
Sanket Agarwal090bf552016-04-21 14:10:55 -0700686 " mBinding = " + mBinding + " mState = " + mState);
687 }
Zhihai Xu401202b2012-12-03 11:36:21 -0800688
689 synchronized(mReceiver) {
690 mQuietEnableExternal = false;
691 mEnableExternal = true;
692 // waive WRITE_SECURE_SETTINGS permission check
Zhihai Xu401202b2012-12-03 11:36:21 -0800693 sendEnableMsg(false);
694 }
Jeff Sharkey67609c72016-03-05 14:29:13 -0700695 if (DBG) Slog.d(TAG, "enable returning");
Zhihai Xu401202b2012-12-03 11:36:21 -0800696 return true;
fredc0f420372012-04-12 00:02:00 -0700697 }
698
699 public boolean disable(boolean persist) {
700 mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
701 "Need BLUETOOTH ADMIN permissicacheNameAndAddresson");
Zhihai Xu40874a02012-10-08 17:57:03 -0700702
Zhihai Xu6eb76522012-11-29 15:41:04 -0800703 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
704 (!checkIfCallerIsForegroundUser())) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700705 Slog.w(TAG,"disable(): not allowed for non-active and non system user");
Zhihai Xu40874a02012-10-08 17:57:03 -0700706 return false;
707 }
708
fredcf2458862012-04-16 15:18:27 -0700709 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700710 Slog.d(TAG,"disable(): mBluetooth = " + mBluetooth +
Matthew Xiecdce0b92012-07-12 19:06:15 -0700711 " mBinding = " + mBinding);
712 }
fredcf2458862012-04-16 15:18:27 -0700713
Zhihai Xu401202b2012-12-03 11:36:21 -0800714 synchronized(mReceiver) {
715 if (persist) {
716 // waive WRITE_SECURE_SETTINGS permission check
717 long callingIdentity = Binder.clearCallingIdentity();
718 persistBluetoothSetting(BLUETOOTH_OFF);
719 Binder.restoreCallingIdentity(callingIdentity);
720 }
721 mEnableExternal = false;
722 sendDisableMsg();
723 }
fredc0f420372012-04-12 00:02:00 -0700724 return true;
725 }
726
fredc649fe492012-04-19 01:07:18 -0700727 public void unbindAndFinish() {
fredcf2458862012-04-16 15:18:27 -0700728 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700729 Slog.d(TAG,"unbindAndFinish(): " + mBluetooth +
Matthew Xiecdce0b92012-07-12 19:06:15 -0700730 " mBinding = " + mBinding);
fredcf2458862012-04-16 15:18:27 -0700731 }
732
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700733 try {
734 mBluetoothLock.writeLock().lock();
fredc0f420372012-04-12 00:02:00 -0700735 if (mUnbinding) return;
736 mUnbinding = true;
Pavlin Radoslavove47ec142016-06-01 22:25:18 -0700737 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
Pavlin Radoslavov74f60c02016-09-21 17:28:11 -0700738 mHandler.removeMessages(MESSAGE_BIND_PROFILE_SERVICE);
Zhihai Xu40874a02012-10-08 17:57:03 -0700739 if (mBluetooth != null) {
Andre Eisenbach305fdab2015-11-11 21:43:26 -0800740 //Unregister callback object
741 try {
742 mBluetooth.unregisterCallback(mBluetoothCallback);
743 } catch (RemoteException re) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700744 Slog.e(TAG, "Unable to unregister BluetoothCallback",re);
fredcbf072a72012-05-09 16:52:50 -0700745 }
Andre Eisenbach305fdab2015-11-11 21:43:26 -0800746
Jeff Sharkey67609c72016-03-05 14:29:13 -0700747 if (DBG) Slog.d(TAG, "Sending unbind request.");
Marie Janssen9db28eb2016-01-12 16:05:15 -0800748 mBluetoothBinder = null;
fredcd6883532012-04-25 17:46:13 -0700749 mBluetooth = null;
750 //Unbind
fredc0f420372012-04-12 00:02:00 -0700751 mContext.unbindService(mConnection);
fredcd6883532012-04-25 17:46:13 -0700752 mUnbinding = false;
Zhihai Xu40874a02012-10-08 17:57:03 -0700753 mBinding = false;
fredcf2458862012-04-16 15:18:27 -0700754 } else {
755 mUnbinding=false;
fredc0f420372012-04-12 00:02:00 -0700756 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800757 mBluetoothGatt = null;
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700758 } finally {
759 mBluetoothLock.writeLock().unlock();
fredc0f420372012-04-12 00:02:00 -0700760 }
761 }
762
Matthew Xieddf7e472013-03-01 18:41:02 -0800763 public IBluetoothGatt getBluetoothGatt() {
764 // sync protection
765 return mBluetoothGatt;
766 }
767
Benjamin Franze8b98922014-11-12 15:57:54 +0000768 @Override
769 public boolean bindBluetoothProfileService(int bluetoothProfile,
770 IBluetoothProfileServiceConnection proxy) {
771 if (!mEnable) {
772 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700773 Slog.d(TAG, "Trying to bind to profile: " + bluetoothProfile +
Benjamin Franze8b98922014-11-12 15:57:54 +0000774 ", while Bluetooth was disabled");
775 }
776 return false;
777 }
778 synchronized (mProfileServices) {
779 ProfileServiceConnections psc = mProfileServices.get(new Integer(bluetoothProfile));
780 if (psc == null) {
781 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700782 Slog.d(TAG, "Creating new ProfileServiceConnections object for"
Benjamin Franze8b98922014-11-12 15:57:54 +0000783 + " profile: " + bluetoothProfile);
784 }
Benjamin Franz5b614592014-12-09 18:58:45 +0000785
786 if (bluetoothProfile != BluetoothProfile.HEADSET) return false;
787
788 Intent intent = new Intent(IBluetoothHeadset.class.getName());
Benjamin Franze8b98922014-11-12 15:57:54 +0000789 psc = new ProfileServiceConnections(intent);
Benjamin Franz5b614592014-12-09 18:58:45 +0000790 if (!psc.bindService()) return false;
791
Benjamin Franze8b98922014-11-12 15:57:54 +0000792 mProfileServices.put(new Integer(bluetoothProfile), psc);
Benjamin Franze8b98922014-11-12 15:57:54 +0000793 }
794 }
795
796 // Introducing a delay to give the client app time to prepare
797 Message addProxyMsg = mHandler.obtainMessage(MESSAGE_ADD_PROXY_DELAYED);
798 addProxyMsg.arg1 = bluetoothProfile;
799 addProxyMsg.obj = proxy;
800 mHandler.sendMessageDelayed(addProxyMsg, ADD_PROXY_DELAY_MS);
801 return true;
802 }
803
804 @Override
805 public void unbindBluetoothProfileService(int bluetoothProfile,
806 IBluetoothProfileServiceConnection proxy) {
807 synchronized (mProfileServices) {
808 ProfileServiceConnections psc = mProfileServices.get(new Integer(bluetoothProfile));
809 if (psc == null) {
810 return;
811 }
812 psc.removeProxy(proxy);
813 }
814 }
815
816 private void unbindAllBluetoothProfileServices() {
817 synchronized (mProfileServices) {
818 for (Integer i : mProfileServices.keySet()) {
819 ProfileServiceConnections psc = mProfileServices.get(i);
Benjamin Franz5b614592014-12-09 18:58:45 +0000820 try {
821 mContext.unbindService(psc);
822 } catch (IllegalArgumentException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700823 Slog.e(TAG, "Unable to unbind service with intent: " + psc.mIntent, e);
Benjamin Franz5b614592014-12-09 18:58:45 +0000824 }
Benjamin Franze8b98922014-11-12 15:57:54 +0000825 psc.removeAllProxies();
826 }
827 mProfileServices.clear();
828 }
829 }
830
831 /**
Miao Chou658bf2f2015-06-26 17:14:35 -0700832 * Send enable message and set adapter name and address. Called when the boot phase becomes
833 * PHASE_SYSTEM_SERVICES_READY.
834 */
835 public void handleOnBootPhase() {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700836 if (DBG) Slog.d(TAG, "Bluetooth boot completed");
Lenka Trochtova13a05192016-12-02 12:19:39 +0100837 UserManagerInternal userManagerInternal =
838 LocalServices.getService(UserManagerInternal.class);
839 userManagerInternal.addUserRestrictionsListener(mUserRestrictionsListener);
840 if (isBluetoothDisallowed()) {
841 return;
842 }
Miao Chou658bf2f2015-06-26 17:14:35 -0700843 if (mEnableExternal && isBluetoothPersistedStateOnBluetooth()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700844 if (DBG) Slog.d(TAG, "Auto-enabling Bluetooth.");
Miao Chou658bf2f2015-06-26 17:14:35 -0700845 sendEnableMsg(mQuietEnableExternal);
Ajay Panickerbf796d82016-03-11 13:47:20 -0800846 } else if (!isNameAndAddressSet()) {
847 if (DBG) Slog.d(TAG, "Getting adapter name and address");
Ajay Panicker4bb48302016-03-31 14:14:27 -0700848 Message getMsg = mHandler.obtainMessage(MESSAGE_GET_NAME_AND_ADDRESS);
849 mHandler.sendMessage(getMsg);
Miao Chou658bf2f2015-06-26 17:14:35 -0700850 }
Miao Chou658bf2f2015-06-26 17:14:35 -0700851 }
852
853 /**
854 * Called when switching to a different foreground user.
855 */
856 public void handleOnSwitchUser(int userHandle) {
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -0700857 if (DBG) Slog.d(TAG, "User " + userHandle + " switched");
858 mHandler.obtainMessage(MESSAGE_USER_SWITCHED, userHandle, 0).sendToTarget();
859 }
860
861 /**
862 * Called when user is unlocked.
863 */
864 public void handleOnUnlockUser(int userHandle) {
865 if (DBG) Slog.d(TAG, "User " + userHandle + " unlocked");
866 mHandler.obtainMessage(MESSAGE_USER_UNLOCKED, userHandle, 0).sendToTarget();
Miao Chou658bf2f2015-06-26 17:14:35 -0700867 }
868
869 /**
Benjamin Franze8b98922014-11-12 15:57:54 +0000870 * This class manages the clients connected to a given ProfileService
871 * and maintains the connection with that service.
872 */
873 final private class ProfileServiceConnections implements ServiceConnection,
874 IBinder.DeathRecipient {
875 final RemoteCallbackList<IBluetoothProfileServiceConnection> mProxies =
876 new RemoteCallbackList <IBluetoothProfileServiceConnection>();
877 IBinder mService;
878 ComponentName mClassName;
879 Intent mIntent;
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700880 boolean mInvokingProxyCallbacks = false;
Benjamin Franze8b98922014-11-12 15:57:54 +0000881
882 ProfileServiceConnections(Intent intent) {
883 mService = null;
884 mClassName = null;
885 mIntent = intent;
886 }
887
Benjamin Franz5b614592014-12-09 18:58:45 +0000888 private boolean bindService() {
889 if (mIntent != null && mService == null &&
890 doBind(mIntent, this, 0, UserHandle.CURRENT_OR_SELF)) {
Benjamin Franze8b98922014-11-12 15:57:54 +0000891 Message msg = mHandler.obtainMessage(MESSAGE_BIND_PROFILE_SERVICE);
892 msg.obj = this;
893 mHandler.sendMessageDelayed(msg, TIMEOUT_BIND_MS);
Benjamin Franz5b614592014-12-09 18:58:45 +0000894 return true;
Benjamin Franze8b98922014-11-12 15:57:54 +0000895 }
Jeff Sharkey67609c72016-03-05 14:29:13 -0700896 Slog.w(TAG, "Unable to bind with intent: " + mIntent);
Benjamin Franz5b614592014-12-09 18:58:45 +0000897 return false;
Benjamin Franze8b98922014-11-12 15:57:54 +0000898 }
899
900 private void addProxy(IBluetoothProfileServiceConnection proxy) {
901 mProxies.register(proxy);
902 if (mService != null) {
903 try{
904 proxy.onServiceConnected(mClassName, mService);
905 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700906 Slog.e(TAG, "Unable to connect to proxy", e);
Benjamin Franze8b98922014-11-12 15:57:54 +0000907 }
908 } else {
909 if (!mHandler.hasMessages(MESSAGE_BIND_PROFILE_SERVICE, this)) {
910 Message msg = mHandler.obtainMessage(MESSAGE_BIND_PROFILE_SERVICE);
911 msg.obj = this;
912 mHandler.sendMessage(msg);
913 }
914 }
915 }
916
917 private void removeProxy(IBluetoothProfileServiceConnection proxy) {
918 if (proxy != null) {
919 if (mProxies.unregister(proxy)) {
920 try {
921 proxy.onServiceDisconnected(mClassName);
922 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700923 Slog.e(TAG, "Unable to disconnect proxy", e);
Benjamin Franze8b98922014-11-12 15:57:54 +0000924 }
925 }
926 } else {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700927 Slog.w(TAG, "Trying to remove a null proxy");
Benjamin Franze8b98922014-11-12 15:57:54 +0000928 }
929 }
930
931 private void removeAllProxies() {
932 onServiceDisconnected(mClassName);
933 mProxies.kill();
934 }
935
936 @Override
937 public void onServiceConnected(ComponentName className, IBinder service) {
938 // remove timeout message
939 mHandler.removeMessages(MESSAGE_BIND_PROFILE_SERVICE, this);
940 mService = service;
941 mClassName = className;
942 try {
943 mService.linkToDeath(this, 0);
944 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700945 Slog.e(TAG, "Unable to linkToDeath", e);
Benjamin Franze8b98922014-11-12 15:57:54 +0000946 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700947
948 if (mInvokingProxyCallbacks) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700949 Slog.e(TAG, "Proxy callbacks already in progress.");
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700950 return;
Benjamin Franze8b98922014-11-12 15:57:54 +0000951 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700952 mInvokingProxyCallbacks = true;
953
954 final int n = mProxies.beginBroadcast();
955 try {
956 for (int i = 0; i < n; i++) {
957 try {
958 mProxies.getBroadcastItem(i).onServiceConnected(className, service);
959 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700960 Slog.e(TAG, "Unable to connect to proxy", e);
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700961 }
962 }
963 } finally {
964 mProxies.finishBroadcast();
965 mInvokingProxyCallbacks = false;
966 }
Benjamin Franze8b98922014-11-12 15:57:54 +0000967 }
968
969 @Override
970 public void onServiceDisconnected(ComponentName className) {
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700971 if (mService == null) return;
Benjamin Franze8b98922014-11-12 15:57:54 +0000972 mService.unlinkToDeath(this, 0);
973 mService = null;
974 mClassName = null;
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700975
976 if (mInvokingProxyCallbacks) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700977 Slog.e(TAG, "Proxy callbacks already in progress.");
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700978 return;
Benjamin Franze8b98922014-11-12 15:57:54 +0000979 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700980 mInvokingProxyCallbacks = true;
981
982 final int n = mProxies.beginBroadcast();
983 try {
984 for (int i = 0; i < n; i++) {
985 try {
986 mProxies.getBroadcastItem(i).onServiceDisconnected(className);
987 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700988 Slog.e(TAG, "Unable to disconnect from proxy", e);
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700989 }
990 }
991 } finally {
992 mProxies.finishBroadcast();
993 mInvokingProxyCallbacks = false;
994 }
Benjamin Franze8b98922014-11-12 15:57:54 +0000995 }
996
997 @Override
998 public void binderDied() {
999 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001000 Slog.w(TAG, "Profile service for profile: " + mClassName
Benjamin Franze8b98922014-11-12 15:57:54 +00001001 + " died.");
1002 }
1003 onServiceDisconnected(mClassName);
1004 // Trigger rebind
1005 Message msg = mHandler.obtainMessage(MESSAGE_BIND_PROFILE_SERVICE);
1006 msg.obj = this;
1007 mHandler.sendMessageDelayed(msg, TIMEOUT_BIND_MS);
1008 }
1009 }
1010
fredcbf072a72012-05-09 16:52:50 -07001011 private void sendBluetoothStateCallback(boolean isUp) {
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001012 try {
1013 int n = mStateChangeCallbacks.beginBroadcast();
Jeff Sharkey67609c72016-03-05 14:29:13 -07001014 if (DBG) Slog.d(TAG,"Broadcasting onBluetoothStateChange("+isUp+") to " + n + " receivers.");
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001015 for (int i=0; i <n;i++) {
1016 try {
1017 mStateChangeCallbacks.getBroadcastItem(i).onBluetoothStateChange(isUp);
1018 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001019 Slog.e(TAG, "Unable to call onBluetoothStateChange() on callback #" + i , e);
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001020 }
fredcbf072a72012-05-09 16:52:50 -07001021 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001022 } finally {
1023 mStateChangeCallbacks.finishBroadcast();
fredcbf072a72012-05-09 16:52:50 -07001024 }
fredcbf072a72012-05-09 16:52:50 -07001025 }
1026
1027 /**
Zhihai Xu40874a02012-10-08 17:57:03 -07001028 * Inform BluetoothAdapter instances that Adapter service is up
1029 */
1030 private void sendBluetoothServiceUpCallback() {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001031 if (DBG) Slog.d(TAG,"Calling onBluetoothServiceUp callbacks");
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001032 try {
1033 int n = mCallbacks.beginBroadcast();
Jeff Sharkey67609c72016-03-05 14:29:13 -07001034 Slog.d(TAG,"Broadcasting onBluetoothServiceUp() to " + n + " receivers.");
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001035 for (int i=0; i <n;i++) {
1036 try {
1037 mCallbacks.getBroadcastItem(i).onBluetoothServiceUp(mBluetooth);
1038 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001039 Slog.e(TAG, "Unable to call onBluetoothServiceUp() on callback #" + i, e);
Zhihai Xu40874a02012-10-08 17:57:03 -07001040 }
1041 }
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001042 } finally {
1043 mCallbacks.finishBroadcast();
Zhihai Xu40874a02012-10-08 17:57:03 -07001044 }
1045 }
1046 /**
fredcbf072a72012-05-09 16:52:50 -07001047 * Inform BluetoothAdapter instances that Adapter service is down
1048 */
1049 private void sendBluetoothServiceDownCallback() {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001050 if (DBG) Slog.d(TAG,"Calling onBluetoothServiceDown callbacks");
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001051 try {
1052 int n = mCallbacks.beginBroadcast();
Jeff Sharkey67609c72016-03-05 14:29:13 -07001053 Slog.d(TAG,"Broadcasting onBluetoothServiceDown() to " + n + " receivers.");
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001054 for (int i=0; i <n;i++) {
1055 try {
1056 mCallbacks.getBroadcastItem(i).onBluetoothServiceDown();
1057 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001058 Slog.e(TAG, "Unable to call onBluetoothServiceDown() on callback #" + i, e);
fredcd6883532012-04-25 17:46:13 -07001059 }
1060 }
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001061 } finally {
1062 mCallbacks.finishBroadcast();
fredcd6883532012-04-25 17:46:13 -07001063 }
1064 }
Svet Ganov408abf72015-05-12 19:13:36 -07001065
fredc0f420372012-04-12 00:02:00 -07001066 public String getAddress() {
Matthew Xieaf5ddbf2012-12-04 10:47:43 -08001067 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
Svet Ganov408abf72015-05-12 19:13:36 -07001068 "Need BLUETOOTH permission");
Zhihai Xu40874a02012-10-08 17:57:03 -07001069
Zhihai Xu6eb76522012-11-29 15:41:04 -08001070 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
Svet Ganov408abf72015-05-12 19:13:36 -07001071 (!checkIfCallerIsForegroundUser())) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001072 Slog.w(TAG,"getAddress(): not allowed for non-active and non system user");
Zhihai Xu6eb76522012-11-29 15:41:04 -08001073 return null;
Zhihai Xu40874a02012-10-08 17:57:03 -07001074 }
1075
Svet Ganov408abf72015-05-12 19:13:36 -07001076 if (mContext.checkCallingOrSelfPermission(Manifest.permission.LOCAL_MAC_ADDRESS)
1077 != PackageManager.PERMISSION_GRANTED) {
1078 return BluetoothAdapter.DEFAULT_MAC_ADDRESS;
1079 }
1080
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001081 try {
1082 mBluetoothLock.readLock().lock();
1083 if (mBluetooth != null) return mBluetooth.getAddress();
1084 } catch (RemoteException e) {
1085 Slog.e(TAG, "getAddress(): Unable to retrieve address remotely. Returning cached address", e);
1086 } finally {
1087 mBluetoothLock.readLock().unlock();
fredc116d1d462012-04-20 14:47:08 -07001088 }
Ajay Panickerbf796d82016-03-11 13:47:20 -08001089
Matthew Xiecdce0b92012-07-12 19:06:15 -07001090 // mAddress is accessed from outside.
1091 // It is alright without a lock. Here, bluetooth is off, no other thread is
1092 // changing mAddress
fredc0f420372012-04-12 00:02:00 -07001093 return mAddress;
1094 }
fredc649fe492012-04-19 01:07:18 -07001095
fredc0f420372012-04-12 00:02:00 -07001096 public String getName() {
Matthew Xieaf5ddbf2012-12-04 10:47:43 -08001097 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
1098 "Need BLUETOOTH permission");
Zhihai Xu40874a02012-10-08 17:57:03 -07001099
Zhihai Xu6eb76522012-11-29 15:41:04 -08001100 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
1101 (!checkIfCallerIsForegroundUser())) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001102 Slog.w(TAG,"getName(): not allowed for non-active and non system user");
Zhihai Xu6eb76522012-11-29 15:41:04 -08001103 return null;
Zhihai Xu40874a02012-10-08 17:57:03 -07001104 }
1105
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001106 try {
1107 mBluetoothLock.readLock().lock();
1108 if (mBluetooth != null) return mBluetooth.getName();
1109 } catch (RemoteException e) {
1110 Slog.e(TAG, "getName(): Unable to retrieve name remotely. Returning cached name", e);
1111 } finally {
1112 mBluetoothLock.readLock().unlock();
fredc116d1d462012-04-20 14:47:08 -07001113 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001114
Matthew Xiecdce0b92012-07-12 19:06:15 -07001115 // mName is accessed from outside.
1116 // It alright without a lock. Here, bluetooth is off, no other thread is
1117 // changing mName
fredc0f420372012-04-12 00:02:00 -07001118 return mName;
1119 }
1120
fredc0f420372012-04-12 00:02:00 -07001121 private class BluetoothServiceConnection implements ServiceConnection {
fredc0f420372012-04-12 00:02:00 -07001122 public void onServiceConnected(ComponentName className, IBinder service) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001123 if (DBG) Slog.d(TAG, "BluetoothServiceConnection: " + className.getClassName());
fredc0f420372012-04-12 00:02:00 -07001124 Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_SERVICE_CONNECTED);
Matthew Xieddf7e472013-03-01 18:41:02 -08001125 // TBD if (className.getClassName().equals(IBluetooth.class.getName())) {
1126 if (className.getClassName().equals("com.android.bluetooth.btservice.AdapterService")) {
1127 msg.arg1 = SERVICE_IBLUETOOTH;
1128 // } else if (className.getClassName().equals(IBluetoothGatt.class.getName())) {
1129 } else if (className.getClassName().equals("com.android.bluetooth.gatt.GattService")) {
1130 msg.arg1 = SERVICE_IBLUETOOTHGATT;
1131 } else {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001132 Slog.e(TAG, "Unknown service connected: " + className.getClassName());
Matthew Xieddf7e472013-03-01 18:41:02 -08001133 return;
1134 }
fredc0f420372012-04-12 00:02:00 -07001135 msg.obj = service;
1136 mHandler.sendMessage(msg);
1137 }
1138
1139 public void onServiceDisconnected(ComponentName className) {
fredc0f420372012-04-12 00:02:00 -07001140 // Called if we unexpected disconnected.
Jeff Sharkey67609c72016-03-05 14:29:13 -07001141 if (DBG) Slog.d(TAG, "BluetoothServiceConnection, disconnected: " +
Matthew Xieddf7e472013-03-01 18:41:02 -08001142 className.getClassName());
fredc0f420372012-04-12 00:02:00 -07001143 Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED);
Matthew Xieddf7e472013-03-01 18:41:02 -08001144 if (className.getClassName().equals("com.android.bluetooth.btservice.AdapterService")) {
1145 msg.arg1 = SERVICE_IBLUETOOTH;
1146 } else if (className.getClassName().equals("com.android.bluetooth.gatt.GattService")) {
1147 msg.arg1 = SERVICE_IBLUETOOTHGATT;
1148 } else {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001149 Slog.e(TAG, "Unknown service disconnected: " + className.getClassName());
Matthew Xieddf7e472013-03-01 18:41:02 -08001150 return;
1151 }
fredc0f420372012-04-12 00:02:00 -07001152 mHandler.sendMessage(msg);
1153 }
1154 }
1155
1156 private BluetoothServiceConnection mConnection = new BluetoothServiceConnection();
1157
Zhihai Xu40874a02012-10-08 17:57:03 -07001158 private class BluetoothHandler extends Handler {
Ajay Panicker4bb48302016-03-31 14:14:27 -07001159 boolean mGetNameAddressOnly = false;
1160
Zhihai Xu40874a02012-10-08 17:57:03 -07001161 public BluetoothHandler(Looper looper) {
1162 super(looper);
1163 }
1164
fredc0f420372012-04-12 00:02:00 -07001165 @Override
1166 public void handleMessage(Message msg) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001167 if (DBG) Slog.d (TAG, "Message: " + msg.what);
fredc0f420372012-04-12 00:02:00 -07001168 switch (msg.what) {
Ajay Panicker4bb48302016-03-31 14:14:27 -07001169 case MESSAGE_GET_NAME_AND_ADDRESS:
1170 if (DBG) Slog.d(TAG, "MESSAGE_GET_NAME_AND_ADDRESS");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001171 try {
1172 mBluetoothLock.writeLock().lock();
Ajay Panicker4bb48302016-03-31 14:14:27 -07001173 if ((mBluetooth == null) && (!mBinding)) {
1174 if (DBG) Slog.d(TAG, "Binding to service to get name and address");
1175 mGetNameAddressOnly = true;
1176 Message timeoutMsg = mHandler.obtainMessage(MESSAGE_TIMEOUT_BIND);
1177 mHandler.sendMessageDelayed(timeoutMsg, TIMEOUT_BIND_MS);
1178 Intent i = new Intent(IBluetooth.class.getName());
1179 if (!doBind(i, mConnection,
1180 Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT,
1181 UserHandle.CURRENT)) {
1182 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
1183 } else {
1184 mBinding = true;
1185 }
1186 } else if (mBluetooth != null) {
1187 try {
1188 storeNameAndAddress(mBluetooth.getName(),
1189 mBluetooth.getAddress());
1190 } catch (RemoteException re) {
1191 Slog.e(TAG, "Unable to grab names", re);
1192 }
1193 if (mGetNameAddressOnly && !mEnable) {
1194 unbindAndFinish();
1195 }
1196 mGetNameAddressOnly = false;
1197 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001198 } finally {
1199 mBluetoothLock.writeLock().unlock();
Ajay Panicker4bb48302016-03-31 14:14:27 -07001200 }
1201 break;
1202
Matthew Xiecdce0b92012-07-12 19:06:15 -07001203 case MESSAGE_ENABLE:
fredcf2458862012-04-16 15:18:27 -07001204 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001205 Slog.d(TAG, "MESSAGE_ENABLE: mBluetooth = " + mBluetooth);
fredc649fe492012-04-19 01:07:18 -07001206 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001207 mHandler.removeMessages(MESSAGE_RESTART_BLUETOOTH_SERVICE);
1208 mEnable = true;
Calvin Ona0b91d72016-06-15 17:58:23 -07001209
1210 // Use service interface to get the exact state
1211 try {
1212 mBluetoothLock.readLock().lock();
1213 if (mBluetooth != null) {
1214 int state = mBluetooth.getState();
1215 if (state == BluetoothAdapter.STATE_BLE_ON) {
1216 Slog.w(TAG, "BT is in BLE_ON State");
1217 mBluetooth.onLeServiceUp();
1218 break;
1219 }
1220 }
1221 } catch (RemoteException e) {
1222 Slog.e(TAG, "", e);
1223 } finally {
1224 mBluetoothLock.readLock().unlock();
1225 }
1226
1227 mQuietEnable = (msg.arg1 == 1);
Pavlin Radoslavove47ec142016-06-01 22:25:18 -07001228 if (mBluetooth == null) {
Calvin Ona0b91d72016-06-15 17:58:23 -07001229 handleEnable(mQuietEnable);
Pavlin Radoslavove47ec142016-06-01 22:25:18 -07001230 } else {
1231 //
1232 // We need to wait until transitioned to STATE_OFF and
1233 // the previous Bluetooth process has exited. The
1234 // waiting period has three components:
1235 // (a) Wait until the local state is STATE_OFF. This
1236 // is accomplished by "waitForOnOff(false, true)".
1237 // (b) Wait until the STATE_OFF state is updated to
1238 // all components.
1239 // (c) Wait until the Bluetooth process exits, and
1240 // ActivityManager detects it.
1241 // The waiting for (b) and (c) is accomplished by
1242 // delaying the MESSAGE_RESTART_BLUETOOTH_SERVICE
1243 // message. On slower devices, that delay needs to be
1244 // on the order of (2 * SERVICE_RESTART_TIME_MS).
1245 //
1246 waitForOnOff(false, true);
Pavlin Radoslavove47ec142016-06-01 22:25:18 -07001247 Message restartMsg = mHandler.obtainMessage(
1248 MESSAGE_RESTART_BLUETOOTH_SERVICE);
1249 mHandler.sendMessageDelayed(restartMsg,
1250 2 * SERVICE_RESTART_TIME_MS);
1251 }
fredc649fe492012-04-19 01:07:18 -07001252 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001253
fredc0f420372012-04-12 00:02:00 -07001254 case MESSAGE_DISABLE:
Zhihai Xu40874a02012-10-08 17:57:03 -07001255 mHandler.removeMessages(MESSAGE_RESTART_BLUETOOTH_SERVICE);
1256 if (mEnable && mBluetooth != null) {
1257 waitForOnOff(true, false);
1258 mEnable = false;
Zhihai Xu401202b2012-12-03 11:36:21 -08001259 handleDisable();
Zhihai Xu40874a02012-10-08 17:57:03 -07001260 waitForOnOff(false, false);
1261 } else {
1262 mEnable = false;
Zhihai Xu401202b2012-12-03 11:36:21 -08001263 handleDisable();
Zhihai Xu40874a02012-10-08 17:57:03 -07001264 }
fredc0f420372012-04-12 00:02:00 -07001265 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001266
fredc0f420372012-04-12 00:02:00 -07001267 case MESSAGE_REGISTER_ADAPTER:
1268 {
1269 IBluetoothManagerCallback callback = (IBluetoothManagerCallback) msg.obj;
fredcd6883532012-04-25 17:46:13 -07001270 boolean added = mCallbacks.register(callback);
Jeff Sharkey67609c72016-03-05 14:29:13 -07001271 Slog.d(TAG,"Added callback: " + (callback == null? "null": callback) +":" +added );
fredc0f420372012-04-12 00:02:00 -07001272 }
1273 break;
1274 case MESSAGE_UNREGISTER_ADAPTER:
1275 {
1276 IBluetoothManagerCallback callback = (IBluetoothManagerCallback) msg.obj;
fredcd6883532012-04-25 17:46:13 -07001277 boolean removed = mCallbacks.unregister(callback);
Jeff Sharkey67609c72016-03-05 14:29:13 -07001278 Slog.d(TAG,"Removed callback: " + (callback == null? "null": callback) +":" + removed);
fredc0f420372012-04-12 00:02:00 -07001279 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001280 }
fredc0f420372012-04-12 00:02:00 -07001281 case MESSAGE_REGISTER_STATE_CHANGE_CALLBACK:
1282 {
1283 IBluetoothStateChangeCallback callback = (IBluetoothStateChangeCallback) msg.obj;
Matthew Xie9b693992013-10-10 11:21:40 -07001284 if (callback != null) {
1285 mStateChangeCallbacks.register(callback);
1286 }
fredc0f420372012-04-12 00:02:00 -07001287 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001288 }
fredc0f420372012-04-12 00:02:00 -07001289 case MESSAGE_UNREGISTER_STATE_CHANGE_CALLBACK:
1290 {
1291 IBluetoothStateChangeCallback callback = (IBluetoothStateChangeCallback) msg.obj;
Matthew Xie9b693992013-10-10 11:21:40 -07001292 if (callback != null) {
1293 mStateChangeCallbacks.unregister(callback);
1294 }
fredc0f420372012-04-12 00:02:00 -07001295 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001296 }
Benjamin Franze8b98922014-11-12 15:57:54 +00001297 case MESSAGE_ADD_PROXY_DELAYED:
1298 {
1299 ProfileServiceConnections psc = mProfileServices.get(
1300 new Integer(msg.arg1));
1301 if (psc == null) {
1302 break;
1303 }
1304 IBluetoothProfileServiceConnection proxy =
1305 (IBluetoothProfileServiceConnection) msg.obj;
1306 psc.addProxy(proxy);
1307 break;
1308 }
1309 case MESSAGE_BIND_PROFILE_SERVICE:
1310 {
1311 ProfileServiceConnections psc = (ProfileServiceConnections) msg.obj;
1312 removeMessages(MESSAGE_BIND_PROFILE_SERVICE, msg.obj);
1313 if (psc == null) {
1314 break;
1315 }
1316 psc.bindService();
1317 break;
1318 }
fredc0f420372012-04-12 00:02:00 -07001319 case MESSAGE_BLUETOOTH_SERVICE_CONNECTED:
1320 {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001321 if (DBG) Slog.d(TAG,"MESSAGE_BLUETOOTH_SERVICE_CONNECTED: " + msg.arg1);
fredc0f420372012-04-12 00:02:00 -07001322
1323 IBinder service = (IBinder) msg.obj;
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001324 try {
1325 mBluetoothLock.writeLock().lock();
Matthew Xieddf7e472013-03-01 18:41:02 -08001326 if (msg.arg1 == SERVICE_IBLUETOOTHGATT) {
1327 mBluetoothGatt = IBluetoothGatt.Stub.asInterface(service);
Nitin Arorad055adb2015-03-02 15:03:51 -08001328 onBluetoothGattServiceUp();
Matthew Xieddf7e472013-03-01 18:41:02 -08001329 break;
1330 } // else must be SERVICE_IBLUETOOTH
1331
1332 //Remove timeout
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001333 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
Matthew Xieddf7e472013-03-01 18:41:02 -08001334
fredc0f420372012-04-12 00:02:00 -07001335 mBinding = false;
Marie Janssen9db28eb2016-01-12 16:05:15 -08001336 mBluetoothBinder = service;
fredc0f420372012-04-12 00:02:00 -07001337 mBluetooth = IBluetooth.Stub.asInterface(service);
fredc0f420372012-04-12 00:02:00 -07001338
Ajay Panicker4bb48302016-03-31 14:14:27 -07001339 if (!isNameAndAddressSet()) {
1340 Message getMsg = mHandler.obtainMessage(MESSAGE_GET_NAME_AND_ADDRESS);
1341 mHandler.sendMessage(getMsg);
1342 if (mGetNameAddressOnly) return;
1343 }
1344
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001345 try {
1346 boolean enableHciSnoopLog = (Settings.Secure.getInt(mContentResolver,
1347 Settings.Secure.BLUETOOTH_HCI_LOG, 0) == 1);
1348 if (!mBluetooth.configHciSnoopLog(enableHciSnoopLog)) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001349 Slog.e(TAG,"IBluetooth.configHciSnoopLog return false");
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001350 }
1351 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001352 Slog.e(TAG,"Unable to call configHciSnoopLog", e);
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001353 }
1354
Matthew Xiecdce0b92012-07-12 19:06:15 -07001355 //Register callback object
fredcbf072a72012-05-09 16:52:50 -07001356 try {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001357 mBluetooth.registerCallback(mBluetoothCallback);
1358 } catch (RemoteException re) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001359 Slog.e(TAG, "Unable to register BluetoothCallback",re);
fredcbf072a72012-05-09 16:52:50 -07001360 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001361 //Inform BluetoothAdapter instances that service is up
Zhihai Xu40874a02012-10-08 17:57:03 -07001362 sendBluetoothServiceUpCallback();
1363
Matthew Xiecdce0b92012-07-12 19:06:15 -07001364 //Do enable request
1365 try {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001366 if (mQuietEnable == false) {
1367 if(!mBluetooth.enable()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001368 Slog.e(TAG,"IBluetooth.enable() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001369 }
1370 }
1371 else
1372 {
1373 if(!mBluetooth.enableNoAutoConnect()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001374 Slog.e(TAG,"IBluetooth.enableNoAutoConnect() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001375 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001376 }
1377 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001378 Slog.e(TAG,"Unable to call enable()",e);
Matthew Xiecdce0b92012-07-12 19:06:15 -07001379 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001380 } finally {
1381 mBluetoothLock.writeLock().unlock();
Freda8c6df02012-07-11 10:25:23 -07001382 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001383
1384 if (!mEnable) {
1385 waitForOnOff(true, false);
Zhihai Xu401202b2012-12-03 11:36:21 -08001386 handleDisable();
Zhihai Xu40874a02012-10-08 17:57:03 -07001387 waitForOnOff(false, false);
1388 }
fredc649fe492012-04-19 01:07:18 -07001389 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001390 }
fredc649fe492012-04-19 01:07:18 -07001391 case MESSAGE_TIMEOUT_BIND: {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001392 Slog.e(TAG, "MESSAGE_TIMEOUT_BIND");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001393 mBluetoothLock.writeLock().lock();
1394 mBinding = false;
1395 mBluetoothLock.writeLock().unlock();
1396
fredc649fe492012-04-19 01:07:18 -07001397 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001398 }
fredcbf072a72012-05-09 16:52:50 -07001399 case MESSAGE_BLUETOOTH_STATE_CHANGE:
fredc0f420372012-04-12 00:02:00 -07001400 {
fredcbf072a72012-05-09 16:52:50 -07001401 int prevState = msg.arg1;
1402 int newState = msg.arg2;
Jeff Sharkey67609c72016-03-05 14:29:13 -07001403 if (DBG) Slog.d(TAG, "MESSAGE_BLUETOOTH_STATE_CHANGE: prevState = " + prevState + ", newState=" + newState);
Zhihai Xu40874a02012-10-08 17:57:03 -07001404 mState = newState;
1405 bluetoothStateChangeHandler(prevState, newState);
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001406 // handle error state transition case from TURNING_ON to OFF
1407 // unbind and rebind bluetooth service and enable bluetooth
Nitin Arorad055adb2015-03-02 15:03:51 -08001408 if ((prevState == BluetoothAdapter.STATE_BLE_TURNING_ON) &&
Calvin Ona0b91d72016-06-15 17:58:23 -07001409 (newState == BluetoothAdapter.STATE_OFF) &&
1410 (mBluetooth != null) && mEnable) {
Marie Janssen2977c3e2016-11-09 12:01:24 -08001411 recoverBluetoothServiceFromError(false);
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001412 }
Nitin Arorad055adb2015-03-02 15:03:51 -08001413 if ((prevState == BluetoothAdapter.STATE_TURNING_ON) &&
Calvin Ona0b91d72016-06-15 17:58:23 -07001414 (newState == BluetoothAdapter.STATE_BLE_ON) &&
1415 (mBluetooth != null) && mEnable) {
Marie Janssen2977c3e2016-11-09 12:01:24 -08001416 recoverBluetoothServiceFromError(true);
Nitin Arorad055adb2015-03-02 15:03:51 -08001417 }
Calvin Ona0b91d72016-06-15 17:58:23 -07001418 // If we tried to enable BT while BT was in the process of shutting down,
1419 // wait for the BT process to fully tear down and then force a restart
1420 // here. This is a bit of a hack (b/29363429).
1421 if ((prevState == BluetoothAdapter.STATE_BLE_TURNING_OFF) &&
1422 (newState == BluetoothAdapter.STATE_OFF)) {
1423 if (mEnable) {
1424 Slog.d(TAG, "Entering STATE_OFF but mEnabled is true; restarting.");
1425 waitForOnOff(false, true);
1426 Message restartMsg = mHandler.obtainMessage(
1427 MESSAGE_RESTART_BLUETOOTH_SERVICE);
1428 mHandler.sendMessageDelayed(restartMsg, 2 * SERVICE_RESTART_TIME_MS);
1429 }
1430 }
Nitin Arorad055adb2015-03-02 15:03:51 -08001431 if (newState == BluetoothAdapter.STATE_ON ||
Calvin Ona0b91d72016-06-15 17:58:23 -07001432 newState == BluetoothAdapter.STATE_BLE_ON) {
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001433 // bluetooth is working, reset the counter
1434 if (mErrorRecoveryRetryCounter != 0) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001435 Slog.w(TAG, "bluetooth is recovered from error");
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001436 mErrorRecoveryRetryCounter = 0;
1437 }
1438 }
fredc649fe492012-04-19 01:07:18 -07001439 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001440 }
fredc0f420372012-04-12 00:02:00 -07001441 case MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED:
1442 {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001443 Slog.e(TAG, "MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED: " + msg.arg1);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001444 try {
1445 mBluetoothLock.writeLock().lock();
Matthew Xieddf7e472013-03-01 18:41:02 -08001446 if (msg.arg1 == SERVICE_IBLUETOOTH) {
1447 // if service is unbinded already, do nothing and return
1448 if (mBluetooth == null) break;
1449 mBluetooth = null;
1450 } else if (msg.arg1 == SERVICE_IBLUETOOTHGATT) {
1451 mBluetoothGatt = null;
1452 break;
1453 } else {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001454 Slog.e(TAG, "Bad msg.arg1: " + msg.arg1);
Matthew Xieddf7e472013-03-01 18:41:02 -08001455 break;
1456 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001457 } finally {
1458 mBluetoothLock.writeLock().unlock();
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301459 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001460
1461 if (mEnable) {
1462 mEnable = false;
1463 // Send a Bluetooth Restart message
1464 Message restartMsg = mHandler.obtainMessage(
1465 MESSAGE_RESTART_BLUETOOTH_SERVICE);
1466 mHandler.sendMessageDelayed(restartMsg,
1467 SERVICE_RESTART_TIME_MS);
1468 }
1469
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001470 sendBluetoothServiceDownCallback();
Zhihai Xu40874a02012-10-08 17:57:03 -07001471
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001472 // Send BT state broadcast to update
1473 // the BT icon correctly
1474 if ((mState == BluetoothAdapter.STATE_TURNING_ON) ||
Calvin Ona0b91d72016-06-15 17:58:23 -07001475 (mState == BluetoothAdapter.STATE_ON)) {
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001476 bluetoothStateChangeHandler(BluetoothAdapter.STATE_ON,
1477 BluetoothAdapter.STATE_TURNING_OFF);
1478 mState = BluetoothAdapter.STATE_TURNING_OFF;
Zhihai Xu40874a02012-10-08 17:57:03 -07001479 }
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001480 if (mState == BluetoothAdapter.STATE_TURNING_OFF) {
1481 bluetoothStateChangeHandler(BluetoothAdapter.STATE_TURNING_OFF,
1482 BluetoothAdapter.STATE_OFF);
1483 }
1484
1485 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
1486 mState = BluetoothAdapter.STATE_OFF;
fredc649fe492012-04-19 01:07:18 -07001487 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001488 }
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301489 case MESSAGE_RESTART_BLUETOOTH_SERVICE:
1490 {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001491 Slog.d(TAG, "MESSAGE_RESTART_BLUETOOTH_SERVICE:"
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301492 +" Restart IBluetooth service");
1493 /* Enable without persisting the setting as
1494 it doesnt change when IBluetooth
1495 service restarts */
Zhihai Xu40874a02012-10-08 17:57:03 -07001496 mEnable = true;
Zhihai Xu401202b2012-12-03 11:36:21 -08001497 handleEnable(mQuietEnable);
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301498 break;
1499 }
1500
fredc0f420372012-04-12 00:02:00 -07001501 case MESSAGE_TIMEOUT_UNBIND:
1502 {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001503 Slog.e(TAG, "MESSAGE_TIMEOUT_UNBIND");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001504 mBluetoothLock.writeLock().lock();
1505 mUnbinding = false;
1506 mBluetoothLock.writeLock().unlock();
fredc649fe492012-04-19 01:07:18 -07001507 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001508 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001509
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001510 case MESSAGE_USER_SWITCHED: {
1511 if (DBG) Slog.d(TAG, "MESSAGE_USER_SWITCHED");
Zhihai Xu40874a02012-10-08 17:57:03 -07001512 mHandler.removeMessages(MESSAGE_USER_SWITCHED);
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001513
Zhihai Xu40874a02012-10-08 17:57:03 -07001514 /* disable and enable BT when detect a user switch */
1515 if (mEnable && mBluetooth != null) {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001516 try {
1517 mBluetoothLock.readLock().lock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001518 if (mBluetooth != null) {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001519 mBluetooth.unregisterCallback(mBluetoothCallback);
Zhihai Xu40874a02012-10-08 17:57:03 -07001520 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001521 } catch (RemoteException re) {
1522 Slog.e(TAG, "Unable to unregister", re);
1523 } finally {
1524 mBluetoothLock.readLock().unlock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001525 }
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001526
1527 if (mState == BluetoothAdapter.STATE_TURNING_OFF) {
1528 // MESSAGE_USER_SWITCHED happened right after MESSAGE_ENABLE
1529 bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_OFF);
1530 mState = BluetoothAdapter.STATE_OFF;
1531 }
1532 if (mState == BluetoothAdapter.STATE_OFF) {
1533 bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_TURNING_ON);
1534 mState = BluetoothAdapter.STATE_TURNING_ON;
1535 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001536
1537 waitForOnOff(true, false);
1538
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001539 if (mState == BluetoothAdapter.STATE_TURNING_ON) {
1540 bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_ON);
1541 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001542
Benjamin Franze8b98922014-11-12 15:57:54 +00001543 unbindAllBluetoothProfileServices();
Zhihai Xu40874a02012-10-08 17:57:03 -07001544 // disable
Zhihai Xu401202b2012-12-03 11:36:21 -08001545 handleDisable();
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001546 // Pbap service need receive STATE_TURNING_OFF intent to close
1547 bluetoothStateChangeHandler(BluetoothAdapter.STATE_ON,
1548 BluetoothAdapter.STATE_TURNING_OFF);
Zhihai Xu40874a02012-10-08 17:57:03 -07001549
Pavlin Radoslavov41401112016-06-27 15:25:18 -07001550 boolean didDisableTimeout = !waitForOnOff(false, true);
Zhihai Xu40874a02012-10-08 17:57:03 -07001551
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001552 bluetoothStateChangeHandler(BluetoothAdapter.STATE_TURNING_OFF,
Zhihai Xu40874a02012-10-08 17:57:03 -07001553 BluetoothAdapter.STATE_OFF);
Zhihai Xu40874a02012-10-08 17:57:03 -07001554 sendBluetoothServiceDownCallback();
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001555
Pavlin Radoslavove957a8a2016-05-24 15:28:41 -07001556 try {
1557 mBluetoothLock.writeLock().lock();
1558 if (mBluetooth != null) {
1559 mBluetooth = null;
1560 // Unbind
1561 mContext.unbindService(mConnection);
1562 }
1563 mBluetoothGatt = null;
1564 } finally {
1565 mBluetoothLock.writeLock().unlock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001566 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001567
Pavlin Radoslavov41401112016-06-27 15:25:18 -07001568 //
1569 // If disabling Bluetooth times out, wait for an
1570 // additional amount of time to ensure the process is
1571 // shut down completely before attempting to restart.
1572 //
1573 if (didDisableTimeout) {
1574 SystemClock.sleep(3000);
1575 } else {
1576 SystemClock.sleep(100);
1577 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001578
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001579 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
1580 mState = BluetoothAdapter.STATE_OFF;
Zhihai Xu40874a02012-10-08 17:57:03 -07001581 // enable
Zhihai Xu401202b2012-12-03 11:36:21 -08001582 handleEnable(mQuietEnable);
John Spurlock8a985d22014-02-25 09:40:05 -05001583 } else if (mBinding || mBluetooth != null) {
Zhihai Xu40874a02012-10-08 17:57:03 -07001584 Message userMsg = mHandler.obtainMessage(MESSAGE_USER_SWITCHED);
1585 userMsg.arg2 = 1 + msg.arg2;
1586 // if user is switched when service is being binding
1587 // delay sending MESSAGE_USER_SWITCHED
1588 mHandler.sendMessageDelayed(userMsg, USER_SWITCHED_TIME_MS);
1589 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001590 Slog.d(TAG, "delay MESSAGE_USER_SWITCHED " + userMsg.arg2);
Zhihai Xu40874a02012-10-08 17:57:03 -07001591 }
John Spurlock8a985d22014-02-25 09:40:05 -05001592 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001593 break;
1594 }
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001595 case MESSAGE_USER_UNLOCKED: {
1596 if (DBG) Slog.d(TAG, "MESSAGE_USER_UNLOCKED");
1597 mHandler.removeMessages(MESSAGE_USER_SWITCHED);
1598
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001599 if (mEnable && !mBinding && (mBluetooth == null)) {
1600 // We should be connected, but we gave up for some
1601 // reason; maybe the Bluetooth service wasn't encryption
1602 // aware, so try binding again.
1603 if (DBG) Slog.d(TAG, "Enabled but not bound; retrying after unlock");
1604 handleEnable(mQuietEnable);
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001605 }
1606 }
fredc0f420372012-04-12 00:02:00 -07001607 }
1608 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001609 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001610
Zhihai Xu401202b2012-12-03 11:36:21 -08001611 private void handleEnable(boolean quietMode) {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001612 mQuietEnable = quietMode;
1613
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001614 try {
1615 mBluetoothLock.writeLock().lock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001616 if ((mBluetooth == null) && (!mBinding)) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001617 //Start bind timeout and bind
1618 Message timeoutMsg=mHandler.obtainMessage(MESSAGE_TIMEOUT_BIND);
1619 mHandler.sendMessageDelayed(timeoutMsg,TIMEOUT_BIND_MS);
Matthew Xiecdce0b92012-07-12 19:06:15 -07001620 Intent i = new Intent(IBluetooth.class.getName());
Dianne Hackbornce09f5a2014-10-10 15:03:13 -07001621 if (!doBind(i, mConnection,Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT,
1622 UserHandle.CURRENT)) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001623 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
Zhihai Xu40874a02012-10-08 17:57:03 -07001624 } else {
1625 mBinding = true;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001626 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001627 } else if (mBluetooth != null) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001628 //Enable bluetooth
1629 try {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001630 if (!mQuietEnable) {
1631 if(!mBluetooth.enable()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001632 Slog.e(TAG,"IBluetooth.enable() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001633 }
1634 }
1635 else {
1636 if(!mBluetooth.enableNoAutoConnect()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001637 Slog.e(TAG,"IBluetooth.enableNoAutoConnect() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001638 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001639 }
1640 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001641 Slog.e(TAG,"Unable to call enable()",e);
Matthew Xiecdce0b92012-07-12 19:06:15 -07001642 }
1643 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001644 } finally {
1645 mBluetoothLock.writeLock().unlock();
Matthew Xiecdce0b92012-07-12 19:06:15 -07001646 }
1647 }
1648
Dianne Hackborn221ea892013-08-04 16:50:16 -07001649 boolean doBind(Intent intent, ServiceConnection conn, int flags, UserHandle user) {
1650 ComponentName comp = intent.resolveSystemService(mContext.getPackageManager(), 0);
1651 intent.setComponent(comp);
1652 if (comp == null || !mContext.bindServiceAsUser(intent, conn, flags, user)) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001653 Slog.e(TAG, "Fail to bind to: " + intent);
Dianne Hackborn221ea892013-08-04 16:50:16 -07001654 return false;
1655 }
1656 return true;
1657 }
1658
Zhihai Xu401202b2012-12-03 11:36:21 -08001659 private void handleDisable() {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001660 try {
1661 mBluetoothLock.readLock().lock();
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001662 if (mBluetooth != null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001663 if (DBG) Slog.d(TAG,"Sending off request.");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001664 if (!mBluetooth.disable()) {
1665 Slog.e(TAG,"IBluetooth.disable() returned false");
Matthew Xiecdce0b92012-07-12 19:06:15 -07001666 }
1667 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001668 } catch (RemoteException e) {
1669 Slog.e(TAG,"Unable to call disable()",e);
1670 } finally {
1671 mBluetoothLock.readLock().unlock();
Matthew Xiecdce0b92012-07-12 19:06:15 -07001672 }
1673 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001674
1675 private boolean checkIfCallerIsForegroundUser() {
1676 int foregroundUser;
1677 int callingUser = UserHandle.getCallingUserId();
Martijn Coenen8385c5a2012-11-29 10:14:16 -08001678 int callingUid = Binder.getCallingUid();
Zhihai Xu40874a02012-10-08 17:57:03 -07001679 long callingIdentity = Binder.clearCallingIdentity();
Benjamin Franze8b98922014-11-12 15:57:54 +00001680 UserManager um = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
1681 UserInfo ui = um.getProfileParent(callingUser);
1682 int parentUser = (ui != null) ? ui.id : UserHandle.USER_NULL;
Martijn Coenen8385c5a2012-11-29 10:14:16 -08001683 int callingAppId = UserHandle.getAppId(callingUid);
Zhihai Xu40874a02012-10-08 17:57:03 -07001684 boolean valid = false;
1685 try {
1686 foregroundUser = ActivityManager.getCurrentUser();
Martijn Coenen8385c5a2012-11-29 10:14:16 -08001687 valid = (callingUser == foregroundUser) ||
Benjamin Franze8b98922014-11-12 15:57:54 +00001688 parentUser == foregroundUser ||
Adrian Roosbd9a9a52014-08-18 15:31:57 +02001689 callingAppId == Process.NFC_UID ||
1690 callingAppId == mSystemUiUid;
Zhihai Xu40874a02012-10-08 17:57:03 -07001691 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001692 Slog.d(TAG, "checkIfCallerIsForegroundUser: valid=" + valid
Zhihai Xu40874a02012-10-08 17:57:03 -07001693 + " callingUser=" + callingUser
Benjamin Franze8b98922014-11-12 15:57:54 +00001694 + " parentUser=" + parentUser
Zhihai Xu40874a02012-10-08 17:57:03 -07001695 + " foregroundUser=" + foregroundUser);
1696 }
1697 } finally {
1698 Binder.restoreCallingIdentity(callingIdentity);
1699 }
1700 return valid;
1701 }
1702
Nitin Arorad055adb2015-03-02 15:03:51 -08001703 private void sendBleStateChanged(int prevState, int newState) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001704 if (DBG) Slog.d(TAG,"BLE State Change Intent: " + prevState + " -> " + newState);
Nitin Arorad055adb2015-03-02 15:03:51 -08001705 // Send broadcast message to everyone else
1706 Intent intent = new Intent(BluetoothAdapter.ACTION_BLE_STATE_CHANGED);
1707 intent.putExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE, prevState);
1708 intent.putExtra(BluetoothAdapter.EXTRA_STATE, newState);
1709 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1710 mContext.sendBroadcastAsUser(intent, UserHandle.ALL, BLUETOOTH_PERM);
1711 }
1712
Zhihai Xu40874a02012-10-08 17:57:03 -07001713 private void bluetoothStateChangeHandler(int prevState, int newState) {
Nitin Arorad055adb2015-03-02 15:03:51 -08001714 boolean isStandardBroadcast = true;
Zhihai Xu40874a02012-10-08 17:57:03 -07001715 if (prevState != newState) {
1716 //Notify all proxy objects first of adapter state change
Calvin Ona0b91d72016-06-15 17:58:23 -07001717 if (newState == BluetoothAdapter.STATE_BLE_ON ||
1718 newState == BluetoothAdapter.STATE_OFF) {
Nitin Arorad055adb2015-03-02 15:03:51 -08001719 boolean intermediate_off = (prevState == BluetoothAdapter.STATE_TURNING_OFF
1720 && newState == BluetoothAdapter.STATE_BLE_ON);
Zhihai Xu40874a02012-10-08 17:57:03 -07001721
Nitin Arorad055adb2015-03-02 15:03:51 -08001722 if (newState == BluetoothAdapter.STATE_OFF) {
1723 // If Bluetooth is off, send service down event to proxy objects, and unbind
Jeff Sharkey67609c72016-03-05 14:29:13 -07001724 if (DBG) Slog.d(TAG, "Bluetooth is complete turn off");
Pavlin Radoslavove47ec142016-06-01 22:25:18 -07001725 sendBluetoothServiceDownCallback();
1726 unbindAndFinish();
1727 sendBleStateChanged(prevState, newState);
1728 // Don't broadcast as it has already been broadcast before
1729 isStandardBroadcast = false;
Nitin Arorad055adb2015-03-02 15:03:51 -08001730
1731 } else if (!intermediate_off) {
1732 // connect to GattService
Jeff Sharkey67609c72016-03-05 14:29:13 -07001733 if (DBG) Slog.d(TAG, "Bluetooth is in LE only mode");
Nitin Arorad055adb2015-03-02 15:03:51 -08001734 if (mBluetoothGatt != null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001735 if (DBG) Slog.d(TAG, "Calling BluetoothGattServiceUp");
Nitin Arorad055adb2015-03-02 15:03:51 -08001736 onBluetoothGattServiceUp();
1737 } else {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001738 if (DBG) Slog.d(TAG, "Binding Bluetooth GATT service");
Nitin Arorad055adb2015-03-02 15:03:51 -08001739 if (mContext.getPackageManager().hasSystemFeature(
1740 PackageManager.FEATURE_BLUETOOTH_LE)) {
1741 Intent i = new Intent(IBluetoothGatt.class.getName());
1742 doBind(i, mConnection, Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT, UserHandle.CURRENT);
1743 }
1744 }
1745 sendBleStateChanged(prevState, newState);
1746 //Don't broadcase this as std intent
1747 isStandardBroadcast = false;
1748
1749 } else if (intermediate_off){
Jeff Sharkey67609c72016-03-05 14:29:13 -07001750 if (DBG) Slog.d(TAG, "Intermediate off, back to LE only mode");
Nitin Arorad055adb2015-03-02 15:03:51 -08001751 // For LE only mode, broadcast as is
1752 sendBleStateChanged(prevState, newState);
1753 sendBluetoothStateCallback(false); // BT is OFF for general users
1754 // Broadcast as STATE_OFF
1755 newState = BluetoothAdapter.STATE_OFF;
1756 sendBrEdrDownCallback();
Zhihai Xu40874a02012-10-08 17:57:03 -07001757 }
Nitin Arorad055adb2015-03-02 15:03:51 -08001758 } else if (newState == BluetoothAdapter.STATE_ON) {
1759 boolean isUp = (newState==BluetoothAdapter.STATE_ON);
1760 sendBluetoothStateCallback(isUp);
1761 sendBleStateChanged(prevState, newState);
1762
Calvin Ona0b91d72016-06-15 17:58:23 -07001763 } else if (newState == BluetoothAdapter.STATE_BLE_TURNING_ON ||
1764 newState == BluetoothAdapter.STATE_BLE_TURNING_OFF ) {
Nitin Arorad055adb2015-03-02 15:03:51 -08001765 sendBleStateChanged(prevState, newState);
1766 isStandardBroadcast = false;
1767
Calvin Ona0b91d72016-06-15 17:58:23 -07001768 } else if (newState == BluetoothAdapter.STATE_TURNING_ON ||
1769 newState == BluetoothAdapter.STATE_TURNING_OFF) {
Nitin Arorad055adb2015-03-02 15:03:51 -08001770 sendBleStateChanged(prevState, newState);
Zhihai Xu40874a02012-10-08 17:57:03 -07001771 }
1772
Nitin Arorad055adb2015-03-02 15:03:51 -08001773 if (isStandardBroadcast) {
1774 if (prevState == BluetoothAdapter.STATE_BLE_ON) {
1775 // Show prevState of BLE_ON as OFF to standard users
1776 prevState = BluetoothAdapter.STATE_OFF;
1777 }
1778 Intent intent = new Intent(BluetoothAdapter.ACTION_STATE_CHANGED);
1779 intent.putExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE, prevState);
1780 intent.putExtra(BluetoothAdapter.EXTRA_STATE, newState);
1781 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1782 mContext.sendBroadcastAsUser(intent, UserHandle.ALL, BLUETOOTH_PERM);
1783 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001784 }
1785 }
1786
1787 /**
1788 * if on is true, wait for state become ON
1789 * if off is true, wait for state become OFF
1790 * if both on and off are false, wait for state not ON
1791 */
1792 private boolean waitForOnOff(boolean on, boolean off) {
1793 int i = 0;
1794 while (i < 10) {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001795 try {
1796 mBluetoothLock.readLock().lock();
1797 if (mBluetooth == null) break;
1798 if (on) {
1799 if (mBluetooth.getState() == BluetoothAdapter.STATE_ON) return true;
1800 } else if (off) {
1801 if (mBluetooth.getState() == BluetoothAdapter.STATE_OFF) return true;
1802 } else {
1803 if (mBluetooth.getState() != BluetoothAdapter.STATE_ON) return true;
Zhihai Xu40874a02012-10-08 17:57:03 -07001804 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001805 } catch (RemoteException e) {
1806 Slog.e(TAG, "getState()", e);
1807 break;
1808 } finally {
1809 mBluetoothLock.readLock().unlock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001810 }
1811 if (on || off) {
1812 SystemClock.sleep(300);
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07001813 } else {
Zhihai Xu40874a02012-10-08 17:57:03 -07001814 SystemClock.sleep(50);
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07001815 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001816 i++;
1817 }
Jeff Sharkey67609c72016-03-05 14:29:13 -07001818 Slog.e(TAG,"waitForOnOff time out");
Zhihai Xu40874a02012-10-08 17:57:03 -07001819 return false;
1820 }
Zhihai Xu681ae7f2012-11-12 15:14:18 -08001821
Zhihai Xu401202b2012-12-03 11:36:21 -08001822 private void sendDisableMsg() {
1823 mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_DISABLE));
1824 }
1825
1826 private void sendEnableMsg(boolean quietMode) {
1827 mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_ENABLE,
1828 quietMode ? 1 : 0, 0));
1829 }
1830
Marie Janssen2977c3e2016-11-09 12:01:24 -08001831 private void recoverBluetoothServiceFromError(boolean clearBle) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001832 Slog.e(TAG,"recoverBluetoothServiceFromError");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001833 try {
1834 mBluetoothLock.readLock().lock();
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001835 if (mBluetooth != null) {
1836 //Unregister callback object
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001837 mBluetooth.unregisterCallback(mBluetoothCallback);
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001838 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001839 } catch (RemoteException re) {
1840 Slog.e(TAG, "Unable to unregister", re);
1841 } finally {
1842 mBluetoothLock.readLock().unlock();
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001843 }
1844
1845 SystemClock.sleep(500);
1846
1847 // disable
1848 handleDisable();
1849
1850 waitForOnOff(false, true);
1851
1852 sendBluetoothServiceDownCallback();
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001853
Pavlin Radoslavove957a8a2016-05-24 15:28:41 -07001854 try {
1855 mBluetoothLock.writeLock().lock();
1856 if (mBluetooth != null) {
1857 mBluetooth = null;
1858 // Unbind
1859 mContext.unbindService(mConnection);
1860 }
1861 mBluetoothGatt = null;
1862 } finally {
1863 mBluetoothLock.writeLock().unlock();
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001864 }
1865
1866 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
1867 mState = BluetoothAdapter.STATE_OFF;
1868
Marie Janssen2977c3e2016-11-09 12:01:24 -08001869 if (clearBle) {
1870 clearBleApps();
1871 }
1872
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001873 mEnable = false;
1874
1875 if (mErrorRecoveryRetryCounter++ < MAX_ERROR_RESTART_RETRIES) {
1876 // Send a Bluetooth Restart message to reenable bluetooth
1877 Message restartMsg = mHandler.obtainMessage(
1878 MESSAGE_RESTART_BLUETOOTH_SERVICE);
1879 mHandler.sendMessageDelayed(restartMsg, ERROR_RESTART_TIME_MS);
1880 } else {
1881 // todo: notify user to power down and power up phone to make bluetooth work.
1882 }
1883 }
Mike Lockwood726d4de2014-10-28 14:06:28 -07001884
Lenka Trochtova13a05192016-12-02 12:19:39 +01001885 private boolean isBluetoothDisallowed() {
1886 long callingIdentity = Binder.clearCallingIdentity();
1887 try {
1888 return mContext.getSystemService(UserManager.class)
1889 .hasUserRestriction(UserManager.DISALLOW_BLUETOOTH, UserHandle.SYSTEM);
1890 } finally {
1891 Binder.restoreCallingIdentity(callingIdentity);
1892 }
1893 }
1894
Mike Lockwood726d4de2014-10-28 14:06:28 -07001895 @Override
Pavlin Radoslavov6e8faff2016-02-23 11:54:37 -08001896 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1897 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DUMP, TAG);
1898 String errorMsg = null;
1899 if (mBluetoothBinder == null) {
1900 errorMsg = "Bluetooth Service not connected";
1901 } else {
1902 try {
1903 mBluetoothBinder.dump(fd, args);
1904 } catch (RemoteException re) {
1905 errorMsg = "RemoteException while calling Bluetooth Service";
1906 }
Mike Lockwood726d4de2014-10-28 14:06:28 -07001907 }
Pavlin Radoslavov6e8faff2016-02-23 11:54:37 -08001908 if (errorMsg != null) {
1909 // Silently return if we are extracting metrics in Protobuf format
1910 if ((args.length > 0) && args[0].startsWith("--proto"))
1911 return;
1912 writer.println(errorMsg);
1913 }
Mike Lockwood726d4de2014-10-28 14:06:28 -07001914 }
fredc0f420372012-04-12 00:02:00 -07001915}