blob: b60dd0f52c73c435a7e6ae7d6ed79ac25bc676a8 [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;
Pavel Grafov4f4f6f82017-03-28 13:44:04 +010021import android.app.AppGlobals;
fredc0f420372012-04-12 00:02:00 -070022import android.bluetooth.BluetoothAdapter;
Benjamin Franze8b98922014-11-12 15:57:54 +000023import android.bluetooth.BluetoothProfile;
Jack He8caab152018-03-02 13:08:36 -080024import android.bluetooth.BluetoothProtoEnums;
fredc0f420372012-04-12 00:02:00 -070025import android.bluetooth.IBluetooth;
fredcbf072a72012-05-09 16:52:50 -070026import android.bluetooth.IBluetoothCallback;
Wei Wange4a744b2015-06-11 17:50:29 -070027import android.bluetooth.IBluetoothGatt;
Benjamin Franze8b98922014-11-12 15:57:54 +000028import android.bluetooth.IBluetoothHeadset;
fredc0f420372012-04-12 00:02:00 -070029import android.bluetooth.IBluetoothManager;
30import android.bluetooth.IBluetoothManagerCallback;
Benjamin Franze8b98922014-11-12 15:57:54 +000031import android.bluetooth.IBluetoothProfileServiceConnection;
fredc0f420372012-04-12 00:02:00 -070032import android.bluetooth.IBluetoothStateChangeCallback;
Svet Ganov77df6f32016-08-17 11:46:34 -070033import android.content.ActivityNotFoundException;
fredc0f420372012-04-12 00:02:00 -070034import android.content.BroadcastReceiver;
35import android.content.ComponentName;
36import android.content.ContentResolver;
37import android.content.Context;
38import android.content.Intent;
39import android.content.IntentFilter;
40import android.content.ServiceConnection;
Svetoslav Ganovac69be52016-06-29 17:31:44 -070041import android.content.pm.ApplicationInfo;
Pavel Grafov4f4f6f82017-03-28 13:44:04 +010042import android.content.pm.IPackageManager;
Matthew Xie32ab77b2013-05-08 19:26:57 -070043import android.content.pm.PackageManager;
Benjamin Franze8b98922014-11-12 15:57:54 +000044import android.content.pm.UserInfo;
Wei Wange4a744b2015-06-11 17:50:29 -070045import android.database.ContentObserver;
Zhihai Xu40874a02012-10-08 17:57:03 -070046import android.os.Binder;
Lenka Trochtova63d5e4a72016-12-02 12:19:39 +010047import android.os.Bundle;
fredc0f420372012-04-12 00:02:00 -070048import android.os.Handler;
fredc0f420372012-04-12 00:02:00 -070049import android.os.IBinder;
Zhihai Xu40874a02012-10-08 17:57:03 -070050import android.os.Looper;
fredc0f420372012-04-12 00:02:00 -070051import android.os.Message;
Zhihai Xu40874a02012-10-08 17:57:03 -070052import android.os.Process;
fredcd6883532012-04-25 17:46:13 -070053import android.os.RemoteCallbackList;
fredc0f420372012-04-12 00:02:00 -070054import android.os.RemoteException;
Zhihai Xu40874a02012-10-08 17:57:03 -070055import android.os.SystemClock;
Stanley Tngcbfcbd12018-06-19 08:48:10 -070056import android.os.SystemProperties;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070057import android.os.UserHandle;
Benjamin Franze8b98922014-11-12 15:57:54 +000058import android.os.UserManager;
Lenka Trochtova63d5e4a72016-12-02 12:19:39 +010059import android.os.UserManagerInternal;
60import android.os.UserManagerInternal.UserRestrictionsListener;
fredc0f420372012-04-12 00:02:00 -070061import android.provider.Settings;
Wei Wang67d84162015-04-26 17:04:29 -070062import android.provider.Settings.SettingNotFoundException;
Stanley Tngcbfcbd12018-06-19 08:48:10 -070063import android.text.TextUtils;
64import android.util.FeatureFlagUtils;
65import android.util.Log;
Jeff Sharkey67609c72016-03-05 14:29:13 -070066import android.util.Slog;
Tej Singhd8e7cc62018-03-22 18:30:31 +000067import android.util.StatsLog;
Mike Lockwood726d4de2014-10-28 14:06:28 -070068
Arthur Hsuf3f95a92018-01-11 16:46:22 -080069import com.android.internal.R;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060070import com.android.internal.util.DumpUtils;
Pavel Grafov4f4f6f82017-03-28 13:44:04 +010071import com.android.server.pm.UserRestrictionsUtils;
Lenka Trochtovac6f0e232017-01-17 10:35:49 +010072
Mike Lockwood726d4de2014-10-28 14:06:28 -070073import java.io.FileDescriptor;
74import java.io.PrintWriter;
Benjamin Franze8b98922014-11-12 15:57:54 +000075import java.util.HashMap;
Marie Janssen59804562016-12-28 14:13:21 -080076import java.util.LinkedList;
Myles Watsonb5cd11a2017-11-27 16:42:11 -080077import java.util.Locale;
Benjamin Franze8b98922014-11-12 15:57:54 +000078import java.util.Map;
Chienyuan177156b2018-12-18 10:40:25 +080079import java.util.NoSuchElementException;
Pavel Grafov4f4f6f82017-03-28 13:44:04 +010080import java.util.concurrent.ConcurrentHashMap;
81import java.util.concurrent.locks.ReentrantReadWriteLock;
Miao Chou658bf2f2015-06-26 17:14:35 -070082
Marie Janssen59804562016-12-28 14:13:21 -080083
fredc0f420372012-04-12 00:02:00 -070084class BluetoothManagerService extends IBluetoothManager.Stub {
85 private static final String TAG = "BluetoothManagerService";
Pavlin Radoslavov41401112016-06-27 15:25:18 -070086 private static final boolean DBG = true;
fredc0f420372012-04-12 00:02:00 -070087
fredc0f420372012-04-12 00:02:00 -070088 private static final String BLUETOOTH_ADMIN_PERM = android.Manifest.permission.BLUETOOTH_ADMIN;
89 private static final String BLUETOOTH_PERM = android.Manifest.permission.BLUETOOTH;
Marie Janssene54b4222017-03-16 18:10:59 -070090
Myles Watsonb5cd11a2017-11-27 16:42:11 -080091 private static final String SECURE_SETTINGS_BLUETOOTH_ADDR_VALID = "bluetooth_addr_valid";
92 private static final String SECURE_SETTINGS_BLUETOOTH_ADDRESS = "bluetooth_address";
93 private static final String SECURE_SETTINGS_BLUETOOTH_NAME = "bluetooth_name";
Marie Janssene54b4222017-03-16 18:10:59 -070094
95 private static final int ACTIVE_LOG_MAX_SIZE = 20;
96 private static final int CRASH_LOG_MAX_SIZE = 100;
Marie Janssene54b4222017-03-16 18:10:59 -070097
fredc0f420372012-04-12 00:02:00 -070098 private static final int TIMEOUT_BIND_MS = 3000; //Maximum msec to wait for a bind
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +053099 //Maximum msec to wait for service restart
100 private static final int SERVICE_RESTART_TIME_MS = 200;
Zhihai Xudd9d17d2013-01-08 17:05:58 -0800101 //Maximum msec to wait for restart due to error
102 private static final int ERROR_RESTART_TIME_MS = 3000;
Zhihai Xu40874a02012-10-08 17:57:03 -0700103 //Maximum msec to delay MESSAGE_USER_SWITCHED
104 private static final int USER_SWITCHED_TIME_MS = 200;
Benjamin Franze8b98922014-11-12 15:57:54 +0000105 // Delay for the addProxy function in msec
106 private static final int ADD_PROXY_DELAY_MS = 100;
fredc0f420372012-04-12 00:02:00 -0700107
108 private static final int MESSAGE_ENABLE = 1;
109 private static final int MESSAGE_DISABLE = 2;
fredc649fe492012-04-19 01:07:18 -0700110 private static final int MESSAGE_REGISTER_ADAPTER = 20;
111 private static final int MESSAGE_UNREGISTER_ADAPTER = 21;
112 private static final int MESSAGE_REGISTER_STATE_CHANGE_CALLBACK = 30;
113 private static final int MESSAGE_UNREGISTER_STATE_CHANGE_CALLBACK = 31;
114 private static final int MESSAGE_BLUETOOTH_SERVICE_CONNECTED = 40;
115 private static final int MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED = 41;
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +0530116 private static final int MESSAGE_RESTART_BLUETOOTH_SERVICE = 42;
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -0700117 private static final int MESSAGE_BLUETOOTH_STATE_CHANGE = 60;
118 private static final int MESSAGE_TIMEOUT_BIND = 100;
119 private static final int MESSAGE_TIMEOUT_UNBIND = 101;
Ajay Panicker4bb48302016-03-31 14:14:27 -0700120 private static final int MESSAGE_GET_NAME_AND_ADDRESS = 200;
Zhihai Xu40874a02012-10-08 17:57:03 -0700121 private static final int MESSAGE_USER_SWITCHED = 300;
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -0700122 private static final int MESSAGE_USER_UNLOCKED = 301;
Benjamin Franze8b98922014-11-12 15:57:54 +0000123 private static final int MESSAGE_ADD_PROXY_DELAYED = 400;
124 private static final int MESSAGE_BIND_PROFILE_SERVICE = 401;
Stanley Tng873b5702017-05-01 21:27:31 -0700125 private static final int MESSAGE_RESTORE_USER_SETTING = 500;
126
127 private static final int RESTORE_SETTING_TO_ON = 1;
128 private static final int RESTORE_SETTING_TO_OFF = 0;
Marie Janssencb21ad72016-12-13 10:51:02 -0800129
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -0700130 private static final int MAX_ERROR_RESTART_RETRIES = 6;
Zhihai Xudd9d17d2013-01-08 17:05:58 -0800131
Zhihai Xu401202b2012-12-03 11:36:21 -0800132 // Bluetooth persisted setting is off
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800133 private static final int BLUETOOTH_OFF = 0;
Zhihai Xu401202b2012-12-03 11:36:21 -0800134 // Bluetooth persisted setting is on
135 // and Airplane mode won't affect Bluetooth state at start up
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800136 private static final int BLUETOOTH_ON_BLUETOOTH = 1;
Zhihai Xu401202b2012-12-03 11:36:21 -0800137 // Bluetooth persisted setting is on
138 // but Airplane mode will affect Bluetooth state at start up
139 // and Airplane mode will have higher priority.
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800140 private static final int BLUETOOTH_ON_AIRPLANE = 2;
fredc0f420372012-04-12 00:02:00 -0700141
Matthew Xieddf7e472013-03-01 18:41:02 -0800142 private static final int SERVICE_IBLUETOOTH = 1;
143 private static final int SERVICE_IBLUETOOTHGATT = 2;
144
fredc0f420372012-04-12 00:02:00 -0700145 private final Context mContext;
Matthew Xiecdce0b92012-07-12 19:06:15 -0700146
147 // Locks are not provided for mName and mAddress.
148 // They are accessed in handler or broadcast receiver, same thread context.
fredc0f420372012-04-12 00:02:00 -0700149 private String mAddress;
150 private String mName;
Matthew Xie6fde3092012-07-11 17:10:07 -0700151 private final ContentResolver mContentResolver;
152 private final RemoteCallbackList<IBluetoothManagerCallback> mCallbacks;
153 private final RemoteCallbackList<IBluetoothStateChangeCallback> mStateChangeCallbacks;
Marie Janssen9db28eb2016-01-12 16:05:15 -0800154 private IBinder mBluetoothBinder;
fredc649fe492012-04-19 01:07:18 -0700155 private IBluetooth mBluetooth;
Matthew Xieddf7e472013-03-01 18:41:02 -0800156 private IBluetoothGatt mBluetoothGatt;
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800157 private final ReentrantReadWriteLock mBluetoothLock = new ReentrantReadWriteLock();
fredc649fe492012-04-19 01:07:18 -0700158 private boolean mBinding;
159 private boolean mUnbinding;
Marie Janssen59804562016-12-28 14:13:21 -0800160
Zhihai Xu401202b2012-12-03 11:36:21 -0800161 // used inside handler thread
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700162 private boolean mQuietEnable = false;
Marie Janssen59804562016-12-28 14:13:21 -0800163 private boolean mEnable;
164
Jack He8caab152018-03-02 13:08:36 -0800165 private static CharSequence timeToLog(long timestamp) {
Marie Janssene54b4222017-03-16 18:10:59 -0700166 return android.text.format.DateFormat.format("MM-dd HH:mm:ss", timestamp);
167 }
168
Marie Janssen59804562016-12-28 14:13:21 -0800169 /**
170 * Used for tracking apps that enabled / disabled Bluetooth.
171 */
172 private class ActiveLog {
Jack He8caab152018-03-02 13:08:36 -0800173 private int mReason;
Marie Janssen59804562016-12-28 14:13:21 -0800174 private String mPackageName;
175 private boolean mEnable;
176 private long mTimestamp;
177
Jack He8caab152018-03-02 13:08:36 -0800178 ActiveLog(int reason, String packageName, boolean enable, long timestamp) {
179 mReason = reason;
Marie Janssen59804562016-12-28 14:13:21 -0800180 mPackageName = packageName;
181 mEnable = enable;
182 mTimestamp = timestamp;
183 }
184
Marie Janssen59804562016-12-28 14:13:21 -0800185 public String toString() {
Jack He8caab152018-03-02 13:08:36 -0800186 return timeToLog(mTimestamp) + (mEnable ? " Enabled " : " Disabled ")
187 + " due to " + getEnableDisableReasonString(mReason) + " by " + mPackageName;
Marie Janssen59804562016-12-28 14:13:21 -0800188 }
189
190 }
191
Jack He8caab152018-03-02 13:08:36 -0800192 private final LinkedList<ActiveLog> mActiveLogs = new LinkedList<>();
193 private final LinkedList<Long> mCrashTimestamps = new LinkedList<>();
Marie Janssene54b4222017-03-16 18:10:59 -0700194 private int mCrashes;
Marie Janssen12a35012017-06-26 07:21:03 -0700195 private long mLastEnabledTime;
Marie Janssen59804562016-12-28 14:13:21 -0800196
197 // configuration from external IBinder call which is used to
Zhihai Xu401202b2012-12-03 11:36:21 -0800198 // synchronize with broadcast receiver.
199 private boolean mQuietEnableExternal;
Zhihai Xu401202b2012-12-03 11:36:21 -0800200 private boolean mEnableExternal;
Marie Janssen59804562016-12-28 14:13:21 -0800201
202 // Map of apps registered to keep BLE scanning on.
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800203 private Map<IBinder, ClientDeathRecipient> mBleApps =
204 new ConcurrentHashMap<IBinder, ClientDeathRecipient>();
Marie Janssen59804562016-12-28 14:13:21 -0800205
Zhihai Xu40874a02012-10-08 17:57:03 -0700206 private int mState;
Zhihai Xu40874a02012-10-08 17:57:03 -0700207 private final BluetoothHandler mHandler;
Zhihai Xudd9d17d2013-01-08 17:05:58 -0800208 private int mErrorRecoveryRetryCounter;
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200209 private final int mSystemUiUid;
fredc0f420372012-04-12 00:02:00 -0700210
Stanley Tng61dbd812019-01-13 16:04:31 -0800211 private boolean mIsHearingAidProfileSupported;
212
Benjamin Franze8b98922014-11-12 15:57:54 +0000213 // Save a ProfileServiceConnections object for each of the bound
214 // bluetooth profile services
Jack He8caab152018-03-02 13:08:36 -0800215 private final Map<Integer, ProfileServiceConnections> mProfileServices = new HashMap<>();
Benjamin Franze8b98922014-11-12 15:57:54 +0000216
Svetoslav Ganovac69be52016-06-29 17:31:44 -0700217 private final boolean mPermissionReviewRequired;
218
Marie Janssen59804562016-12-28 14:13:21 -0800219 private final IBluetoothCallback mBluetoothCallback = new IBluetoothCallback.Stub() {
fredcbf072a72012-05-09 16:52:50 -0700220 @Override
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800221 public void onBluetoothStateChange(int prevState, int newState) throws RemoteException {
222 Message msg =
223 mHandler.obtainMessage(MESSAGE_BLUETOOTH_STATE_CHANGE, prevState, newState);
fredcbf072a72012-05-09 16:52:50 -0700224 mHandler.sendMessage(msg);
225 }
226 };
227
Lenka Trochtova63d5e4a72016-12-02 12:19:39 +0100228 private final UserRestrictionsListener mUserRestrictionsListener =
229 new UserRestrictionsListener() {
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800230 @Override
231 public void onUserRestrictionsChanged(int userId, Bundle newRestrictions,
232 Bundle prevRestrictions) {
Myles Watson6291fae2017-06-29 03:12:02 -0700233
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800234 if (UserRestrictionsUtils.restrictionsChanged(prevRestrictions, newRestrictions,
235 UserManager.DISALLOW_BLUETOOTH_SHARING)) {
236 updateOppLauncherComponentState(userId,
237 newRestrictions.getBoolean(UserManager.DISALLOW_BLUETOOTH_SHARING));
238 }
Pavel Grafov4f4f6f82017-03-28 13:44:04 +0100239
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800240 // DISALLOW_BLUETOOTH can only be set by DO or PO on the system user.
241 if (userId == UserHandle.USER_SYSTEM
242 && UserRestrictionsUtils.restrictionsChanged(prevRestrictions,
243 newRestrictions, UserManager.DISALLOW_BLUETOOTH)) {
244 if (userId == UserHandle.USER_SYSTEM && newRestrictions.getBoolean(
245 UserManager.DISALLOW_BLUETOOTH)) {
246 updateOppLauncherComponentState(userId, true); // Sharing disallowed
Jack He8caab152018-03-02 13:08:36 -0800247 sendDisableMsg(BluetoothProtoEnums.ENABLE_DISABLE_REASON_DISALLOWED,
248 mContext.getPackageName());
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800249 } else {
250 updateOppLauncherComponentState(userId, newRestrictions.getBoolean(
251 UserManager.DISALLOW_BLUETOOTH_SHARING));
252 }
253 }
Lenka Trochtova63d5e4a72016-12-02 12:19:39 +0100254 }
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800255 };
Lenka Trochtova63d5e4a72016-12-02 12:19:39 +0100256
Ajay Panicker467bc042017-02-22 12:23:15 -0800257 private final ContentObserver mAirplaneModeObserver = new ContentObserver(null) {
258 @Override
259 public void onChange(boolean unused) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800260 synchronized (this) {
Ajay Panicker467bc042017-02-22 12:23:15 -0800261 if (isBluetoothPersistedStateOn()) {
262 if (isAirplaneModeOn()) {
263 persistBluetoothSetting(BLUETOOTH_ON_AIRPLANE);
264 } else {
265 persistBluetoothSetting(BLUETOOTH_ON_BLUETOOTH);
266 }
267 }
268
269 int st = BluetoothAdapter.STATE_OFF;
270 try {
271 mBluetoothLock.readLock().lock();
272 if (mBluetooth != null) {
273 st = mBluetooth.getState();
274 }
275 } catch (RemoteException e) {
276 Slog.e(TAG, "Unable to call getState", e);
277 return;
278 } finally {
279 mBluetoothLock.readLock().unlock();
280 }
281
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800282 Slog.d(TAG,
283 "Airplane Mode change - current state: " + BluetoothAdapter.nameForState(
Rene Mayrhofer0860f292018-11-28 11:32:40 -0800284 st) + ", isAirplaneModeOn()=" + isAirplaneModeOn());
Ajay Panicker467bc042017-02-22 12:23:15 -0800285
286 if (isAirplaneModeOn()) {
287 // Clear registered LE apps to force shut-off
288 clearBleApps();
289
290 // If state is BLE_ON make sure we trigger disableBLE
291 if (st == BluetoothAdapter.STATE_BLE_ON) {
292 try {
293 mBluetoothLock.readLock().lock();
294 if (mBluetooth != null) {
Hansong Zhang276eb1b2018-04-23 11:17:17 -0700295 addActiveLog(
296 BluetoothProtoEnums.ENABLE_DISABLE_REASON_AIRPLANE_MODE,
297 mContext.getPackageName(), false);
Ajay Panicker467bc042017-02-22 12:23:15 -0800298 mBluetooth.onBrEdrDown();
299 mEnable = false;
300 mEnableExternal = false;
301 }
302 } catch (RemoteException e) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800303 Slog.e(TAG, "Unable to call onBrEdrDown", e);
Ajay Panicker467bc042017-02-22 12:23:15 -0800304 } finally {
305 mBluetoothLock.readLock().unlock();
306 }
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800307 } else if (st == BluetoothAdapter.STATE_ON) {
Jack He8caab152018-03-02 13:08:36 -0800308 sendDisableMsg(BluetoothProtoEnums.ENABLE_DISABLE_REASON_AIRPLANE_MODE,
309 mContext.getPackageName());
Ajay Panicker467bc042017-02-22 12:23:15 -0800310 }
311 } else if (mEnableExternal) {
Jack He8caab152018-03-02 13:08:36 -0800312 sendEnableMsg(mQuietEnableExternal,
313 BluetoothProtoEnums.ENABLE_DISABLE_REASON_AIRPLANE_MODE,
314 mContext.getPackageName());
Ajay Panicker467bc042017-02-22 12:23:15 -0800315 }
316 }
317 }
318 };
319
fredcbf072a72012-05-09 16:52:50 -0700320 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
fredc0f420372012-04-12 00:02:00 -0700321 @Override
322 public void onReceive(Context context, Intent intent) {
323 String action = intent.getAction();
fredcbf072a72012-05-09 16:52:50 -0700324 if (BluetoothAdapter.ACTION_LOCAL_NAME_CHANGED.equals(action)) {
fredc0f420372012-04-12 00:02:00 -0700325 String newName = intent.getStringExtra(BluetoothAdapter.EXTRA_LOCAL_NAME);
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800326 if (DBG) {
327 Slog.d(TAG, "Bluetooth Adapter name changed to " + newName);
328 }
fredc0f420372012-04-12 00:02:00 -0700329 if (newName != null) {
330 storeNameAndAddress(newName, null);
331 }
Stanley Tngdd749b02017-04-17 22:35:45 -0700332 } else if (BluetoothAdapter.ACTION_BLUETOOTH_ADDRESS_CHANGED.equals(action)) {
333 String newAddress = intent.getStringExtra(BluetoothAdapter.EXTRA_BLUETOOTH_ADDRESS);
334 if (newAddress != null) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800335 if (DBG) {
336 Slog.d(TAG, "Bluetooth Adapter address changed to " + newAddress);
337 }
Stanley Tngdd749b02017-04-17 22:35:45 -0700338 storeNameAndAddress(null, newAddress);
339 } else {
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800340 if (DBG) {
341 Slog.e(TAG, "No Bluetooth Adapter address parameter found");
342 }
Stanley Tngdd749b02017-04-17 22:35:45 -0700343 }
Stanley Tng873b5702017-05-01 21:27:31 -0700344 } else if (Intent.ACTION_SETTING_RESTORED.equals(action)) {
345 final String name = intent.getStringExtra(Intent.EXTRA_SETTING_NAME);
346 if (Settings.Global.BLUETOOTH_ON.equals(name)) {
347 // The Bluetooth On state may be changed during system restore.
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800348 final String prevValue =
349 intent.getStringExtra(Intent.EXTRA_SETTING_PREVIOUS_VALUE);
350 final String newValue = intent.getStringExtra(Intent.EXTRA_SETTING_NEW_VALUE);
Stanley Tng873b5702017-05-01 21:27:31 -0700351
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800352 if (DBG) {
353 Slog.d(TAG,
354 "ACTION_SETTING_RESTORED with BLUETOOTH_ON, prevValue=" + prevValue
355 + ", newValue=" + newValue);
356 }
Stanley Tng873b5702017-05-01 21:27:31 -0700357
358 if ((newValue != null) && (prevValue != null) && !prevValue.equals(newValue)) {
359 Message msg = mHandler.obtainMessage(MESSAGE_RESTORE_USER_SETTING,
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800360 newValue.equals("0") ? RESTORE_SETTING_TO_OFF
361 : RESTORE_SETTING_TO_ON, 0);
Stanley Tng873b5702017-05-01 21:27:31 -0700362 mHandler.sendMessage(msg);
363 }
364 }
fredc0f420372012-04-12 00:02:00 -0700365 }
366 }
367 };
368
369 BluetoothManagerService(Context context) {
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700370 mHandler = new BluetoothHandler(IoThread.get().getLooper());
Zhihai Xu40874a02012-10-08 17:57:03 -0700371
fredc0f420372012-04-12 00:02:00 -0700372 mContext = context;
Svetoslav Ganovac69be52016-06-29 17:31:44 -0700373
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800374 mPermissionReviewRequired = context.getResources()
375 .getBoolean(com.android.internal.R.bool.config_permissionReviewRequired);
Svetoslav Ganovac69be52016-06-29 17:31:44 -0700376
Marie Janssene54b4222017-03-16 18:10:59 -0700377 mCrashes = 0;
fredc0f420372012-04-12 00:02:00 -0700378 mBluetooth = null;
Marie Janssen9db28eb2016-01-12 16:05:15 -0800379 mBluetoothBinder = null;
Nitin Arorad055adb2015-03-02 15:03:51 -0800380 mBluetoothGatt = null;
fredc0f420372012-04-12 00:02:00 -0700381 mBinding = false;
382 mUnbinding = false;
Zhihai Xu40874a02012-10-08 17:57:03 -0700383 mEnable = false;
384 mState = BluetoothAdapter.STATE_OFF;
Zhihai Xu401202b2012-12-03 11:36:21 -0800385 mQuietEnableExternal = false;
386 mEnableExternal = false;
fredc0f420372012-04-12 00:02:00 -0700387 mAddress = null;
388 mName = null;
Zhihai Xudd9d17d2013-01-08 17:05:58 -0800389 mErrorRecoveryRetryCounter = 0;
fredc0f420372012-04-12 00:02:00 -0700390 mContentResolver = context.getContentResolver();
Wei Wange4a744b2015-06-11 17:50:29 -0700391 // Observe BLE scan only mode settings change.
392 registerForBleScanModeChange();
fredcd6883532012-04-25 17:46:13 -0700393 mCallbacks = new RemoteCallbackList<IBluetoothManagerCallback>();
394 mStateChangeCallbacks = new RemoteCallbackList<IBluetoothStateChangeCallback>();
Stanley Tng873b5702017-05-01 21:27:31 -0700395
Stanley Tng61dbd812019-01-13 16:04:31 -0800396 mIsHearingAidProfileSupported = context.getResources()
397 .getBoolean(com.android.internal.R.bool.config_hearing_aid_profile_supported);
398
Stanley Tngcbfcbd12018-06-19 08:48:10 -0700399 // TODO: We need a more generic way to initialize the persist keys of FeatureFlagUtils
Stanley Tngcbfcbd12018-06-19 08:48:10 -0700400 String value = SystemProperties.get(FeatureFlagUtils.PERSIST_PREFIX + FeatureFlagUtils.HEARING_AID_SETTINGS);
401 if (!TextUtils.isEmpty(value)) {
Stanley Tng61dbd812019-01-13 16:04:31 -0800402 boolean isHearingAidEnabled = Boolean.parseBoolean(value);
Stanley Tngcbfcbd12018-06-19 08:48:10 -0700403 Log.v(TAG, "set feature flag HEARING_AID_SETTINGS to " + isHearingAidEnabled);
404 FeatureFlagUtils.setEnabled(context, FeatureFlagUtils.HEARING_AID_SETTINGS, isHearingAidEnabled);
Stanley Tng61dbd812019-01-13 16:04:31 -0800405 if (isHearingAidEnabled && !mIsHearingAidProfileSupported) {
406 // Overwrite to enable support by FeatureFlag
407 mIsHearingAidProfileSupported = true;
408 }
Stanley Tngcbfcbd12018-06-19 08:48:10 -0700409 }
410
Stanley Tng873b5702017-05-01 21:27:31 -0700411 IntentFilter filter = new IntentFilter();
412 filter.addAction(BluetoothAdapter.ACTION_LOCAL_NAME_CHANGED);
413 filter.addAction(BluetoothAdapter.ACTION_BLUETOOTH_ADDRESS_CHANGED);
414 filter.addAction(Intent.ACTION_SETTING_RESTORED);
Dianne Hackbornd83a0962014-05-02 16:28:33 -0700415 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
Matthew Xie6fde3092012-07-11 17:10:07 -0700416 mContext.registerReceiver(mReceiver, filter);
Stanley Tng873b5702017-05-01 21:27:31 -0700417
fredc0f420372012-04-12 00:02:00 -0700418 loadStoredNameAndAddress();
Zhihai Xu401202b2012-12-03 11:36:21 -0800419 if (isBluetoothPersistedStateOn()) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800420 if (DBG) {
421 Slog.d(TAG, "Startup: Bluetooth persisted state is ON.");
422 }
Zhihai Xu401202b2012-12-03 11:36:21 -0800423 mEnableExternal = true;
fredc0f420372012-04-12 00:02:00 -0700424 }
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200425
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800426 String airplaneModeRadios =
427 Settings.Global.getString(mContentResolver, Settings.Global.AIRPLANE_MODE_RADIOS);
428 if (airplaneModeRadios == null || airplaneModeRadios.contains(
429 Settings.Global.RADIO_BLUETOOTH)) {
Ajay Panicker467bc042017-02-22 12:23:15 -0800430 mContentResolver.registerContentObserver(
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800431 Settings.Global.getUriFor(Settings.Global.AIRPLANE_MODE_ON), true,
432 mAirplaneModeObserver);
Ajay Panicker467bc042017-02-22 12:23:15 -0800433 }
434
Marie Janssen59804562016-12-28 14:13:21 -0800435 int systemUiUid = -1;
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200436 try {
Arthur Hsuf3f95a92018-01-11 16:46:22 -0800437 // Check if device is configured with no home screen, which implies no SystemUI.
438 boolean noHome = mContext.getResources().getBoolean(R.bool.config_noHomeScreen);
439 if (!noHome) {
440 systemUiUid = mContext.getPackageManager()
441 .getPackageUidAsUser("com.android.systemui", PackageManager.MATCH_SYSTEM_ONLY,
442 UserHandle.USER_SYSTEM);
443 }
444 Slog.d(TAG, "Detected SystemUiUid: " + Integer.toString(systemUiUid));
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200445 } catch (PackageManager.NameNotFoundException e) {
Joe LaPennaacddf2b2015-09-04 12:52:42 -0700446 // Some platforms, such as wearables do not have a system ui.
Jeff Sharkey67609c72016-03-05 14:29:13 -0700447 Slog.w(TAG, "Unable to resolve SystemUI's UID.", e);
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200448 }
Marie Janssen59804562016-12-28 14:13:21 -0800449 mSystemUiUid = systemUiUid;
fredc0f420372012-04-12 00:02:00 -0700450 }
451
fredc649fe492012-04-19 01:07:18 -0700452 /**
453 * Returns true if airplane mode is currently on
454 */
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800455 private boolean isAirplaneModeOn() {
Christopher Tatec09cdce2012-09-10 16:50:14 -0700456 return Settings.Global.getInt(mContext.getContentResolver(),
457 Settings.Global.AIRPLANE_MODE_ON, 0) == 1;
fredc649fe492012-04-19 01:07:18 -0700458 }
459
Arthur Hsu2433baf2018-01-11 11:05:11 -0800460 private boolean supportBluetoothPersistedState() {
461 return mContext.getResources().getBoolean(R.bool.config_supportBluetoothPersistedState);
462 }
463
fredc649fe492012-04-19 01:07:18 -0700464 /**
465 * Returns true if the Bluetooth saved state is "on"
466 */
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800467 private boolean isBluetoothPersistedStateOn() {
Arthur Hsu2433baf2018-01-11 11:05:11 -0800468 if (!supportBluetoothPersistedState()) {
469 return false;
470 }
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800471 int state = Settings.Global.getInt(mContentResolver, Settings.Global.BLUETOOTH_ON, -1);
472 if (DBG) {
473 Slog.d(TAG, "Bluetooth persisted state: " + state);
474 }
Marie Janssen9fa24912016-10-18 10:04:24 -0700475 return state != BLUETOOTH_OFF;
Zhihai Xu401202b2012-12-03 11:36:21 -0800476 }
477
478 /**
479 * Returns true if the Bluetooth saved state is BLUETOOTH_ON_BLUETOOTH
480 */
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800481 private boolean isBluetoothPersistedStateOnBluetooth() {
Arthur Hsu2433baf2018-01-11 11:05:11 -0800482 if (!supportBluetoothPersistedState()) {
483 return false;
484 }
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800485 return Settings.Global.getInt(mContentResolver, Settings.Global.BLUETOOTH_ON,
486 BLUETOOTH_ON_BLUETOOTH) == BLUETOOTH_ON_BLUETOOTH;
fredc649fe492012-04-19 01:07:18 -0700487 }
488
489 /**
490 * Save the Bluetooth on/off state
fredc649fe492012-04-19 01:07:18 -0700491 */
Zhihai Xu401202b2012-12-03 11:36:21 -0800492 private void persistBluetoothSetting(int value) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800493 if (DBG) {
494 Slog.d(TAG, "Persisting Bluetooth Setting: " + value);
495 }
Marie Janssenfa630682016-12-15 13:51:30 -0800496 // waive WRITE_SECURE_SETTINGS permission check
497 long callingIdentity = Binder.clearCallingIdentity();
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800498 Settings.Global.putInt(mContext.getContentResolver(), Settings.Global.BLUETOOTH_ON, value);
Marie Janssenfa630682016-12-15 13:51:30 -0800499 Binder.restoreCallingIdentity(callingIdentity);
fredc649fe492012-04-19 01:07:18 -0700500 }
501
502 /**
503 * Returns true if the Bluetooth Adapter's name and address is
504 * locally cached
505 * @return
506 */
fredc0f420372012-04-12 00:02:00 -0700507 private boolean isNameAndAddressSet() {
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800508 return mName != null && mAddress != null && mName.length() > 0 && mAddress.length() > 0;
fredc0f420372012-04-12 00:02:00 -0700509 }
510
fredc649fe492012-04-19 01:07:18 -0700511 /**
512 * Retrieve the Bluetooth Adapter's name and address and save it in
513 * in the local cache
514 */
fredc0f420372012-04-12 00:02:00 -0700515 private void loadStoredNameAndAddress() {
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800516 if (DBG) {
517 Slog.d(TAG, "Loading stored name and address");
518 }
519 if (mContext.getResources()
520 .getBoolean(com.android.internal.R.bool.config_bluetooth_address_validation)
521 && Settings.Secure.getInt(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDR_VALID, 0)
522 == 0) {
Zhihai Xud31c3222012-10-31 16:08:57 -0700523 // if the valid flag is not set, don't load the address and name
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800524 if (DBG) {
525 Slog.d(TAG, "invalid bluetooth name and address stored");
526 }
Zhihai Xud31c3222012-10-31 16:08:57 -0700527 return;
528 }
fredc0f420372012-04-12 00:02:00 -0700529 mName = Settings.Secure.getString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_NAME);
530 mAddress = Settings.Secure.getString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDRESS);
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800531 if (DBG) {
532 Slog.d(TAG, "Stored bluetooth Name=" + mName + ",Address=" + mAddress);
533 }
fredc0f420372012-04-12 00:02:00 -0700534 }
535
fredc649fe492012-04-19 01:07:18 -0700536 /**
537 * Save the Bluetooth name and address in the persistent store.
538 * Only non-null values will be saved.
539 * @param name
540 * @param address
541 */
fredc0f420372012-04-12 00:02:00 -0700542 private void storeNameAndAddress(String name, String address) {
543 if (name != null) {
544 Settings.Secure.putString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_NAME, name);
fredc0f420372012-04-12 00:02:00 -0700545 mName = name;
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800546 if (DBG) {
547 Slog.d(TAG, "Stored Bluetooth name: " + Settings.Secure.getString(mContentResolver,
548 SECURE_SETTINGS_BLUETOOTH_NAME));
549 }
fredc0f420372012-04-12 00:02:00 -0700550 }
551
552 if (address != null) {
553 Settings.Secure.putString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDRESS, address);
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800554 mAddress = address;
555 if (DBG) {
556 Slog.d(TAG,
557 "Stored Bluetoothaddress: " + Settings.Secure.getString(mContentResolver,
558 SECURE_SETTINGS_BLUETOOTH_ADDRESS));
559 }
fredc0f420372012-04-12 00:02:00 -0700560 }
Zhihai Xud31c3222012-10-31 16:08:57 -0700561
562 if ((name != null) && (address != null)) {
563 Settings.Secure.putInt(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDR_VALID, 1);
564 }
fredc0f420372012-04-12 00:02:00 -0700565 }
566
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800567 public IBluetooth registerAdapter(IBluetoothManagerCallback callback) {
Natalie Silvanovich55db6462014-05-01 16:12:23 -0700568 if (callback == null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700569 Slog.w(TAG, "Callback is null in registerAdapter");
Natalie Silvanovich55db6462014-05-01 16:12:23 -0700570 return null;
571 }
fredc0f420372012-04-12 00:02:00 -0700572 Message msg = mHandler.obtainMessage(MESSAGE_REGISTER_ADAPTER);
573 msg.obj = callback;
574 mHandler.sendMessage(msg);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700575
576 return mBluetooth;
fredc0f420372012-04-12 00:02:00 -0700577 }
578
579 public void unregisterAdapter(IBluetoothManagerCallback callback) {
Natalie Silvanovich55db6462014-05-01 16:12:23 -0700580 if (callback == null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700581 Slog.w(TAG, "Callback is null in unregisterAdapter");
Natalie Silvanovich55db6462014-05-01 16:12:23 -0700582 return;
583 }
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800584 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");
fredc0f420372012-04-12 00:02:00 -0700585 Message msg = mHandler.obtainMessage(MESSAGE_UNREGISTER_ADAPTER);
586 msg.obj = callback;
587 mHandler.sendMessage(msg);
588 }
589
590 public void registerStateChangeCallback(IBluetoothStateChangeCallback callback) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800591 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");
Marie Janssencb21ad72016-12-13 10:51:02 -0800592 if (callback == null) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800593 Slog.w(TAG, "registerStateChangeCallback: Callback is null!");
594 return;
Marie Janssencb21ad72016-12-13 10:51:02 -0800595 }
fredc0f420372012-04-12 00:02:00 -0700596 Message msg = mHandler.obtainMessage(MESSAGE_REGISTER_STATE_CHANGE_CALLBACK);
597 msg.obj = callback;
598 mHandler.sendMessage(msg);
599 }
600
601 public void unregisterStateChangeCallback(IBluetoothStateChangeCallback callback) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800602 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");
Marie Janssencb21ad72016-12-13 10:51:02 -0800603 if (callback == null) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800604 Slog.w(TAG, "unregisterStateChangeCallback: Callback is null!");
605 return;
Marie Janssencb21ad72016-12-13 10:51:02 -0800606 }
fredc0f420372012-04-12 00:02:00 -0700607 Message msg = mHandler.obtainMessage(MESSAGE_UNREGISTER_STATE_CHANGE_CALLBACK);
608 msg.obj = callback;
609 mHandler.sendMessage(msg);
610 }
611
612 public boolean isEnabled() {
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800613 if ((Binder.getCallingUid() != Process.SYSTEM_UID) && (!checkIfCallerIsForegroundUser())) {
614 Slog.w(TAG, "isEnabled(): not allowed for non-active and non system user");
Zhihai Xu40874a02012-10-08 17:57:03 -0700615 return false;
616 }
617
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700618 try {
619 mBluetoothLock.readLock().lock();
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800620 if (mBluetooth != null) {
621 return mBluetooth.isEnabled();
622 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700623 } catch (RemoteException e) {
624 Slog.e(TAG, "isEnabled()", e);
625 } finally {
626 mBluetoothLock.readLock().unlock();
fredc0f420372012-04-12 00:02:00 -0700627 }
628 return false;
629 }
630
Christine Hallstrom995c90a2016-05-25 15:49:08 -0700631 public int getState() {
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800632 if ((Binder.getCallingUid() != Process.SYSTEM_UID) && (!checkIfCallerIsForegroundUser())) {
Marie Janssencb21ad72016-12-13 10:51:02 -0800633 Slog.w(TAG, "getState(): report OFF for non-active and non system user");
Christine Hallstrom995c90a2016-05-25 15:49:08 -0700634 return BluetoothAdapter.STATE_OFF;
635 }
636
637 try {
638 mBluetoothLock.readLock().lock();
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800639 if (mBluetooth != null) {
640 return mBluetooth.getState();
641 }
Christine Hallstrom995c90a2016-05-25 15:49:08 -0700642 } catch (RemoteException e) {
643 Slog.e(TAG, "getState()", e);
644 } finally {
645 mBluetoothLock.readLock().unlock();
646 }
647 return BluetoothAdapter.STATE_OFF;
648 }
649
Nitin Arorad055adb2015-03-02 15:03:51 -0800650 class ClientDeathRecipient implements IBinder.DeathRecipient {
Marie Janssen59804562016-12-28 14:13:21 -0800651 private String mPackageName;
652
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800653 ClientDeathRecipient(String packageName) {
Marie Janssen59804562016-12-28 14:13:21 -0800654 mPackageName = packageName;
655 }
656
Nitin Arorad055adb2015-03-02 15:03:51 -0800657 public void binderDied() {
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800658 if (DBG) {
659 Slog.d(TAG, "Binder is dead - unregister " + mPackageName);
Marie Janssen2977c3e2016-11-09 12:01:24 -0800660 }
Stanley Tng2c5fd282018-03-19 13:06:45 -0700661
662 for (Map.Entry<IBinder, ClientDeathRecipient> entry : mBleApps.entrySet()) {
663 IBinder token = entry.getKey();
664 ClientDeathRecipient deathRec = entry.getValue();
665 if (deathRec.equals(this)) {
Stanley Tng600109c2018-03-20 16:54:27 -0700666 updateBleAppCount(token, false, mPackageName);
Stanley Tng2c5fd282018-03-19 13:06:45 -0700667 break;
668 }
669 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800670 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800671
Marie Janssen59804562016-12-28 14:13:21 -0800672 public String getPackageName() {
673 return mPackageName;
674 }
675 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800676
Wei Wang67d84162015-04-26 17:04:29 -0700677 @Override
678 public boolean isBleScanAlwaysAvailable() {
Marie Janssena80d7452016-10-25 10:47:51 -0700679 if (isAirplaneModeOn() && !mEnable) {
680 return false;
681 }
Wei Wang67d84162015-04-26 17:04:29 -0700682 try {
Jack He8caab152018-03-02 13:08:36 -0800683 return Settings.Global.getInt(mContentResolver,
684 Settings.Global.BLE_SCAN_ALWAYS_AVAILABLE) != 0;
Wei Wang67d84162015-04-26 17:04:29 -0700685 } catch (SettingNotFoundException e) {
686 }
687 return false;
688 }
689
Stanley Tng61dbd812019-01-13 16:04:31 -0800690 @Override
691 public boolean isHearingAidProfileSupported() {
692 return mIsHearingAidProfileSupported;
693 }
694
Wei Wange4a744b2015-06-11 17:50:29 -0700695 // Monitor change of BLE scan only mode settings.
696 private void registerForBleScanModeChange() {
697 ContentObserver contentObserver = new ContentObserver(null) {
698 @Override
699 public void onChange(boolean selfChange) {
Marie Janssen2977c3e2016-11-09 12:01:24 -0800700 if (isBleScanAlwaysAvailable()) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800701 // Nothing to do
702 return;
Marie Janssen2977c3e2016-11-09 12:01:24 -0800703 }
704 // BLE scan is not available.
705 disableBleScanMode();
706 clearBleApps();
707 try {
708 mBluetoothLock.readLock().lock();
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800709 if (mBluetooth != null) {
Hansong Zhang276eb1b2018-04-23 11:17:17 -0700710 addActiveLog(BluetoothProtoEnums.ENABLE_DISABLE_REASON_APPLICATION_REQUEST,
711 mContext.getPackageName(), false);
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800712 mBluetooth.onBrEdrDown();
713 }
Marie Janssen2977c3e2016-11-09 12:01:24 -0800714 } catch (RemoteException e) {
715 Slog.e(TAG, "error when disabling bluetooth", e);
716 } finally {
717 mBluetoothLock.readLock().unlock();
Wei Wange4a744b2015-06-11 17:50:29 -0700718 }
719 }
720 };
721
722 mContentResolver.registerContentObserver(
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800723 Settings.Global.getUriFor(Settings.Global.BLE_SCAN_ALWAYS_AVAILABLE), false,
724 contentObserver);
Wei Wange4a744b2015-06-11 17:50:29 -0700725 }
726
727 // Disable ble scan only mode.
728 private void disableBleScanMode() {
729 try {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700730 mBluetoothLock.writeLock().lock();
Wei Wange4a744b2015-06-11 17:50:29 -0700731 if (mBluetooth != null && (mBluetooth.getState() != BluetoothAdapter.STATE_ON)) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800732 if (DBG) {
733 Slog.d(TAG, "Reseting the mEnable flag for clean disable");
734 }
Wei Wange4a744b2015-06-11 17:50:29 -0700735 mEnable = false;
736 }
737 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700738 Slog.e(TAG, "getState()", e);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700739 } finally {
740 mBluetoothLock.writeLock().unlock();
Wei Wange4a744b2015-06-11 17:50:29 -0700741 }
742 }
743
Marie Janssen59804562016-12-28 14:13:21 -0800744 public int updateBleAppCount(IBinder token, boolean enable, String packageName) {
745 ClientDeathRecipient r = mBleApps.get(token);
746 if (r == null && enable) {
747 ClientDeathRecipient deathRec = new ClientDeathRecipient(packageName);
748 try {
749 token.linkToDeath(deathRec, 0);
750 } catch (RemoteException ex) {
751 throw new IllegalArgumentException("BLE app (" + packageName + ") already dead!");
Nitin Arorad055adb2015-03-02 15:03:51 -0800752 }
Marie Janssen59804562016-12-28 14:13:21 -0800753 mBleApps.put(token, deathRec);
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800754 if (DBG) {
755 Slog.d(TAG, "Registered for death of " + packageName);
756 }
Marie Janssen59804562016-12-28 14:13:21 -0800757 } else if (!enable && r != null) {
758 // Unregister death recipient as the app goes away.
759 token.unlinkToDeath(r, 0);
760 mBleApps.remove(token);
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800761 if (DBG) {
762 Slog.d(TAG, "Unregistered for death of " + packageName);
763 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800764 }
Marie Janssen2977c3e2016-11-09 12:01:24 -0800765 int appCount = mBleApps.size();
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800766 if (DBG) {
767 Slog.d(TAG, appCount + " registered Ble Apps");
768 }
Marie Janssen2977c3e2016-11-09 12:01:24 -0800769 if (appCount == 0 && mEnable) {
Wei Wange4a744b2015-06-11 17:50:29 -0700770 disableBleScanMode();
Nitin Arorad055adb2015-03-02 15:03:51 -0800771 }
Martin Brabhamc2b06222017-02-27 16:55:07 -0800772 if (appCount == 0 && !mEnableExternal) {
773 sendBrEdrDownCallback();
774 }
Marie Janssen2977c3e2016-11-09 12:01:24 -0800775 return appCount;
Nitin Arorad055adb2015-03-02 15:03:51 -0800776 }
777
Wei Wange4a744b2015-06-11 17:50:29 -0700778 // Clear all apps using BLE scan only mode.
779 private void clearBleApps() {
Marie Janssen2977c3e2016-11-09 12:01:24 -0800780 mBleApps.clear();
Wei Wange4a744b2015-06-11 17:50:29 -0700781 }
782
Marie Janssen59804562016-12-28 14:13:21 -0800783 /** @hide */
Nitin Arorad055adb2015-03-02 15:03:51 -0800784 public boolean isBleAppPresent() {
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800785 if (DBG) {
786 Slog.d(TAG, "isBleAppPresent() count: " + mBleApps.size());
787 }
Marie Janssen2977c3e2016-11-09 12:01:24 -0800788 return mBleApps.size() > 0;
Nitin Arorad055adb2015-03-02 15:03:51 -0800789 }
790
791 /**
Myles Watson304ebf22018-05-11 08:47:24 -0700792 * Call IBluetooth.onLeServiceUp() to continue if Bluetooth should be on.
Nitin Arorad055adb2015-03-02 15:03:51 -0800793 */
Myles Watson304ebf22018-05-11 08:47:24 -0700794 private void continueFromBleOnState() {
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800795 if (DBG) {
Myles Watson304ebf22018-05-11 08:47:24 -0700796 Slog.d(TAG, "continueFromBleOnState()");
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800797 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700798 try {
799 mBluetoothLock.readLock().lock();
Marie Janssenfa630682016-12-15 13:51:30 -0800800 if (mBluetooth == null) {
Myles Watson304ebf22018-05-11 08:47:24 -0700801 Slog.e(TAG, "onBluetoothServiceUp: mBluetooth is null!");
Marie Janssenfa630682016-12-15 13:51:30 -0800802 return;
803 }
804 if (isBluetoothPersistedStateOnBluetooth() || !isBleAppPresent()) {
805 // This triggers transition to STATE_ON
Nitin Arorad055adb2015-03-02 15:03:51 -0800806 mBluetooth.onLeServiceUp();
Nitin Arorad055adb2015-03-02 15:03:51 -0800807 persistBluetoothSetting(BLUETOOTH_ON_BLUETOOTH);
Nitin Arorad055adb2015-03-02 15:03:51 -0800808 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700809 } catch (RemoteException e) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800810 Slog.e(TAG, "Unable to call onServiceUp", e);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700811 } finally {
812 mBluetoothLock.readLock().unlock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800813 }
814 }
815
816 /**
817 * Inform BluetoothAdapter instances that BREDR part is down
818 * and turn off all service and stack if no LE app needs it
819 */
820 private void sendBrEdrDownCallback() {
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800821 if (DBG) {
822 Slog.d(TAG, "Calling sendBrEdrDownCallback callbacks");
823 }
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700824
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700825 if (mBluetooth == null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700826 Slog.w(TAG, "Bluetooth handle is null");
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700827 return;
828 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800829
Martin Brabhamc2b06222017-02-27 16:55:07 -0800830 if (isBleAppPresent()) {
831 // Need to stay at BLE ON. Disconnect all Gatt connections
832 try {
833 mBluetoothGatt.unregAll();
834 } catch (RemoteException e) {
835 Slog.e(TAG, "Unable to disconnect all apps.", e);
836 }
837 } else {
Nitin Arorad055adb2015-03-02 15:03:51 -0800838 try {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700839 mBluetoothLock.readLock().lock();
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800840 if (mBluetooth != null) {
841 mBluetooth.onBrEdrDown();
842 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700843 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700844 Slog.e(TAG, "Call to onBrEdrDown() failed.", e);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700845 } finally {
846 mBluetoothLock.readLock().unlock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800847 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800848 }
Martin Brabhamc2b06222017-02-27 16:55:07 -0800849
Nitin Arorad055adb2015-03-02 15:03:51 -0800850 }
851
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800852 public boolean enableNoAutoConnect(String packageName) {
Lenka Trochtova63d5e4a72016-12-02 12:19:39 +0100853 if (isBluetoothDisallowed()) {
854 if (DBG) {
855 Slog.d(TAG, "enableNoAutoConnect(): not enabling - bluetooth disallowed");
856 }
857 return false;
858 }
859
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700860 mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800861 "Need BLUETOOTH ADMIN permission");
Zhihai Xu40874a02012-10-08 17:57:03 -0700862
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700863 if (DBG) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800864 Slog.d(TAG, "enableNoAutoConnect(): mBluetooth =" + mBluetooth + " mBinding = "
865 + mBinding);
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700866 }
Martijn Coenen8385c5a2012-11-29 10:14:16 -0800867 int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
868
869 if (callingAppId != Process.NFC_UID) {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700870 throw new SecurityException("no permission to enable Bluetooth quietly");
871 }
Martijn Coenen8385c5a2012-11-29 10:14:16 -0800872
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800873 synchronized (mReceiver) {
Zhihai Xu401202b2012-12-03 11:36:21 -0800874 mQuietEnableExternal = true;
875 mEnableExternal = true;
Jack He8caab152018-03-02 13:08:36 -0800876 sendEnableMsg(true,
877 BluetoothProtoEnums.ENABLE_DISABLE_REASON_APPLICATION_REQUEST, packageName);
Zhihai Xu401202b2012-12-03 11:36:21 -0800878 }
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700879 return true;
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700880 }
Ajay Panicker4bb48302016-03-31 14:14:27 -0700881
Svetoslav Ganovac69be52016-06-29 17:31:44 -0700882 public boolean enable(String packageName) throws RemoteException {
883 final int callingUid = Binder.getCallingUid();
884 final boolean callerSystem = UserHandle.getAppId(callingUid) == Process.SYSTEM_UID;
885
Lenka Trochtova63d5e4a72016-12-02 12:19:39 +0100886 if (isBluetoothDisallowed()) {
887 if (DBG) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800888 Slog.d(TAG, "enable(): not enabling - bluetooth disallowed");
Lenka Trochtova63d5e4a72016-12-02 12:19:39 +0100889 }
890 return false;
891 }
892
Svetoslav Ganovac69be52016-06-29 17:31:44 -0700893 if (!callerSystem) {
894 if (!checkIfCallerIsForegroundUser()) {
895 Slog.w(TAG, "enable(): not allowed for non-active and non system user");
896 return false;
897 }
898
899 mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
900 "Need BLUETOOTH ADMIN permission");
901
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800902 if (!isEnabled() && mPermissionReviewRequired && startConsentUiIfNeeded(packageName,
903 callingUid, BluetoothAdapter.ACTION_REQUEST_ENABLE)) {
Svetoslav Ganovac69be52016-06-29 17:31:44 -0700904 return false;
905 }
fredcf2458862012-04-16 15:18:27 -0700906 }
907
Zhihai Xu401202b2012-12-03 11:36:21 -0800908 if (DBG) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800909 Slog.d(TAG, "enable(" + packageName + "): mBluetooth =" + mBluetooth + " mBinding = "
910 + mBinding + " mState = " + BluetoothAdapter.nameForState(mState));
Sanket Agarwal090bf552016-04-21 14:10:55 -0700911 }
Zhihai Xu401202b2012-12-03 11:36:21 -0800912
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800913 synchronized (mReceiver) {
Zhihai Xu401202b2012-12-03 11:36:21 -0800914 mQuietEnableExternal = false;
915 mEnableExternal = true;
916 // waive WRITE_SECURE_SETTINGS permission check
Jack He8caab152018-03-02 13:08:36 -0800917 sendEnableMsg(false,
918 BluetoothProtoEnums.ENABLE_DISABLE_REASON_APPLICATION_REQUEST, packageName);
Zhihai Xu401202b2012-12-03 11:36:21 -0800919 }
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800920 if (DBG) {
921 Slog.d(TAG, "enable returning");
922 }
Zhihai Xu401202b2012-12-03 11:36:21 -0800923 return true;
fredc0f420372012-04-12 00:02:00 -0700924 }
925
Svetoslav Ganovac69be52016-06-29 17:31:44 -0700926 public boolean disable(String packageName, boolean persist) throws RemoteException {
927 final int callingUid = Binder.getCallingUid();
928 final boolean callerSystem = UserHandle.getAppId(callingUid) == Process.SYSTEM_UID;
Zhihai Xu40874a02012-10-08 17:57:03 -0700929
Svetoslav Ganovac69be52016-06-29 17:31:44 -0700930 if (!callerSystem) {
931 if (!checkIfCallerIsForegroundUser()) {
932 Slog.w(TAG, "disable(): not allowed for non-active and non system user");
933 return false;
934 }
935
936 mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
937 "Need BLUETOOTH ADMIN permission");
938
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800939 if (isEnabled() && mPermissionReviewRequired && startConsentUiIfNeeded(packageName,
940 callingUid, BluetoothAdapter.ACTION_REQUEST_DISABLE)) {
Svetoslav Ganovac69be52016-06-29 17:31:44 -0700941 return false;
942 }
Zhihai Xu40874a02012-10-08 17:57:03 -0700943 }
944
fredcf2458862012-04-16 15:18:27 -0700945 if (DBG) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800946 Slog.d(TAG, "disable(): mBluetooth = " + mBluetooth + " mBinding = " + mBinding);
Matthew Xiecdce0b92012-07-12 19:06:15 -0700947 }
fredcf2458862012-04-16 15:18:27 -0700948
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800949 synchronized (mReceiver) {
Zhihai Xu401202b2012-12-03 11:36:21 -0800950 if (persist) {
Zhihai Xu401202b2012-12-03 11:36:21 -0800951 persistBluetoothSetting(BLUETOOTH_OFF);
Zhihai Xu401202b2012-12-03 11:36:21 -0800952 }
953 mEnableExternal = false;
Jack He8caab152018-03-02 13:08:36 -0800954 sendDisableMsg(BluetoothProtoEnums.ENABLE_DISABLE_REASON_APPLICATION_REQUEST,
955 packageName);
Zhihai Xu401202b2012-12-03 11:36:21 -0800956 }
fredc0f420372012-04-12 00:02:00 -0700957 return true;
958 }
959
baishengf62d8692018-01-25 18:07:24 +0800960 private boolean startConsentUiIfNeeded(String packageName,
961 int callingUid, String intentAction) throws RemoteException {
962 if (checkBluetoothPermissionWhenPermissionReviewRequired()) {
963 return false;
964 }
Svetoslav Ganovac69be52016-06-29 17:31:44 -0700965 try {
966 // Validate the package only if we are going to use it
967 ApplicationInfo applicationInfo = mContext.getPackageManager()
968 .getApplicationInfoAsUser(packageName,
969 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
970 UserHandle.getUserId(callingUid));
971 if (applicationInfo.uid != callingUid) {
baishengf62d8692018-01-25 18:07:24 +0800972 throw new SecurityException("Package " + packageName
973 + " not in uid " + callingUid);
Svetoslav Ganovac69be52016-06-29 17:31:44 -0700974 }
975
Ivan Podogovd2d32b12016-12-05 16:46:52 +0000976 Intent intent = new Intent(intentAction);
Ivan Podogov1ab87252017-01-03 12:02:18 +0000977 intent.putExtra(Intent.EXTRA_PACKAGE_NAME, packageName);
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800978 intent.setFlags(
979 Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
Ivan Podogov1ab87252017-01-03 12:02:18 +0000980 try {
981 mContext.startActivity(intent);
982 } catch (ActivityNotFoundException e) {
983 // Shouldn't happen
984 Slog.e(TAG, "Intent to handle action " + intentAction + " missing");
985 return false;
Svetoslav Ganovac69be52016-06-29 17:31:44 -0700986 }
Ivan Podogov1ab87252017-01-03 12:02:18 +0000987 return true;
Svetoslav Ganovac69be52016-06-29 17:31:44 -0700988 } catch (PackageManager.NameNotFoundException e) {
989 throw new RemoteException(e.getMessage());
990 }
Svetoslav Ganovac69be52016-06-29 17:31:44 -0700991 }
992
baishengf62d8692018-01-25 18:07:24 +0800993 /**
994 * Check if the caller must still pass permission check or if the caller is exempted
995 * from the consent UI via the MANAGE_BLUETOOTH_WHEN_PERMISSION_REVIEW_REQUIRED check.
996 *
997 * Commands from some callers may be exempted from triggering the consent UI when
998 * enabling bluetooth. This exemption is checked via the
999 * MANAGE_BLUETOOTH_WHEN_PERMISSION_REVIEW_REQUIRED and allows calls to skip
1000 * the consent UI where it may otherwise be required.
1001 *
1002 * @hide
1003 */
1004 private boolean checkBluetoothPermissionWhenPermissionReviewRequired() {
1005 if (!mPermissionReviewRequired) {
1006 return false;
1007 }
1008 int result = mContext.checkCallingPermission(
1009 android.Manifest.permission.MANAGE_BLUETOOTH_WHEN_PERMISSION_REVIEW_REQUIRED);
1010 return result == PackageManager.PERMISSION_GRANTED;
1011 }
1012
fredc649fe492012-04-19 01:07:18 -07001013 public void unbindAndFinish() {
fredcf2458862012-04-16 15:18:27 -07001014 if (DBG) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001015 Slog.d(TAG, "unbindAndFinish(): " + mBluetooth + " mBinding = " + mBinding
1016 + " mUnbinding = " + mUnbinding);
fredcf2458862012-04-16 15:18:27 -07001017 }
1018
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001019 try {
1020 mBluetoothLock.writeLock().lock();
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001021 if (mUnbinding) {
1022 return;
1023 }
fredc0f420372012-04-12 00:02:00 -07001024 mUnbinding = true;
Pavlin Radoslavove47ec142016-06-01 22:25:18 -07001025 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
Pavlin Radoslavov74f60c02016-09-21 17:28:11 -07001026 mHandler.removeMessages(MESSAGE_BIND_PROFILE_SERVICE);
Zhihai Xu40874a02012-10-08 17:57:03 -07001027 if (mBluetooth != null) {
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001028 //Unregister callback object
1029 try {
1030 mBluetooth.unregisterCallback(mBluetoothCallback);
1031 } catch (RemoteException re) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001032 Slog.e(TAG, "Unable to unregister BluetoothCallback", re);
fredcbf072a72012-05-09 16:52:50 -07001033 }
Marie Janssen9db28eb2016-01-12 16:05:15 -08001034 mBluetoothBinder = null;
fredcd6883532012-04-25 17:46:13 -07001035 mBluetooth = null;
fredc0f420372012-04-12 00:02:00 -07001036 mContext.unbindService(mConnection);
fredcd6883532012-04-25 17:46:13 -07001037 mUnbinding = false;
Zhihai Xu40874a02012-10-08 17:57:03 -07001038 mBinding = false;
fredcf2458862012-04-16 15:18:27 -07001039 } else {
Marie Janssencb21ad72016-12-13 10:51:02 -08001040 mUnbinding = false;
fredc0f420372012-04-12 00:02:00 -07001041 }
Nitin Arorad055adb2015-03-02 15:03:51 -08001042 mBluetoothGatt = null;
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001043 } finally {
1044 mBluetoothLock.writeLock().unlock();
fredc0f420372012-04-12 00:02:00 -07001045 }
1046 }
1047
Matthew Xieddf7e472013-03-01 18:41:02 -08001048 public IBluetoothGatt getBluetoothGatt() {
1049 // sync protection
1050 return mBluetoothGatt;
1051 }
1052
Benjamin Franze8b98922014-11-12 15:57:54 +00001053 @Override
1054 public boolean bindBluetoothProfileService(int bluetoothProfile,
1055 IBluetoothProfileServiceConnection proxy) {
1056 if (!mEnable) {
1057 if (DBG) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001058 Slog.d(TAG, "Trying to bind to profile: " + bluetoothProfile
1059 + ", while Bluetooth was disabled");
Benjamin Franze8b98922014-11-12 15:57:54 +00001060 }
1061 return false;
1062 }
1063 synchronized (mProfileServices) {
1064 ProfileServiceConnections psc = mProfileServices.get(new Integer(bluetoothProfile));
1065 if (psc == null) {
1066 if (DBG) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001067 Slog.d(TAG, "Creating new ProfileServiceConnections object for" + " profile: "
1068 + bluetoothProfile);
Benjamin Franze8b98922014-11-12 15:57:54 +00001069 }
Benjamin Franz5b614592014-12-09 18:58:45 +00001070
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001071 if (bluetoothProfile != BluetoothProfile.HEADSET) {
1072 return false;
1073 }
Benjamin Franz5b614592014-12-09 18:58:45 +00001074
1075 Intent intent = new Intent(IBluetoothHeadset.class.getName());
Benjamin Franze8b98922014-11-12 15:57:54 +00001076 psc = new ProfileServiceConnections(intent);
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001077 if (!psc.bindService()) {
1078 return false;
1079 }
Benjamin Franz5b614592014-12-09 18:58:45 +00001080
Benjamin Franze8b98922014-11-12 15:57:54 +00001081 mProfileServices.put(new Integer(bluetoothProfile), psc);
Benjamin Franze8b98922014-11-12 15:57:54 +00001082 }
1083 }
1084
1085 // Introducing a delay to give the client app time to prepare
1086 Message addProxyMsg = mHandler.obtainMessage(MESSAGE_ADD_PROXY_DELAYED);
1087 addProxyMsg.arg1 = bluetoothProfile;
1088 addProxyMsg.obj = proxy;
1089 mHandler.sendMessageDelayed(addProxyMsg, ADD_PROXY_DELAY_MS);
1090 return true;
1091 }
1092
1093 @Override
1094 public void unbindBluetoothProfileService(int bluetoothProfile,
1095 IBluetoothProfileServiceConnection proxy) {
1096 synchronized (mProfileServices) {
1097 ProfileServiceConnections psc = mProfileServices.get(new Integer(bluetoothProfile));
1098 if (psc == null) {
1099 return;
1100 }
1101 psc.removeProxy(proxy);
1102 }
1103 }
1104
1105 private void unbindAllBluetoothProfileServices() {
1106 synchronized (mProfileServices) {
1107 for (Integer i : mProfileServices.keySet()) {
1108 ProfileServiceConnections psc = mProfileServices.get(i);
Benjamin Franz5b614592014-12-09 18:58:45 +00001109 try {
1110 mContext.unbindService(psc);
1111 } catch (IllegalArgumentException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001112 Slog.e(TAG, "Unable to unbind service with intent: " + psc.mIntent, e);
Benjamin Franz5b614592014-12-09 18:58:45 +00001113 }
Benjamin Franze8b98922014-11-12 15:57:54 +00001114 psc.removeAllProxies();
1115 }
1116 mProfileServices.clear();
1117 }
1118 }
1119
1120 /**
Miao Chou658bf2f2015-06-26 17:14:35 -07001121 * Send enable message and set adapter name and address. Called when the boot phase becomes
1122 * PHASE_SYSTEM_SERVICES_READY.
1123 */
1124 public void handleOnBootPhase() {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001125 if (DBG) {
1126 Slog.d(TAG, "Bluetooth boot completed");
1127 }
Lenka Trochtova63d5e4a72016-12-02 12:19:39 +01001128 UserManagerInternal userManagerInternal =
1129 LocalServices.getService(UserManagerInternal.class);
1130 userManagerInternal.addUserRestrictionsListener(mUserRestrictionsListener);
Lenka Trochtovac6f0e232017-01-17 10:35:49 +01001131 final boolean isBluetoothDisallowed = isBluetoothDisallowed();
Lenka Trochtovac6f0e232017-01-17 10:35:49 +01001132 if (isBluetoothDisallowed) {
Lenka Trochtova63d5e4a72016-12-02 12:19:39 +01001133 return;
1134 }
Miao Chou658bf2f2015-06-26 17:14:35 -07001135 if (mEnableExternal && isBluetoothPersistedStateOnBluetooth()) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001136 if (DBG) {
1137 Slog.d(TAG, "Auto-enabling Bluetooth.");
1138 }
Jack He8caab152018-03-02 13:08:36 -08001139 sendEnableMsg(mQuietEnableExternal,
1140 BluetoothProtoEnums.ENABLE_DISABLE_REASON_SYSTEM_BOOT,
1141 mContext.getPackageName());
Ajay Panickerbf796d82016-03-11 13:47:20 -08001142 } else if (!isNameAndAddressSet()) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001143 if (DBG) {
1144 Slog.d(TAG, "Getting adapter name and address");
1145 }
Ajay Panicker4bb48302016-03-31 14:14:27 -07001146 Message getMsg = mHandler.obtainMessage(MESSAGE_GET_NAME_AND_ADDRESS);
1147 mHandler.sendMessage(getMsg);
Miao Chou658bf2f2015-06-26 17:14:35 -07001148 }
Miao Chou658bf2f2015-06-26 17:14:35 -07001149 }
1150
1151 /**
1152 * Called when switching to a different foreground user.
1153 */
1154 public void handleOnSwitchUser(int userHandle) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001155 if (DBG) {
1156 Slog.d(TAG, "User " + userHandle + " switched");
1157 }
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001158 mHandler.obtainMessage(MESSAGE_USER_SWITCHED, userHandle, 0).sendToTarget();
1159 }
1160
1161 /**
1162 * Called when user is unlocked.
1163 */
1164 public void handleOnUnlockUser(int userHandle) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001165 if (DBG) {
1166 Slog.d(TAG, "User " + userHandle + " unlocked");
1167 }
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001168 mHandler.obtainMessage(MESSAGE_USER_UNLOCKED, userHandle, 0).sendToTarget();
Miao Chou658bf2f2015-06-26 17:14:35 -07001169 }
1170
1171 /**
Benjamin Franze8b98922014-11-12 15:57:54 +00001172 * This class manages the clients connected to a given ProfileService
1173 * and maintains the connection with that service.
1174 */
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001175 private final class ProfileServiceConnections
1176 implements ServiceConnection, IBinder.DeathRecipient {
Benjamin Franze8b98922014-11-12 15:57:54 +00001177 final RemoteCallbackList<IBluetoothProfileServiceConnection> mProxies =
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001178 new RemoteCallbackList<IBluetoothProfileServiceConnection>();
Benjamin Franze8b98922014-11-12 15:57:54 +00001179 IBinder mService;
1180 ComponentName mClassName;
1181 Intent mIntent;
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001182 boolean mInvokingProxyCallbacks = false;
Benjamin Franze8b98922014-11-12 15:57:54 +00001183
1184 ProfileServiceConnections(Intent intent) {
1185 mService = null;
1186 mClassName = null;
1187 mIntent = intent;
1188 }
1189
Benjamin Franz5b614592014-12-09 18:58:45 +00001190 private boolean bindService() {
jonerlin37fc85d2018-08-09 16:39:43 +08001191 int state = BluetoothAdapter.STATE_OFF;
1192 try {
1193 mBluetoothLock.readLock().lock();
1194 if (mBluetooth != null) {
1195 state = mBluetooth.getState();
1196 }
1197 } catch (RemoteException e) {
1198 Slog.e(TAG, "Unable to call getState", e);
1199 return false;
1200 } finally {
1201 mBluetoothLock.readLock().unlock();
1202 }
1203
1204 if (!mEnable || state != BluetoothAdapter.STATE_ON) {
1205 if (DBG) {
1206 Slog.d(TAG, "Unable to bindService while Bluetooth is disabled");
1207 }
1208 return false;
1209 }
1210
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001211 if (mIntent != null && mService == null && doBind(mIntent, this, 0,
1212 UserHandle.CURRENT_OR_SELF)) {
Benjamin Franze8b98922014-11-12 15:57:54 +00001213 Message msg = mHandler.obtainMessage(MESSAGE_BIND_PROFILE_SERVICE);
1214 msg.obj = this;
1215 mHandler.sendMessageDelayed(msg, TIMEOUT_BIND_MS);
Benjamin Franz5b614592014-12-09 18:58:45 +00001216 return true;
Benjamin Franze8b98922014-11-12 15:57:54 +00001217 }
Jeff Sharkey67609c72016-03-05 14:29:13 -07001218 Slog.w(TAG, "Unable to bind with intent: " + mIntent);
Benjamin Franz5b614592014-12-09 18:58:45 +00001219 return false;
Benjamin Franze8b98922014-11-12 15:57:54 +00001220 }
1221
1222 private void addProxy(IBluetoothProfileServiceConnection proxy) {
1223 mProxies.register(proxy);
1224 if (mService != null) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001225 try {
Benjamin Franze8b98922014-11-12 15:57:54 +00001226 proxy.onServiceConnected(mClassName, mService);
1227 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001228 Slog.e(TAG, "Unable to connect to proxy", e);
Benjamin Franze8b98922014-11-12 15:57:54 +00001229 }
1230 } else {
1231 if (!mHandler.hasMessages(MESSAGE_BIND_PROFILE_SERVICE, this)) {
1232 Message msg = mHandler.obtainMessage(MESSAGE_BIND_PROFILE_SERVICE);
1233 msg.obj = this;
1234 mHandler.sendMessage(msg);
1235 }
1236 }
1237 }
1238
1239 private void removeProxy(IBluetoothProfileServiceConnection proxy) {
1240 if (proxy != null) {
1241 if (mProxies.unregister(proxy)) {
1242 try {
1243 proxy.onServiceDisconnected(mClassName);
1244 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001245 Slog.e(TAG, "Unable to disconnect proxy", e);
Benjamin Franze8b98922014-11-12 15:57:54 +00001246 }
1247 }
1248 } else {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001249 Slog.w(TAG, "Trying to remove a null proxy");
Benjamin Franze8b98922014-11-12 15:57:54 +00001250 }
1251 }
1252
1253 private void removeAllProxies() {
1254 onServiceDisconnected(mClassName);
1255 mProxies.kill();
1256 }
1257
1258 @Override
1259 public void onServiceConnected(ComponentName className, IBinder service) {
1260 // remove timeout message
1261 mHandler.removeMessages(MESSAGE_BIND_PROFILE_SERVICE, this);
1262 mService = service;
1263 mClassName = className;
1264 try {
1265 mService.linkToDeath(this, 0);
1266 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001267 Slog.e(TAG, "Unable to linkToDeath", e);
Benjamin Franze8b98922014-11-12 15:57:54 +00001268 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001269
1270 if (mInvokingProxyCallbacks) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001271 Slog.e(TAG, "Proxy callbacks already in progress.");
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001272 return;
Benjamin Franze8b98922014-11-12 15:57:54 +00001273 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001274 mInvokingProxyCallbacks = true;
1275
1276 final int n = mProxies.beginBroadcast();
1277 try {
1278 for (int i = 0; i < n; i++) {
1279 try {
1280 mProxies.getBroadcastItem(i).onServiceConnected(className, service);
1281 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001282 Slog.e(TAG, "Unable to connect to proxy", e);
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001283 }
1284 }
1285 } finally {
1286 mProxies.finishBroadcast();
1287 mInvokingProxyCallbacks = false;
1288 }
Benjamin Franze8b98922014-11-12 15:57:54 +00001289 }
1290
1291 @Override
1292 public void onServiceDisconnected(ComponentName className) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001293 if (mService == null) {
1294 return;
1295 }
Chienyuan177156b2018-12-18 10:40:25 +08001296 try {
1297 mService.unlinkToDeath(this, 0);
1298 } catch (NoSuchElementException e) {
1299 Log.e(TAG, "error unlinking to death", e);
1300 }
Benjamin Franze8b98922014-11-12 15:57:54 +00001301 mService = null;
1302 mClassName = null;
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001303
1304 if (mInvokingProxyCallbacks) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001305 Slog.e(TAG, "Proxy callbacks already in progress.");
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001306 return;
Benjamin Franze8b98922014-11-12 15:57:54 +00001307 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001308 mInvokingProxyCallbacks = true;
1309
1310 final int n = mProxies.beginBroadcast();
1311 try {
1312 for (int i = 0; i < n; i++) {
1313 try {
1314 mProxies.getBroadcastItem(i).onServiceDisconnected(className);
1315 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001316 Slog.e(TAG, "Unable to disconnect from proxy", e);
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001317 }
1318 }
1319 } finally {
1320 mProxies.finishBroadcast();
1321 mInvokingProxyCallbacks = false;
1322 }
Benjamin Franze8b98922014-11-12 15:57:54 +00001323 }
1324
1325 @Override
1326 public void binderDied() {
1327 if (DBG) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001328 Slog.w(TAG, "Profile service for profile: " + mClassName + " died.");
Benjamin Franze8b98922014-11-12 15:57:54 +00001329 }
1330 onServiceDisconnected(mClassName);
1331 // Trigger rebind
1332 Message msg = mHandler.obtainMessage(MESSAGE_BIND_PROFILE_SERVICE);
1333 msg.obj = this;
1334 mHandler.sendMessageDelayed(msg, TIMEOUT_BIND_MS);
1335 }
1336 }
1337
fredcbf072a72012-05-09 16:52:50 -07001338 private void sendBluetoothStateCallback(boolean isUp) {
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001339 try {
1340 int n = mStateChangeCallbacks.beginBroadcast();
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001341 if (DBG) {
1342 Slog.d(TAG, "Broadcasting onBluetoothStateChange(" + isUp + ") to " + n
1343 + " receivers.");
1344 }
1345 for (int i = 0; i < n; i++) {
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001346 try {
1347 mStateChangeCallbacks.getBroadcastItem(i).onBluetoothStateChange(isUp);
1348 } catch (RemoteException e) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001349 Slog.e(TAG, "Unable to call onBluetoothStateChange() on callback #" + i, e);
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001350 }
fredcbf072a72012-05-09 16:52:50 -07001351 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001352 } finally {
1353 mStateChangeCallbacks.finishBroadcast();
fredcbf072a72012-05-09 16:52:50 -07001354 }
fredcbf072a72012-05-09 16:52:50 -07001355 }
1356
1357 /**
Zhihai Xu40874a02012-10-08 17:57:03 -07001358 * Inform BluetoothAdapter instances that Adapter service is up
1359 */
1360 private void sendBluetoothServiceUpCallback() {
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001361 try {
1362 int n = mCallbacks.beginBroadcast();
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001363 Slog.d(TAG, "Broadcasting onBluetoothServiceUp() to " + n + " receivers.");
1364 for (int i = 0; i < n; i++) {
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001365 try {
1366 mCallbacks.getBroadcastItem(i).onBluetoothServiceUp(mBluetooth);
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001367 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001368 Slog.e(TAG, "Unable to call onBluetoothServiceUp() on callback #" + i, e);
Zhihai Xu40874a02012-10-08 17:57:03 -07001369 }
1370 }
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001371 } finally {
1372 mCallbacks.finishBroadcast();
Zhihai Xu40874a02012-10-08 17:57:03 -07001373 }
1374 }
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001375
Zhihai Xu40874a02012-10-08 17:57:03 -07001376 /**
fredcbf072a72012-05-09 16:52:50 -07001377 * Inform BluetoothAdapter instances that Adapter service is down
1378 */
1379 private void sendBluetoothServiceDownCallback() {
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001380 try {
1381 int n = mCallbacks.beginBroadcast();
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001382 Slog.d(TAG, "Broadcasting onBluetoothServiceDown() to " + n + " receivers.");
1383 for (int i = 0; i < n; i++) {
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001384 try {
1385 mCallbacks.getBroadcastItem(i).onBluetoothServiceDown();
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001386 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001387 Slog.e(TAG, "Unable to call onBluetoothServiceDown() on callback #" + i, e);
fredcd6883532012-04-25 17:46:13 -07001388 }
1389 }
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001390 } finally {
1391 mCallbacks.finishBroadcast();
fredcd6883532012-04-25 17:46:13 -07001392 }
1393 }
Svet Ganov408abf72015-05-12 19:13:36 -07001394
fredc0f420372012-04-12 00:02:00 -07001395 public String getAddress() {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001396 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");
Zhihai Xu40874a02012-10-08 17:57:03 -07001397
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001398 if ((Binder.getCallingUid() != Process.SYSTEM_UID) && (!checkIfCallerIsForegroundUser())) {
1399 Slog.w(TAG, "getAddress(): not allowed for non-active and non system user");
Zhihai Xu6eb76522012-11-29 15:41:04 -08001400 return null;
Zhihai Xu40874a02012-10-08 17:57:03 -07001401 }
1402
Svet Ganov408abf72015-05-12 19:13:36 -07001403 if (mContext.checkCallingOrSelfPermission(Manifest.permission.LOCAL_MAC_ADDRESS)
1404 != PackageManager.PERMISSION_GRANTED) {
1405 return BluetoothAdapter.DEFAULT_MAC_ADDRESS;
1406 }
1407
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001408 try {
1409 mBluetoothLock.readLock().lock();
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001410 if (mBluetooth != null) {
1411 return mBluetooth.getAddress();
1412 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001413 } catch (RemoteException e) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001414 Slog.e(TAG,
1415 "getAddress(): Unable to retrieve address remotely. Returning cached address",
1416 e);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001417 } finally {
1418 mBluetoothLock.readLock().unlock();
fredc116d1d462012-04-20 14:47:08 -07001419 }
Ajay Panickerbf796d82016-03-11 13:47:20 -08001420
Matthew Xiecdce0b92012-07-12 19:06:15 -07001421 // mAddress is accessed from outside.
1422 // It is alright without a lock. Here, bluetooth is off, no other thread is
1423 // changing mAddress
fredc0f420372012-04-12 00:02:00 -07001424 return mAddress;
1425 }
fredc649fe492012-04-19 01:07:18 -07001426
fredc0f420372012-04-12 00:02:00 -07001427 public String getName() {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001428 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");
Zhihai Xu40874a02012-10-08 17:57:03 -07001429
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001430 if ((Binder.getCallingUid() != Process.SYSTEM_UID) && (!checkIfCallerIsForegroundUser())) {
1431 Slog.w(TAG, "getName(): not allowed for non-active and non system user");
Zhihai Xu6eb76522012-11-29 15:41:04 -08001432 return null;
Zhihai Xu40874a02012-10-08 17:57:03 -07001433 }
1434
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001435 try {
1436 mBluetoothLock.readLock().lock();
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001437 if (mBluetooth != null) {
1438 return mBluetooth.getName();
1439 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001440 } catch (RemoteException e) {
1441 Slog.e(TAG, "getName(): Unable to retrieve name remotely. Returning cached name", e);
1442 } finally {
1443 mBluetoothLock.readLock().unlock();
fredc116d1d462012-04-20 14:47:08 -07001444 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001445
Matthew Xiecdce0b92012-07-12 19:06:15 -07001446 // mName is accessed from outside.
1447 // It alright without a lock. Here, bluetooth is off, no other thread is
1448 // changing mName
fredc0f420372012-04-12 00:02:00 -07001449 return mName;
1450 }
1451
fredc0f420372012-04-12 00:02:00 -07001452 private class BluetoothServiceConnection implements ServiceConnection {
Marie Janssencb21ad72016-12-13 10:51:02 -08001453 public void onServiceConnected(ComponentName componentName, IBinder service) {
1454 String name = componentName.getClassName();
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001455 if (DBG) {
1456 Slog.d(TAG, "BluetoothServiceConnection: " + name);
1457 }
fredc0f420372012-04-12 00:02:00 -07001458 Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_SERVICE_CONNECTED);
Marie Janssencb21ad72016-12-13 10:51:02 -08001459 if (name.equals("com.android.bluetooth.btservice.AdapterService")) {
Matthew Xieddf7e472013-03-01 18:41:02 -08001460 msg.arg1 = SERVICE_IBLUETOOTH;
Marie Janssencb21ad72016-12-13 10:51:02 -08001461 } else if (name.equals("com.android.bluetooth.gatt.GattService")) {
Matthew Xieddf7e472013-03-01 18:41:02 -08001462 msg.arg1 = SERVICE_IBLUETOOTHGATT;
1463 } else {
Marie Janssencb21ad72016-12-13 10:51:02 -08001464 Slog.e(TAG, "Unknown service connected: " + name);
Matthew Xieddf7e472013-03-01 18:41:02 -08001465 return;
1466 }
fredc0f420372012-04-12 00:02:00 -07001467 msg.obj = service;
1468 mHandler.sendMessage(msg);
1469 }
1470
Marie Janssencb21ad72016-12-13 10:51:02 -08001471 public void onServiceDisconnected(ComponentName componentName) {
1472 // Called if we unexpectedly disconnect.
1473 String name = componentName.getClassName();
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001474 if (DBG) {
1475 Slog.d(TAG, "BluetoothServiceConnection, disconnected: " + name);
1476 }
fredc0f420372012-04-12 00:02:00 -07001477 Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED);
Marie Janssencb21ad72016-12-13 10:51:02 -08001478 if (name.equals("com.android.bluetooth.btservice.AdapterService")) {
Matthew Xieddf7e472013-03-01 18:41:02 -08001479 msg.arg1 = SERVICE_IBLUETOOTH;
Marie Janssencb21ad72016-12-13 10:51:02 -08001480 } else if (name.equals("com.android.bluetooth.gatt.GattService")) {
Matthew Xieddf7e472013-03-01 18:41:02 -08001481 msg.arg1 = SERVICE_IBLUETOOTHGATT;
1482 } else {
Marie Janssencb21ad72016-12-13 10:51:02 -08001483 Slog.e(TAG, "Unknown service disconnected: " + name);
Matthew Xieddf7e472013-03-01 18:41:02 -08001484 return;
1485 }
fredc0f420372012-04-12 00:02:00 -07001486 mHandler.sendMessage(msg);
1487 }
1488 }
1489
1490 private BluetoothServiceConnection mConnection = new BluetoothServiceConnection();
1491
Zhihai Xu40874a02012-10-08 17:57:03 -07001492 private class BluetoothHandler extends Handler {
Ajay Panicker4bb48302016-03-31 14:14:27 -07001493 boolean mGetNameAddressOnly = false;
1494
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001495 BluetoothHandler(Looper looper) {
Zhihai Xu40874a02012-10-08 17:57:03 -07001496 super(looper);
1497 }
1498
fredc0f420372012-04-12 00:02:00 -07001499 @Override
1500 public void handleMessage(Message msg) {
fredc0f420372012-04-12 00:02:00 -07001501 switch (msg.what) {
Ajay Panicker4bb48302016-03-31 14:14:27 -07001502 case MESSAGE_GET_NAME_AND_ADDRESS:
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001503 if (DBG) {
1504 Slog.d(TAG, "MESSAGE_GET_NAME_AND_ADDRESS");
1505 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001506 try {
1507 mBluetoothLock.writeLock().lock();
Ajay Panicker4bb48302016-03-31 14:14:27 -07001508 if ((mBluetooth == null) && (!mBinding)) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001509 if (DBG) {
1510 Slog.d(TAG, "Binding to service to get name and address");
1511 }
Ajay Panicker4bb48302016-03-31 14:14:27 -07001512 mGetNameAddressOnly = true;
1513 Message timeoutMsg = mHandler.obtainMessage(MESSAGE_TIMEOUT_BIND);
1514 mHandler.sendMessageDelayed(timeoutMsg, TIMEOUT_BIND_MS);
1515 Intent i = new Intent(IBluetooth.class.getName());
1516 if (!doBind(i, mConnection,
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001517 Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT,
1518 UserHandle.CURRENT)) {
Ajay Panicker4bb48302016-03-31 14:14:27 -07001519 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
1520 } else {
1521 mBinding = true;
1522 }
1523 } else if (mBluetooth != null) {
1524 try {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001525 storeNameAndAddress(mBluetooth.getName(), mBluetooth.getAddress());
Ajay Panicker4bb48302016-03-31 14:14:27 -07001526 } catch (RemoteException re) {
1527 Slog.e(TAG, "Unable to grab names", re);
1528 }
1529 if (mGetNameAddressOnly && !mEnable) {
1530 unbindAndFinish();
1531 }
1532 mGetNameAddressOnly = false;
1533 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001534 } finally {
1535 mBluetoothLock.writeLock().unlock();
Ajay Panicker4bb48302016-03-31 14:14:27 -07001536 }
1537 break;
1538
Matthew Xiecdce0b92012-07-12 19:06:15 -07001539 case MESSAGE_ENABLE:
fredcf2458862012-04-16 15:18:27 -07001540 if (DBG) {
Marie Janssencb21ad72016-12-13 10:51:02 -08001541 Slog.d(TAG, "MESSAGE_ENABLE(" + msg.arg1 + "): mBluetooth = " + mBluetooth);
fredc649fe492012-04-19 01:07:18 -07001542 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001543 mHandler.removeMessages(MESSAGE_RESTART_BLUETOOTH_SERVICE);
1544 mEnable = true;
Calvin Ona0b91d72016-06-15 17:58:23 -07001545
1546 // Use service interface to get the exact state
1547 try {
1548 mBluetoothLock.readLock().lock();
1549 if (mBluetooth != null) {
1550 int state = mBluetooth.getState();
1551 if (state == BluetoothAdapter.STATE_BLE_ON) {
Marie Janssene0bfa2e2016-12-20 11:21:12 -08001552 Slog.w(TAG, "BT Enable in BLE_ON State, going to ON");
Calvin Ona0b91d72016-06-15 17:58:23 -07001553 mBluetooth.onLeServiceUp();
Marie Janssene0bfa2e2016-12-20 11:21:12 -08001554 persistBluetoothSetting(BLUETOOTH_ON_BLUETOOTH);
Calvin Ona0b91d72016-06-15 17:58:23 -07001555 break;
1556 }
1557 }
1558 } catch (RemoteException e) {
1559 Slog.e(TAG, "", e);
1560 } finally {
1561 mBluetoothLock.readLock().unlock();
1562 }
1563
1564 mQuietEnable = (msg.arg1 == 1);
Pavlin Radoslavove47ec142016-06-01 22:25:18 -07001565 if (mBluetooth == null) {
Calvin Ona0b91d72016-06-15 17:58:23 -07001566 handleEnable(mQuietEnable);
Pavlin Radoslavove47ec142016-06-01 22:25:18 -07001567 } else {
1568 //
1569 // We need to wait until transitioned to STATE_OFF and
1570 // the previous Bluetooth process has exited. The
1571 // waiting period has three components:
1572 // (a) Wait until the local state is STATE_OFF. This
1573 // is accomplished by "waitForOnOff(false, true)".
1574 // (b) Wait until the STATE_OFF state is updated to
1575 // all components.
1576 // (c) Wait until the Bluetooth process exits, and
1577 // ActivityManager detects it.
1578 // The waiting for (b) and (c) is accomplished by
1579 // delaying the MESSAGE_RESTART_BLUETOOTH_SERVICE
1580 // message. On slower devices, that delay needs to be
1581 // on the order of (2 * SERVICE_RESTART_TIME_MS).
1582 //
1583 waitForOnOff(false, true);
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001584 Message restartMsg =
1585 mHandler.obtainMessage(MESSAGE_RESTART_BLUETOOTH_SERVICE);
1586 mHandler.sendMessageDelayed(restartMsg, 2 * SERVICE_RESTART_TIME_MS);
Pavlin Radoslavove47ec142016-06-01 22:25:18 -07001587 }
fredc649fe492012-04-19 01:07:18 -07001588 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001589
fredc0f420372012-04-12 00:02:00 -07001590 case MESSAGE_DISABLE:
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001591 if (DBG) {
1592 Slog.d(TAG, "MESSAGE_DISABLE: mBluetooth = " + mBluetooth);
1593 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001594 mHandler.removeMessages(MESSAGE_RESTART_BLUETOOTH_SERVICE);
1595 if (mEnable && mBluetooth != null) {
1596 waitForOnOff(true, false);
1597 mEnable = false;
Zhihai Xu401202b2012-12-03 11:36:21 -08001598 handleDisable();
Zhihai Xu40874a02012-10-08 17:57:03 -07001599 waitForOnOff(false, false);
1600 } else {
1601 mEnable = false;
Zhihai Xu401202b2012-12-03 11:36:21 -08001602 handleDisable();
Zhihai Xu40874a02012-10-08 17:57:03 -07001603 }
fredc0f420372012-04-12 00:02:00 -07001604 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001605
Stanley Tng873b5702017-05-01 21:27:31 -07001606 case MESSAGE_RESTORE_USER_SETTING:
Jack He8caab152018-03-02 13:08:36 -08001607 if ((msg.arg1 == RESTORE_SETTING_TO_OFF) && mEnable) {
1608 if (DBG) {
1609 Slog.d(TAG, "Restore Bluetooth state to disabled");
Stanley Tng873b5702017-05-01 21:27:31 -07001610 }
Jack He8caab152018-03-02 13:08:36 -08001611 persistBluetoothSetting(BLUETOOTH_OFF);
1612 mEnableExternal = false;
1613 sendDisableMsg(
1614 BluetoothProtoEnums.ENABLE_DISABLE_REASON_RESTORE_USER_SETTING,
1615 mContext.getPackageName());
1616 } else if ((msg.arg1 == RESTORE_SETTING_TO_ON) && !mEnable) {
1617 if (DBG) {
1618 Slog.d(TAG, "Restore Bluetooth state to enabled");
1619 }
1620 mQuietEnableExternal = false;
1621 mEnableExternal = true;
1622 // waive WRITE_SECURE_SETTINGS permission check
1623 sendEnableMsg(false,
1624 BluetoothProtoEnums.ENABLE_DISABLE_REASON_RESTORE_USER_SETTING,
1625 mContext.getPackageName());
Stanley Tng873b5702017-05-01 21:27:31 -07001626 }
1627 break;
1628
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001629 case MESSAGE_REGISTER_ADAPTER: {
fredc0f420372012-04-12 00:02:00 -07001630 IBluetoothManagerCallback callback = (IBluetoothManagerCallback) msg.obj;
Marie Janssencb21ad72016-12-13 10:51:02 -08001631 mCallbacks.register(callback);
fredc0f420372012-04-12 00:02:00 -07001632 break;
Marie Janssencb21ad72016-12-13 10:51:02 -08001633 }
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001634 case MESSAGE_UNREGISTER_ADAPTER: {
fredc0f420372012-04-12 00:02:00 -07001635 IBluetoothManagerCallback callback = (IBluetoothManagerCallback) msg.obj;
Marie Janssencb21ad72016-12-13 10:51:02 -08001636 mCallbacks.unregister(callback);
fredc0f420372012-04-12 00:02:00 -07001637 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001638 }
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001639 case MESSAGE_REGISTER_STATE_CHANGE_CALLBACK: {
1640 IBluetoothStateChangeCallback callback =
1641 (IBluetoothStateChangeCallback) msg.obj;
Marie Janssencb21ad72016-12-13 10:51:02 -08001642 mStateChangeCallbacks.register(callback);
fredc0f420372012-04-12 00:02:00 -07001643 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001644 }
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001645 case MESSAGE_UNREGISTER_STATE_CHANGE_CALLBACK: {
1646 IBluetoothStateChangeCallback callback =
1647 (IBluetoothStateChangeCallback) msg.obj;
Marie Janssencb21ad72016-12-13 10:51:02 -08001648 mStateChangeCallbacks.unregister(callback);
fredc0f420372012-04-12 00:02:00 -07001649 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001650 }
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001651 case MESSAGE_ADD_PROXY_DELAYED: {
Jack He8caab152018-03-02 13:08:36 -08001652 ProfileServiceConnections psc = mProfileServices.get(msg.arg1);
Benjamin Franze8b98922014-11-12 15:57:54 +00001653 if (psc == null) {
1654 break;
1655 }
1656 IBluetoothProfileServiceConnection proxy =
1657 (IBluetoothProfileServiceConnection) msg.obj;
1658 psc.addProxy(proxy);
1659 break;
1660 }
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001661 case MESSAGE_BIND_PROFILE_SERVICE: {
Benjamin Franze8b98922014-11-12 15:57:54 +00001662 ProfileServiceConnections psc = (ProfileServiceConnections) msg.obj;
1663 removeMessages(MESSAGE_BIND_PROFILE_SERVICE, msg.obj);
1664 if (psc == null) {
1665 break;
1666 }
1667 psc.bindService();
1668 break;
1669 }
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001670 case MESSAGE_BLUETOOTH_SERVICE_CONNECTED: {
1671 if (DBG) {
1672 Slog.d(TAG, "MESSAGE_BLUETOOTH_SERVICE_CONNECTED: " + msg.arg1);
1673 }
fredc0f420372012-04-12 00:02:00 -07001674
1675 IBinder service = (IBinder) msg.obj;
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001676 try {
1677 mBluetoothLock.writeLock().lock();
Matthew Xieddf7e472013-03-01 18:41:02 -08001678 if (msg.arg1 == SERVICE_IBLUETOOTHGATT) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001679 mBluetoothGatt =
1680 IBluetoothGatt.Stub.asInterface(Binder.allowBlocking(service));
Myles Watson304ebf22018-05-11 08:47:24 -07001681 continueFromBleOnState();
Matthew Xieddf7e472013-03-01 18:41:02 -08001682 break;
1683 } // else must be SERVICE_IBLUETOOTH
1684
1685 //Remove timeout
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001686 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
Matthew Xieddf7e472013-03-01 18:41:02 -08001687
fredc0f420372012-04-12 00:02:00 -07001688 mBinding = false;
Marie Janssen9db28eb2016-01-12 16:05:15 -08001689 mBluetoothBinder = service;
Jeff Sharkey0a17db12016-11-04 11:23:46 -06001690 mBluetooth = IBluetooth.Stub.asInterface(Binder.allowBlocking(service));
fredc0f420372012-04-12 00:02:00 -07001691
Ajay Panicker4bb48302016-03-31 14:14:27 -07001692 if (!isNameAndAddressSet()) {
1693 Message getMsg = mHandler.obtainMessage(MESSAGE_GET_NAME_AND_ADDRESS);
1694 mHandler.sendMessage(getMsg);
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001695 if (mGetNameAddressOnly) {
1696 return;
1697 }
Ajay Panicker4bb48302016-03-31 14:14:27 -07001698 }
1699
Matthew Xiecdce0b92012-07-12 19:06:15 -07001700 //Register callback object
fredcbf072a72012-05-09 16:52:50 -07001701 try {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001702 mBluetooth.registerCallback(mBluetoothCallback);
1703 } catch (RemoteException re) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001704 Slog.e(TAG, "Unable to register BluetoothCallback", re);
fredcbf072a72012-05-09 16:52:50 -07001705 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001706 //Inform BluetoothAdapter instances that service is up
Zhihai Xu40874a02012-10-08 17:57:03 -07001707 sendBluetoothServiceUpCallback();
1708
Matthew Xiecdce0b92012-07-12 19:06:15 -07001709 //Do enable request
1710 try {
Jack Hea6e031c2017-12-08 12:21:37 -08001711 if (!mQuietEnable) {
Marie Janssencb21ad72016-12-13 10:51:02 -08001712 if (!mBluetooth.enable()) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001713 Slog.e(TAG, "IBluetooth.enable() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001714 }
Marie Janssencb21ad72016-12-13 10:51:02 -08001715 } else {
1716 if (!mBluetooth.enableNoAutoConnect()) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001717 Slog.e(TAG, "IBluetooth.enableNoAutoConnect() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001718 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001719 }
1720 } catch (RemoteException e) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001721 Slog.e(TAG, "Unable to call enable()", e);
Matthew Xiecdce0b92012-07-12 19:06:15 -07001722 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001723 } finally {
1724 mBluetoothLock.writeLock().unlock();
Freda8c6df02012-07-11 10:25:23 -07001725 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001726
1727 if (!mEnable) {
1728 waitForOnOff(true, false);
Zhihai Xu401202b2012-12-03 11:36:21 -08001729 handleDisable();
Zhihai Xu40874a02012-10-08 17:57:03 -07001730 waitForOnOff(false, false);
1731 }
fredc649fe492012-04-19 01:07:18 -07001732 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001733 }
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001734 case MESSAGE_BLUETOOTH_STATE_CHANGE: {
fredcbf072a72012-05-09 16:52:50 -07001735 int prevState = msg.arg1;
1736 int newState = msg.arg2;
Marie Janssencb21ad72016-12-13 10:51:02 -08001737 if (DBG) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001738 Slog.d(TAG,
1739 "MESSAGE_BLUETOOTH_STATE_CHANGE: " + BluetoothAdapter.nameForState(
1740 prevState) + " > " + BluetoothAdapter.nameForState(
1741 newState));
Marie Janssencb21ad72016-12-13 10:51:02 -08001742 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001743 mState = newState;
1744 bluetoothStateChangeHandler(prevState, newState);
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001745 // handle error state transition case from TURNING_ON to OFF
1746 // unbind and rebind bluetooth service and enable bluetooth
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001747 if ((prevState == BluetoothAdapter.STATE_BLE_TURNING_ON) && (newState
1748 == BluetoothAdapter.STATE_OFF) && (mBluetooth != null) && mEnable) {
Marie Janssen2977c3e2016-11-09 12:01:24 -08001749 recoverBluetoothServiceFromError(false);
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001750 }
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001751 if ((prevState == BluetoothAdapter.STATE_TURNING_ON) && (newState
1752 == BluetoothAdapter.STATE_BLE_ON) && (mBluetooth != null) && mEnable) {
Marie Janssen2977c3e2016-11-09 12:01:24 -08001753 recoverBluetoothServiceFromError(true);
Nitin Arorad055adb2015-03-02 15:03:51 -08001754 }
Calvin Ona0b91d72016-06-15 17:58:23 -07001755 // If we tried to enable BT while BT was in the process of shutting down,
1756 // wait for the BT process to fully tear down and then force a restart
1757 // here. This is a bit of a hack (b/29363429).
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001758 if ((prevState == BluetoothAdapter.STATE_BLE_TURNING_OFF) && (newState
1759 == BluetoothAdapter.STATE_OFF)) {
Calvin Ona0b91d72016-06-15 17:58:23 -07001760 if (mEnable) {
1761 Slog.d(TAG, "Entering STATE_OFF but mEnabled is true; restarting.");
1762 waitForOnOff(false, true);
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001763 Message restartMsg =
1764 mHandler.obtainMessage(MESSAGE_RESTART_BLUETOOTH_SERVICE);
Calvin Ona0b91d72016-06-15 17:58:23 -07001765 mHandler.sendMessageDelayed(restartMsg, 2 * SERVICE_RESTART_TIME_MS);
1766 }
1767 }
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001768 if (newState == BluetoothAdapter.STATE_ON
1769 || newState == BluetoothAdapter.STATE_BLE_ON) {
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001770 // bluetooth is working, reset the counter
1771 if (mErrorRecoveryRetryCounter != 0) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001772 Slog.w(TAG, "bluetooth is recovered from error");
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001773 mErrorRecoveryRetryCounter = 0;
1774 }
1775 }
fredc649fe492012-04-19 01:07:18 -07001776 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001777 }
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001778 case MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED: {
Marie Janssencb21ad72016-12-13 10:51:02 -08001779 Slog.e(TAG, "MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED(" + msg.arg1 + ")");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001780 try {
1781 mBluetoothLock.writeLock().lock();
Matthew Xieddf7e472013-03-01 18:41:02 -08001782 if (msg.arg1 == SERVICE_IBLUETOOTH) {
1783 // if service is unbinded already, do nothing and return
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001784 if (mBluetooth == null) {
1785 break;
1786 }
Matthew Xieddf7e472013-03-01 18:41:02 -08001787 mBluetooth = null;
1788 } else if (msg.arg1 == SERVICE_IBLUETOOTHGATT) {
1789 mBluetoothGatt = null;
1790 break;
1791 } else {
Marie Janssencb21ad72016-12-13 10:51:02 -08001792 Slog.e(TAG, "Unknown argument for service disconnect!");
Matthew Xieddf7e472013-03-01 18:41:02 -08001793 break;
1794 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001795 } finally {
1796 mBluetoothLock.writeLock().unlock();
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301797 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001798
Marie Janssene54b4222017-03-16 18:10:59 -07001799 // log the unexpected crash
1800 addCrashLog();
Jack He8caab152018-03-02 13:08:36 -08001801 addActiveLog(BluetoothProtoEnums.ENABLE_DISABLE_REASON_CRASH,
1802 mContext.getPackageName(), false);
Zhihai Xu40874a02012-10-08 17:57:03 -07001803 if (mEnable) {
1804 mEnable = false;
1805 // Send a Bluetooth Restart message
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001806 Message restartMsg =
1807 mHandler.obtainMessage(MESSAGE_RESTART_BLUETOOTH_SERVICE);
1808 mHandler.sendMessageDelayed(restartMsg, SERVICE_RESTART_TIME_MS);
Zhihai Xu40874a02012-10-08 17:57:03 -07001809 }
1810
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001811 sendBluetoothServiceDownCallback();
Zhihai Xu40874a02012-10-08 17:57:03 -07001812
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001813 // Send BT state broadcast to update
1814 // the BT icon correctly
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001815 if ((mState == BluetoothAdapter.STATE_TURNING_ON) || (mState
1816 == BluetoothAdapter.STATE_ON)) {
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001817 bluetoothStateChangeHandler(BluetoothAdapter.STATE_ON,
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001818 BluetoothAdapter.STATE_TURNING_OFF);
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001819 mState = BluetoothAdapter.STATE_TURNING_OFF;
Zhihai Xu40874a02012-10-08 17:57:03 -07001820 }
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001821 if (mState == BluetoothAdapter.STATE_TURNING_OFF) {
1822 bluetoothStateChangeHandler(BluetoothAdapter.STATE_TURNING_OFF,
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001823 BluetoothAdapter.STATE_OFF);
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001824 }
1825
1826 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
1827 mState = BluetoothAdapter.STATE_OFF;
fredc649fe492012-04-19 01:07:18 -07001828 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001829 }
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001830 case MESSAGE_RESTART_BLUETOOTH_SERVICE: {
Marie Janssencb21ad72016-12-13 10:51:02 -08001831 Slog.d(TAG, "MESSAGE_RESTART_BLUETOOTH_SERVICE");
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301832 /* Enable without persisting the setting as
1833 it doesnt change when IBluetooth
1834 service restarts */
Zhihai Xu40874a02012-10-08 17:57:03 -07001835 mEnable = true;
Jack He8caab152018-03-02 13:08:36 -08001836 addActiveLog(BluetoothProtoEnums.ENABLE_DISABLE_REASON_RESTARTED,
1837 mContext.getPackageName(), true);
Zhihai Xu401202b2012-12-03 11:36:21 -08001838 handleEnable(mQuietEnable);
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301839 break;
1840 }
Marie Janssencb21ad72016-12-13 10:51:02 -08001841 case MESSAGE_TIMEOUT_BIND: {
1842 Slog.e(TAG, "MESSAGE_TIMEOUT_BIND");
1843 mBluetoothLock.writeLock().lock();
1844 mBinding = false;
1845 mBluetoothLock.writeLock().unlock();
1846 break;
1847 }
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001848 case MESSAGE_TIMEOUT_UNBIND: {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001849 Slog.e(TAG, "MESSAGE_TIMEOUT_UNBIND");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001850 mBluetoothLock.writeLock().lock();
1851 mUnbinding = false;
1852 mBluetoothLock.writeLock().unlock();
fredc649fe492012-04-19 01:07:18 -07001853 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001854 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001855
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001856 case MESSAGE_USER_SWITCHED: {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001857 if (DBG) {
1858 Slog.d(TAG, "MESSAGE_USER_SWITCHED");
1859 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001860 mHandler.removeMessages(MESSAGE_USER_SWITCHED);
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001861
Zhihai Xu40874a02012-10-08 17:57:03 -07001862 /* disable and enable BT when detect a user switch */
Ram Periathiruvadi88256d12017-05-03 19:11:20 -07001863 if (mBluetooth != null && isEnabled()) {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001864 try {
1865 mBluetoothLock.readLock().lock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001866 if (mBluetooth != null) {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001867 mBluetooth.unregisterCallback(mBluetoothCallback);
Zhihai Xu40874a02012-10-08 17:57:03 -07001868 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001869 } catch (RemoteException re) {
1870 Slog.e(TAG, "Unable to unregister", re);
1871 } finally {
1872 mBluetoothLock.readLock().unlock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001873 }
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001874
1875 if (mState == BluetoothAdapter.STATE_TURNING_OFF) {
1876 // MESSAGE_USER_SWITCHED happened right after MESSAGE_ENABLE
1877 bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_OFF);
1878 mState = BluetoothAdapter.STATE_OFF;
1879 }
1880 if (mState == BluetoothAdapter.STATE_OFF) {
1881 bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_TURNING_ON);
1882 mState = BluetoothAdapter.STATE_TURNING_ON;
1883 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001884
1885 waitForOnOff(true, false);
1886
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001887 if (mState == BluetoothAdapter.STATE_TURNING_ON) {
1888 bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_ON);
1889 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001890
Benjamin Franze8b98922014-11-12 15:57:54 +00001891 unbindAllBluetoothProfileServices();
Zhihai Xu40874a02012-10-08 17:57:03 -07001892 // disable
Jack He8caab152018-03-02 13:08:36 -08001893 addActiveLog(BluetoothProtoEnums.ENABLE_DISABLE_REASON_USER_SWITCH,
1894 mContext.getPackageName(), false);
Zhihai Xu401202b2012-12-03 11:36:21 -08001895 handleDisable();
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001896 // Pbap service need receive STATE_TURNING_OFF intent to close
1897 bluetoothStateChangeHandler(BluetoothAdapter.STATE_ON,
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001898 BluetoothAdapter.STATE_TURNING_OFF);
Zhihai Xu40874a02012-10-08 17:57:03 -07001899
Pavlin Radoslavov41401112016-06-27 15:25:18 -07001900 boolean didDisableTimeout = !waitForOnOff(false, true);
Zhihai Xu40874a02012-10-08 17:57:03 -07001901
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001902 bluetoothStateChangeHandler(BluetoothAdapter.STATE_TURNING_OFF,
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001903 BluetoothAdapter.STATE_OFF);
Zhihai Xu40874a02012-10-08 17:57:03 -07001904 sendBluetoothServiceDownCallback();
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001905
Pavlin Radoslavove957a8a2016-05-24 15:28:41 -07001906 try {
1907 mBluetoothLock.writeLock().lock();
1908 if (mBluetooth != null) {
1909 mBluetooth = null;
1910 // Unbind
1911 mContext.unbindService(mConnection);
1912 }
1913 mBluetoothGatt = null;
1914 } finally {
1915 mBluetoothLock.writeLock().unlock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001916 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001917
Pavlin Radoslavov41401112016-06-27 15:25:18 -07001918 //
1919 // If disabling Bluetooth times out, wait for an
1920 // additional amount of time to ensure the process is
1921 // shut down completely before attempting to restart.
1922 //
1923 if (didDisableTimeout) {
1924 SystemClock.sleep(3000);
1925 } else {
1926 SystemClock.sleep(100);
1927 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001928
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001929 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
1930 mState = BluetoothAdapter.STATE_OFF;
Zhihai Xu40874a02012-10-08 17:57:03 -07001931 // enable
Jack He8caab152018-03-02 13:08:36 -08001932 addActiveLog(BluetoothProtoEnums.ENABLE_DISABLE_REASON_USER_SWITCH,
1933 mContext.getPackageName(), true);
Ram Periathiruvadi88256d12017-05-03 19:11:20 -07001934 // mEnable flag could have been reset on disableBLE. Reenable it.
1935 mEnable = true;
Zhihai Xu401202b2012-12-03 11:36:21 -08001936 handleEnable(mQuietEnable);
John Spurlock8a985d22014-02-25 09:40:05 -05001937 } else if (mBinding || mBluetooth != null) {
Zhihai Xu40874a02012-10-08 17:57:03 -07001938 Message userMsg = mHandler.obtainMessage(MESSAGE_USER_SWITCHED);
1939 userMsg.arg2 = 1 + msg.arg2;
Marie Janssencb21ad72016-12-13 10:51:02 -08001940 // if user is switched when service is binding retry after a delay
Zhihai Xu40874a02012-10-08 17:57:03 -07001941 mHandler.sendMessageDelayed(userMsg, USER_SWITCHED_TIME_MS);
1942 if (DBG) {
Marie Janssencb21ad72016-12-13 10:51:02 -08001943 Slog.d(TAG, "Retry MESSAGE_USER_SWITCHED " + userMsg.arg2);
Zhihai Xu40874a02012-10-08 17:57:03 -07001944 }
John Spurlock8a985d22014-02-25 09:40:05 -05001945 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001946 break;
1947 }
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001948 case MESSAGE_USER_UNLOCKED: {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001949 if (DBG) {
1950 Slog.d(TAG, "MESSAGE_USER_UNLOCKED");
1951 }
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001952 mHandler.removeMessages(MESSAGE_USER_SWITCHED);
1953
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001954 if (mEnable && !mBinding && (mBluetooth == null)) {
1955 // We should be connected, but we gave up for some
1956 // reason; maybe the Bluetooth service wasn't encryption
1957 // aware, so try binding again.
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001958 if (DBG) {
1959 Slog.d(TAG, "Enabled but not bound; retrying after unlock");
1960 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001961 handleEnable(mQuietEnable);
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001962 }
1963 }
fredc0f420372012-04-12 00:02:00 -07001964 }
1965 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001966 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001967
Zhihai Xu401202b2012-12-03 11:36:21 -08001968 private void handleEnable(boolean quietMode) {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001969 mQuietEnable = quietMode;
1970
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001971 try {
1972 mBluetoothLock.writeLock().lock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001973 if ((mBluetooth == null) && (!mBinding)) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001974 //Start bind timeout and bind
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001975 Message timeoutMsg = mHandler.obtainMessage(MESSAGE_TIMEOUT_BIND);
1976 mHandler.sendMessageDelayed(timeoutMsg, TIMEOUT_BIND_MS);
Matthew Xiecdce0b92012-07-12 19:06:15 -07001977 Intent i = new Intent(IBluetooth.class.getName());
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001978 if (!doBind(i, mConnection, Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT,
Dianne Hackbornce09f5a2014-10-10 15:03:13 -07001979 UserHandle.CURRENT)) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001980 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
Zhihai Xu40874a02012-10-08 17:57:03 -07001981 } else {
1982 mBinding = true;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001983 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001984 } else if (mBluetooth != null) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001985 //Enable bluetooth
1986 try {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001987 if (!mQuietEnable) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001988 if (!mBluetooth.enable()) {
1989 Slog.e(TAG, "IBluetooth.enable() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001990 }
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001991 } else {
1992 if (!mBluetooth.enableNoAutoConnect()) {
1993 Slog.e(TAG, "IBluetooth.enableNoAutoConnect() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001994 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001995 }
1996 } catch (RemoteException e) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001997 Slog.e(TAG, "Unable to call enable()", e);
Matthew Xiecdce0b92012-07-12 19:06:15 -07001998 }
1999 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07002000 } finally {
2001 mBluetoothLock.writeLock().unlock();
Matthew Xiecdce0b92012-07-12 19:06:15 -07002002 }
2003 }
2004
Dianne Hackborn221ea892013-08-04 16:50:16 -07002005 boolean doBind(Intent intent, ServiceConnection conn, int flags, UserHandle user) {
2006 ComponentName comp = intent.resolveSystemService(mContext.getPackageManager(), 0);
2007 intent.setComponent(comp);
2008 if (comp == null || !mContext.bindServiceAsUser(intent, conn, flags, user)) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07002009 Slog.e(TAG, "Fail to bind to: " + intent);
Dianne Hackborn221ea892013-08-04 16:50:16 -07002010 return false;
2011 }
2012 return true;
2013 }
2014
Zhihai Xu401202b2012-12-03 11:36:21 -08002015 private void handleDisable() {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07002016 try {
2017 mBluetoothLock.readLock().lock();
Andre Eisenbach305fdab2015-11-11 21:43:26 -08002018 if (mBluetooth != null) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002019 if (DBG) {
2020 Slog.d(TAG, "Sending off request.");
2021 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07002022 if (!mBluetooth.disable()) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002023 Slog.e(TAG, "IBluetooth.disable() returned false");
Matthew Xiecdce0b92012-07-12 19:06:15 -07002024 }
2025 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07002026 } catch (RemoteException e) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002027 Slog.e(TAG, "Unable to call disable()", e);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07002028 } finally {
2029 mBluetoothLock.readLock().unlock();
Matthew Xiecdce0b92012-07-12 19:06:15 -07002030 }
2031 }
Zhihai Xu40874a02012-10-08 17:57:03 -07002032
2033 private boolean checkIfCallerIsForegroundUser() {
2034 int foregroundUser;
2035 int callingUser = UserHandle.getCallingUserId();
Martijn Coenen8385c5a2012-11-29 10:14:16 -08002036 int callingUid = Binder.getCallingUid();
Zhihai Xu40874a02012-10-08 17:57:03 -07002037 long callingIdentity = Binder.clearCallingIdentity();
Benjamin Franze8b98922014-11-12 15:57:54 +00002038 UserManager um = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
2039 UserInfo ui = um.getProfileParent(callingUser);
2040 int parentUser = (ui != null) ? ui.id : UserHandle.USER_NULL;
Martijn Coenen8385c5a2012-11-29 10:14:16 -08002041 int callingAppId = UserHandle.getAppId(callingUid);
Zhihai Xu40874a02012-10-08 17:57:03 -07002042 boolean valid = false;
2043 try {
2044 foregroundUser = ActivityManager.getCurrentUser();
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002045 valid = (callingUser == foregroundUser) || parentUser == foregroundUser
2046 || callingAppId == Process.NFC_UID || callingAppId == mSystemUiUid;
Marie Janssencb21ad72016-12-13 10:51:02 -08002047 if (DBG && !valid) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002048 Slog.d(TAG, "checkIfCallerIsForegroundUser: valid=" + valid + " callingUser="
2049 + callingUser + " parentUser=" + parentUser + " foregroundUser="
2050 + foregroundUser);
Zhihai Xu40874a02012-10-08 17:57:03 -07002051 }
2052 } finally {
2053 Binder.restoreCallingIdentity(callingIdentity);
2054 }
2055 return valid;
2056 }
2057
Nitin Arorad055adb2015-03-02 15:03:51 -08002058 private void sendBleStateChanged(int prevState, int newState) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002059 if (DBG) {
2060 Slog.d(TAG,
2061 "Sending BLE State Change: " + BluetoothAdapter.nameForState(prevState) + " > "
2062 + BluetoothAdapter.nameForState(newState));
2063 }
Nitin Arorad055adb2015-03-02 15:03:51 -08002064 // Send broadcast message to everyone else
2065 Intent intent = new Intent(BluetoothAdapter.ACTION_BLE_STATE_CHANGED);
2066 intent.putExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE, prevState);
2067 intent.putExtra(BluetoothAdapter.EXTRA_STATE, newState);
2068 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
2069 mContext.sendBroadcastAsUser(intent, UserHandle.ALL, BLUETOOTH_PERM);
2070 }
2071
Zhihai Xu40874a02012-10-08 17:57:03 -07002072 private void bluetoothStateChangeHandler(int prevState, int newState) {
Nitin Arorad055adb2015-03-02 15:03:51 -08002073 boolean isStandardBroadcast = true;
Marie Janssencb21ad72016-12-13 10:51:02 -08002074 if (prevState == newState) { // No change. Nothing to do.
2075 return;
2076 }
2077 // Notify all proxy objects first of adapter state change
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002078 if (newState == BluetoothAdapter.STATE_BLE_ON || newState == BluetoothAdapter.STATE_OFF) {
Marie Janssencb21ad72016-12-13 10:51:02 -08002079 boolean intermediate_off = (prevState == BluetoothAdapter.STATE_TURNING_OFF
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002080 && newState == BluetoothAdapter.STATE_BLE_ON);
Zhihai Xu40874a02012-10-08 17:57:03 -07002081
Marie Janssencb21ad72016-12-13 10:51:02 -08002082 if (newState == BluetoothAdapter.STATE_OFF) {
2083 // If Bluetooth is off, send service down event to proxy objects, and unbind
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002084 if (DBG) {
2085 Slog.d(TAG, "Bluetooth is complete send Service Down");
2086 }
Marie Janssencb21ad72016-12-13 10:51:02 -08002087 sendBluetoothServiceDownCallback();
2088 unbindAndFinish();
Nitin Arorad055adb2015-03-02 15:03:51 -08002089 sendBleStateChanged(prevState, newState);
Marie Janssencb21ad72016-12-13 10:51:02 -08002090 // Don't broadcast as it has already been broadcast before
Nitin Arorad055adb2015-03-02 15:03:51 -08002091 isStandardBroadcast = false;
2092
Marie Janssencb21ad72016-12-13 10:51:02 -08002093 } else if (!intermediate_off) {
2094 // connect to GattService
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002095 if (DBG) {
2096 Slog.d(TAG, "Bluetooth is in LE only mode");
2097 }
Myles Watson304ebf22018-05-11 08:47:24 -07002098 if (mBluetoothGatt != null || !mContext.getPackageManager()
2099 .hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
2100 continueFromBleOnState();
Marie Janssencb21ad72016-12-13 10:51:02 -08002101 } else {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002102 if (DBG) {
2103 Slog.d(TAG, "Binding Bluetooth GATT service");
2104 }
Myles Watson304ebf22018-05-11 08:47:24 -07002105 Intent i = new Intent(IBluetoothGatt.class.getName());
2106 doBind(i, mConnection, Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT,
2107 UserHandle.CURRENT);
Nitin Arorad055adb2015-03-02 15:03:51 -08002108 }
Marie Janssencb21ad72016-12-13 10:51:02 -08002109 sendBleStateChanged(prevState, newState);
2110 //Don't broadcase this as std intent
2111 isStandardBroadcast = false;
2112
2113 } else if (intermediate_off) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002114 if (DBG) {
2115 Slog.d(TAG, "Intermediate off, back to LE only mode");
2116 }
Marie Janssencb21ad72016-12-13 10:51:02 -08002117 // For LE only mode, broadcast as is
2118 sendBleStateChanged(prevState, newState);
2119 sendBluetoothStateCallback(false); // BT is OFF for general users
2120 // Broadcast as STATE_OFF
2121 newState = BluetoothAdapter.STATE_OFF;
2122 sendBrEdrDownCallback();
Nitin Arorad055adb2015-03-02 15:03:51 -08002123 }
Marie Janssencb21ad72016-12-13 10:51:02 -08002124 } else if (newState == BluetoothAdapter.STATE_ON) {
2125 boolean isUp = (newState == BluetoothAdapter.STATE_ON);
2126 sendBluetoothStateCallback(isUp);
2127 sendBleStateChanged(prevState, newState);
2128
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002129 } else if (newState == BluetoothAdapter.STATE_BLE_TURNING_ON
2130 || newState == BluetoothAdapter.STATE_BLE_TURNING_OFF) {
Marie Janssencb21ad72016-12-13 10:51:02 -08002131 sendBleStateChanged(prevState, newState);
2132 isStandardBroadcast = false;
2133
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002134 } else if (newState == BluetoothAdapter.STATE_TURNING_ON
2135 || newState == BluetoothAdapter.STATE_TURNING_OFF) {
Marie Janssencb21ad72016-12-13 10:51:02 -08002136 sendBleStateChanged(prevState, newState);
2137 }
2138
2139 if (isStandardBroadcast) {
2140 if (prevState == BluetoothAdapter.STATE_BLE_ON) {
2141 // Show prevState of BLE_ON as OFF to standard users
2142 prevState = BluetoothAdapter.STATE_OFF;
2143 }
2144 Intent intent = new Intent(BluetoothAdapter.ACTION_STATE_CHANGED);
2145 intent.putExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE, prevState);
2146 intent.putExtra(BluetoothAdapter.EXTRA_STATE, newState);
2147 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
2148 mContext.sendBroadcastAsUser(intent, UserHandle.ALL, BLUETOOTH_PERM);
Zhihai Xu40874a02012-10-08 17:57:03 -07002149 }
2150 }
2151
2152 /**
2153 * if on is true, wait for state become ON
2154 * if off is true, wait for state become OFF
2155 * if both on and off are false, wait for state not ON
2156 */
2157 private boolean waitForOnOff(boolean on, boolean off) {
2158 int i = 0;
2159 while (i < 10) {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07002160 try {
2161 mBluetoothLock.readLock().lock();
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002162 if (mBluetooth == null) {
2163 break;
2164 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07002165 if (on) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002166 if (mBluetooth.getState() == BluetoothAdapter.STATE_ON) {
2167 return true;
2168 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07002169 } else if (off) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002170 if (mBluetooth.getState() == BluetoothAdapter.STATE_OFF) {
2171 return true;
2172 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07002173 } else {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002174 if (mBluetooth.getState() != BluetoothAdapter.STATE_ON) {
2175 return true;
2176 }
Zhihai Xu40874a02012-10-08 17:57:03 -07002177 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07002178 } catch (RemoteException e) {
2179 Slog.e(TAG, "getState()", e);
2180 break;
2181 } finally {
2182 mBluetoothLock.readLock().unlock();
Zhihai Xu40874a02012-10-08 17:57:03 -07002183 }
2184 if (on || off) {
2185 SystemClock.sleep(300);
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07002186 } else {
Zhihai Xu40874a02012-10-08 17:57:03 -07002187 SystemClock.sleep(50);
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07002188 }
Zhihai Xu40874a02012-10-08 17:57:03 -07002189 i++;
2190 }
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002191 Slog.e(TAG, "waitForOnOff time out");
Zhihai Xu40874a02012-10-08 17:57:03 -07002192 return false;
2193 }
Zhihai Xu681ae7f2012-11-12 15:14:18 -08002194
Jack He8caab152018-03-02 13:08:36 -08002195 private void sendDisableMsg(int reason, String packageName) {
Zhihai Xu401202b2012-12-03 11:36:21 -08002196 mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_DISABLE));
Jack He8caab152018-03-02 13:08:36 -08002197 addActiveLog(reason, packageName, false);
Zhihai Xu401202b2012-12-03 11:36:21 -08002198 }
2199
Jack He8caab152018-03-02 13:08:36 -08002200 private void sendEnableMsg(boolean quietMode, int reason, String packageName) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002201 mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_ENABLE, quietMode ? 1 : 0, 0));
Jack He8caab152018-03-02 13:08:36 -08002202 addActiveLog(reason, packageName, true);
Marie Janssen12a35012017-06-26 07:21:03 -07002203 mLastEnabledTime = SystemClock.elapsedRealtime();
Marie Janssen59804562016-12-28 14:13:21 -08002204 }
2205
Jack He8caab152018-03-02 13:08:36 -08002206 private void addActiveLog(int reason, String packageName, boolean enable) {
Marie Janssen59804562016-12-28 14:13:21 -08002207 synchronized (mActiveLogs) {
Marie Janssene54b4222017-03-16 18:10:59 -07002208 if (mActiveLogs.size() > ACTIVE_LOG_MAX_SIZE) {
Marie Janssen59804562016-12-28 14:13:21 -08002209 mActiveLogs.remove();
2210 }
Jack He8caab152018-03-02 13:08:36 -08002211 mActiveLogs.add(
2212 new ActiveLog(reason, packageName, enable, System.currentTimeMillis()));
Marie Janssen59804562016-12-28 14:13:21 -08002213 }
Tej Singhd8e7cc62018-03-22 18:30:31 +00002214
2215 int state = enable ? StatsLog.BLUETOOTH_ENABLED_STATE_CHANGED__STATE__ENABLED :
2216 StatsLog.BLUETOOTH_ENABLED_STATE_CHANGED__STATE__DISABLED;
2217 StatsLog.write_non_chained(StatsLog.BLUETOOTH_ENABLED_STATE_CHANGED,
2218 Binder.getCallingUid(), null, state, reason, packageName);
Zhihai Xu401202b2012-12-03 11:36:21 -08002219 }
2220
Marie Janssene54b4222017-03-16 18:10:59 -07002221 private void addCrashLog() {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002222 synchronized (mCrashTimestamps) {
2223 if (mCrashTimestamps.size() == CRASH_LOG_MAX_SIZE) {
2224 mCrashTimestamps.removeFirst();
2225 }
2226 mCrashTimestamps.add(System.currentTimeMillis());
2227 mCrashes++;
2228 }
Marie Janssene54b4222017-03-16 18:10:59 -07002229 }
2230
Marie Janssen2977c3e2016-11-09 12:01:24 -08002231 private void recoverBluetoothServiceFromError(boolean clearBle) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002232 Slog.e(TAG, "recoverBluetoothServiceFromError");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07002233 try {
2234 mBluetoothLock.readLock().lock();
Zhihai Xudd9d17d2013-01-08 17:05:58 -08002235 if (mBluetooth != null) {
2236 //Unregister callback object
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07002237 mBluetooth.unregisterCallback(mBluetoothCallback);
Zhihai Xudd9d17d2013-01-08 17:05:58 -08002238 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07002239 } catch (RemoteException re) {
2240 Slog.e(TAG, "Unable to unregister", re);
2241 } finally {
2242 mBluetoothLock.readLock().unlock();
Zhihai Xudd9d17d2013-01-08 17:05:58 -08002243 }
2244
2245 SystemClock.sleep(500);
2246
2247 // disable
Jack He8caab152018-03-02 13:08:36 -08002248 addActiveLog(BluetoothProtoEnums.ENABLE_DISABLE_REASON_START_ERROR,
2249 mContext.getPackageName(), false);
Zhihai Xudd9d17d2013-01-08 17:05:58 -08002250 handleDisable();
2251
2252 waitForOnOff(false, true);
2253
2254 sendBluetoothServiceDownCallback();
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07002255
Pavlin Radoslavove957a8a2016-05-24 15:28:41 -07002256 try {
2257 mBluetoothLock.writeLock().lock();
2258 if (mBluetooth != null) {
2259 mBluetooth = null;
2260 // Unbind
2261 mContext.unbindService(mConnection);
2262 }
2263 mBluetoothGatt = null;
2264 } finally {
2265 mBluetoothLock.writeLock().unlock();
Zhihai Xudd9d17d2013-01-08 17:05:58 -08002266 }
2267
2268 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
2269 mState = BluetoothAdapter.STATE_OFF;
2270
Marie Janssen2977c3e2016-11-09 12:01:24 -08002271 if (clearBle) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002272 clearBleApps();
Marie Janssen2977c3e2016-11-09 12:01:24 -08002273 }
2274
Zhihai Xudd9d17d2013-01-08 17:05:58 -08002275 mEnable = false;
2276
2277 if (mErrorRecoveryRetryCounter++ < MAX_ERROR_RESTART_RETRIES) {
2278 // Send a Bluetooth Restart message to reenable bluetooth
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002279 Message restartMsg = mHandler.obtainMessage(MESSAGE_RESTART_BLUETOOTH_SERVICE);
Zhihai Xudd9d17d2013-01-08 17:05:58 -08002280 mHandler.sendMessageDelayed(restartMsg, ERROR_RESTART_TIME_MS);
2281 } else {
2282 // todo: notify user to power down and power up phone to make bluetooth work.
2283 }
2284 }
Mike Lockwood726d4de2014-10-28 14:06:28 -07002285
Lenka Trochtova63d5e4a72016-12-02 12:19:39 +01002286 private boolean isBluetoothDisallowed() {
2287 long callingIdentity = Binder.clearCallingIdentity();
2288 try {
2289 return mContext.getSystemService(UserManager.class)
2290 .hasUserRestriction(UserManager.DISALLOW_BLUETOOTH, UserHandle.SYSTEM);
2291 } finally {
2292 Binder.restoreCallingIdentity(callingIdentity);
2293 }
2294 }
2295
Lenka Trochtovac6f0e232017-01-17 10:35:49 +01002296 /**
2297 * Disables BluetoothOppLauncherActivity component, so the Bluetooth sharing option is not
Pavel Grafov4f4f6f82017-03-28 13:44:04 +01002298 * offered to the user if Bluetooth or sharing is disallowed. Puts the component to its default
2299 * state if Bluetooth is not disallowed.
Lenka Trochtovac6f0e232017-01-17 10:35:49 +01002300 *
Pavel Grafov4f4f6f82017-03-28 13:44:04 +01002301 * @param userId user to disable bluetooth sharing for.
2302 * @param bluetoothSharingDisallowed whether bluetooth sharing is disallowed.
Lenka Trochtovac6f0e232017-01-17 10:35:49 +01002303 */
Pavel Grafov4f4f6f82017-03-28 13:44:04 +01002304 private void updateOppLauncherComponentState(int userId, boolean bluetoothSharingDisallowed) {
Lenka Trochtovac6f0e232017-01-17 10:35:49 +01002305 final ComponentName oppLauncherComponent = new ComponentName("com.android.bluetooth",
2306 "com.android.bluetooth.opp.BluetoothOppLauncherActivity");
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002307 final int newState =
2308 bluetoothSharingDisallowed ? PackageManager.COMPONENT_ENABLED_STATE_DISABLED
2309 : PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
Lenka Trochtovac6f0e232017-01-17 10:35:49 +01002310 try {
Pavel Grafov4f4f6f82017-03-28 13:44:04 +01002311 final IPackageManager imp = AppGlobals.getPackageManager();
Myles Watson6291fae2017-06-29 03:12:02 -07002312 imp.setComponentEnabledSetting(oppLauncherComponent, newState,
2313 PackageManager.DONT_KILL_APP, userId);
Lenka Trochtovac6f0e232017-01-17 10:35:49 +01002314 } catch (Exception e) {
2315 // The component was not found, do nothing.
2316 }
2317 }
2318
Mike Lockwood726d4de2014-10-28 14:06:28 -07002319 @Override
Pavlin Radoslavov6e8faff2016-02-23 11:54:37 -08002320 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002321 if (!DumpUtils.checkDumpPermission(mContext, TAG, writer)) {
2322 return;
2323 }
Pavlin Radoslavov6e8faff2016-02-23 11:54:37 -08002324 String errorMsg = null;
Marie Janssen59804562016-12-28 14:13:21 -08002325
2326 boolean protoOut = (args.length > 0) && args[0].startsWith("--proto");
2327
2328 if (!protoOut) {
2329 writer.println("Bluetooth Status");
2330 writer.println(" enabled: " + isEnabled());
2331 writer.println(" state: " + BluetoothAdapter.nameForState(mState));
2332 writer.println(" address: " + mAddress);
2333 writer.println(" name: " + mName);
2334 if (mEnable) {
Marie Janssen12a35012017-06-26 07:21:03 -07002335 long onDuration = SystemClock.elapsedRealtime() - mLastEnabledTime;
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002336 String onDurationString = String.format(Locale.US, "%02d:%02d:%02d.%03d",
2337 (int) (onDuration / (1000 * 60 * 60)),
2338 (int) ((onDuration / (1000 * 60)) % 60), (int) ((onDuration / 1000) % 60),
2339 (int) (onDuration % 1000));
Andre Eisenbache66e1682017-04-10 13:49:13 -07002340 writer.println(" time since enabled: " + onDurationString);
Marie Janssen59804562016-12-28 14:13:21 -08002341 }
2342
Marie Janssena95924d2017-01-18 09:37:52 -08002343 if (mActiveLogs.size() == 0) {
Andre Eisenbache66e1682017-04-10 13:49:13 -07002344 writer.println("\nBluetooth never enabled!");
Marie Janssena95924d2017-01-18 09:37:52 -08002345 } else {
Andre Eisenbache66e1682017-04-10 13:49:13 -07002346 writer.println("\nEnable log:");
Marie Janssena95924d2017-01-18 09:37:52 -08002347 for (ActiveLog log : mActiveLogs) {
2348 writer.println(" " + log);
2349 }
Marie Janssen59804562016-12-28 14:13:21 -08002350 }
2351
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002352 writer.println(
2353 "\nBluetooth crashed " + mCrashes + " time" + (mCrashes == 1 ? "" : "s"));
2354 if (mCrashes == CRASH_LOG_MAX_SIZE) {
2355 writer.println("(last " + CRASH_LOG_MAX_SIZE + ")");
2356 }
Marie Janssene54b4222017-03-16 18:10:59 -07002357 for (Long time : mCrashTimestamps) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002358 writer.println(" " + timeToLog(time));
Marie Janssene54b4222017-03-16 18:10:59 -07002359 }
2360
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002361 writer.println("\n" + mBleApps.size() + " BLE app" + (mBleApps.size() == 1 ? "" : "s")
2362 + "registered");
Marie Janssen59804562016-12-28 14:13:21 -08002363 for (ClientDeathRecipient app : mBleApps.values()) {
Marie Janssena95924d2017-01-18 09:37:52 -08002364 writer.println(" " + app.getPackageName());
Marie Janssen59804562016-12-28 14:13:21 -08002365 }
2366
Marie Janssena95924d2017-01-18 09:37:52 -08002367 writer.println("");
Marie Janssen59804562016-12-28 14:13:21 -08002368 writer.flush();
Marie Janssenf5ec5382017-01-03 11:37:38 -08002369 if (args.length == 0) {
Marie Janssena95924d2017-01-18 09:37:52 -08002370 // Add arg to produce output
2371 args = new String[1];
2372 args[0] = "--print";
Marie Janssenf5ec5382017-01-03 11:37:38 -08002373 }
Marie Janssen59804562016-12-28 14:13:21 -08002374 }
2375
Pavlin Radoslavov6e8faff2016-02-23 11:54:37 -08002376 if (mBluetoothBinder == null) {
2377 errorMsg = "Bluetooth Service not connected";
2378 } else {
2379 try {
2380 mBluetoothBinder.dump(fd, args);
2381 } catch (RemoteException re) {
Marie Janssen59804562016-12-28 14:13:21 -08002382 errorMsg = "RemoteException while dumping Bluetooth Service";
Pavlin Radoslavov6e8faff2016-02-23 11:54:37 -08002383 }
Mike Lockwood726d4de2014-10-28 14:06:28 -07002384 }
Pavlin Radoslavov6e8faff2016-02-23 11:54:37 -08002385 if (errorMsg != null) {
2386 // Silently return if we are extracting metrics in Protobuf format
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002387 if (protoOut) {
2388 return;
2389 }
Pavlin Radoslavov6e8faff2016-02-23 11:54:37 -08002390 writer.println(errorMsg);
2391 }
Mike Lockwood726d4de2014-10-28 14:06:28 -07002392 }
Jack He8caab152018-03-02 13:08:36 -08002393
2394 private static String getEnableDisableReasonString(int reason) {
2395 switch (reason) {
2396 case BluetoothProtoEnums.ENABLE_DISABLE_REASON_APPLICATION_REQUEST:
2397 return "APPLICATION_REQUEST";
2398 case BluetoothProtoEnums.ENABLE_DISABLE_REASON_AIRPLANE_MODE:
2399 return "AIRPLANE_MODE";
2400 case BluetoothProtoEnums.ENABLE_DISABLE_REASON_DISALLOWED:
2401 return "DISALLOWED";
2402 case BluetoothProtoEnums.ENABLE_DISABLE_REASON_RESTARTED:
2403 return "RESTARTED";
2404 case BluetoothProtoEnums.ENABLE_DISABLE_REASON_START_ERROR:
2405 return "START_ERROR";
2406 case BluetoothProtoEnums.ENABLE_DISABLE_REASON_SYSTEM_BOOT:
2407 return "SYSTEM_BOOT";
2408 case BluetoothProtoEnums.ENABLE_DISABLE_REASON_CRASH:
2409 return "CRASH";
2410 case BluetoothProtoEnums.ENABLE_DISABLE_REASON_USER_SWITCH:
2411 return "USER_SWITCH";
2412 case BluetoothProtoEnums.ENABLE_DISABLE_REASON_RESTORE_USER_SETTING:
2413 return "RESTORE_USER_SETTING";
2414 case BluetoothProtoEnums.ENABLE_DISABLE_REASON_UNSPECIFIED:
2415 default: return "UNKNOWN[" + reason + "]";
2416 }
2417 }
fredc0f420372012-04-12 00:02:00 -07002418}