blob: 2827bd3261196992afa8146c527354efa20a4b29 [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;
Jack Hea80cead2019-04-23 20:00:18 -070022import android.app.AppOpsManager;
fredc0f420372012-04-12 00:02:00 -070023import android.bluetooth.BluetoothAdapter;
Benjamin Franze8b98922014-11-12 15:57:54 +000024import android.bluetooth.BluetoothProfile;
Jack He8caab152018-03-02 13:08:36 -080025import android.bluetooth.BluetoothProtoEnums;
fredc0f420372012-04-12 00:02:00 -070026import android.bluetooth.IBluetooth;
fredcbf072a72012-05-09 16:52:50 -070027import android.bluetooth.IBluetoothCallback;
Wei Wange4a744b2015-06-11 17:50:29 -070028import android.bluetooth.IBluetoothGatt;
Benjamin Franze8b98922014-11-12 15:57:54 +000029import android.bluetooth.IBluetoothHeadset;
fredc0f420372012-04-12 00:02:00 -070030import android.bluetooth.IBluetoothManager;
31import android.bluetooth.IBluetoothManagerCallback;
Benjamin Franze8b98922014-11-12 15:57:54 +000032import android.bluetooth.IBluetoothProfileServiceConnection;
fredc0f420372012-04-12 00:02:00 -070033import android.bluetooth.IBluetoothStateChangeCallback;
Svet Ganov77df6f32016-08-17 11:46:34 -070034import android.content.ActivityNotFoundException;
fredc0f420372012-04-12 00:02:00 -070035import android.content.BroadcastReceiver;
36import android.content.ComponentName;
37import android.content.ContentResolver;
38import android.content.Context;
39import android.content.Intent;
40import android.content.IntentFilter;
41import android.content.ServiceConnection;
Svetoslav Ganovac69be52016-06-29 17:31:44 -070042import android.content.pm.ApplicationInfo;
Pavel Grafov4f4f6f82017-03-28 13:44:04 +010043import android.content.pm.IPackageManager;
Matthew Xie32ab77b2013-05-08 19:26:57 -070044import android.content.pm.PackageManager;
Benjamin Franze8b98922014-11-12 15:57:54 +000045import android.content.pm.UserInfo;
Wei Wange4a744b2015-06-11 17:50:29 -070046import android.database.ContentObserver;
Zhihai Xu40874a02012-10-08 17:57:03 -070047import android.os.Binder;
Lenka Trochtova63d5e4a72016-12-02 12:19:39 +010048import android.os.Bundle;
fredc0f420372012-04-12 00:02:00 -070049import android.os.Handler;
fredc0f420372012-04-12 00:02:00 -070050import android.os.IBinder;
Zhihai Xu40874a02012-10-08 17:57:03 -070051import android.os.Looper;
fredc0f420372012-04-12 00:02:00 -070052import android.os.Message;
Zhihai Xu40874a02012-10-08 17:57:03 -070053import android.os.Process;
fredcd6883532012-04-25 17:46:13 -070054import android.os.RemoteCallbackList;
fredc0f420372012-04-12 00:02:00 -070055import android.os.RemoteException;
Zhihai Xu40874a02012-10-08 17:57:03 -070056import android.os.SystemClock;
Stanley Tngfe8c8332018-06-19 08:48:10 -070057import android.os.SystemProperties;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070058import android.os.UserHandle;
Benjamin Franze8b98922014-11-12 15:57:54 +000059import android.os.UserManager;
Lenka Trochtova63d5e4a72016-12-02 12:19:39 +010060import android.os.UserManagerInternal;
61import android.os.UserManagerInternal.UserRestrictionsListener;
fredc0f420372012-04-12 00:02:00 -070062import android.provider.Settings;
Wei Wang67d84162015-04-26 17:04:29 -070063import android.provider.Settings.SettingNotFoundException;
Stanley Tngfe8c8332018-06-19 08:48:10 -070064import android.text.TextUtils;
65import android.util.FeatureFlagUtils;
66import android.util.Log;
Jeff Sharkey67609c72016-03-05 14:29:13 -070067import android.util.Slog;
Tej Singhd8e7cc62018-03-22 18:30:31 +000068import android.util.StatsLog;
Mike Lockwood726d4de2014-10-28 14:06:28 -070069
Arthur Hsuf3f95a92018-01-11 16:46:22 -080070import com.android.internal.R;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060071import com.android.internal.util.DumpUtils;
Pavel Grafov4f4f6f82017-03-28 13:44:04 +010072import com.android.server.pm.UserRestrictionsUtils;
Lenka Trochtovac6f0e232017-01-17 10:35:49 +010073
Mike Lockwood726d4de2014-10-28 14:06:28 -070074import java.io.FileDescriptor;
75import java.io.PrintWriter;
Benjamin Franze8b98922014-11-12 15:57:54 +000076import java.util.HashMap;
Marie Janssen59804562016-12-28 14:13:21 -080077import java.util.LinkedList;
Myles Watsonb5cd11a2017-11-27 16:42:11 -080078import java.util.Locale;
Benjamin Franze8b98922014-11-12 15:57:54 +000079import java.util.Map;
Chienyuan177156b2018-12-18 10:40:25 +080080import java.util.NoSuchElementException;
Pavel Grafov4f4f6f82017-03-28 13:44:04 +010081import java.util.concurrent.ConcurrentHashMap;
82import java.util.concurrent.locks.ReentrantReadWriteLock;
Miao Chou658bf2f2015-06-26 17:14:35 -070083
Marie Janssen59804562016-12-28 14:13:21 -080084
fredc0f420372012-04-12 00:02:00 -070085class BluetoothManagerService extends IBluetoothManager.Stub {
86 private static final String TAG = "BluetoothManagerService";
Pavlin Radoslavov41401112016-06-27 15:25:18 -070087 private static final boolean DBG = true;
fredc0f420372012-04-12 00:02:00 -070088
fredc0f420372012-04-12 00:02:00 -070089 private static final String BLUETOOTH_ADMIN_PERM = android.Manifest.permission.BLUETOOTH_ADMIN;
90 private static final String BLUETOOTH_PERM = android.Manifest.permission.BLUETOOTH;
Marie Janssene54b4222017-03-16 18:10:59 -070091
Myles Watsonb5cd11a2017-11-27 16:42:11 -080092 private static final String SECURE_SETTINGS_BLUETOOTH_ADDR_VALID = "bluetooth_addr_valid";
93 private static final String SECURE_SETTINGS_BLUETOOTH_ADDRESS = "bluetooth_address";
94 private static final String SECURE_SETTINGS_BLUETOOTH_NAME = "bluetooth_name";
Marie Janssene54b4222017-03-16 18:10:59 -070095
96 private static final int ACTIVE_LOG_MAX_SIZE = 20;
97 private static final int CRASH_LOG_MAX_SIZE = 100;
Marie Janssene54b4222017-03-16 18:10:59 -070098
fredc0f420372012-04-12 00:02:00 -070099 private static final int TIMEOUT_BIND_MS = 3000; //Maximum msec to wait for a bind
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +0530100 //Maximum msec to wait for service restart
101 private static final int SERVICE_RESTART_TIME_MS = 200;
Zhihai Xudd9d17d2013-01-08 17:05:58 -0800102 //Maximum msec to wait for restart due to error
103 private static final int ERROR_RESTART_TIME_MS = 3000;
Zhihai Xu40874a02012-10-08 17:57:03 -0700104 //Maximum msec to delay MESSAGE_USER_SWITCHED
105 private static final int USER_SWITCHED_TIME_MS = 200;
Benjamin Franze8b98922014-11-12 15:57:54 +0000106 // Delay for the addProxy function in msec
107 private static final int ADD_PROXY_DELAY_MS = 100;
fredc0f420372012-04-12 00:02:00 -0700108
109 private static final int MESSAGE_ENABLE = 1;
110 private static final int MESSAGE_DISABLE = 2;
fredc649fe492012-04-19 01:07:18 -0700111 private static final int MESSAGE_REGISTER_ADAPTER = 20;
112 private static final int MESSAGE_UNREGISTER_ADAPTER = 21;
113 private static final int MESSAGE_REGISTER_STATE_CHANGE_CALLBACK = 30;
114 private static final int MESSAGE_UNREGISTER_STATE_CHANGE_CALLBACK = 31;
115 private static final int MESSAGE_BLUETOOTH_SERVICE_CONNECTED = 40;
116 private static final int MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED = 41;
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +0530117 private static final int MESSAGE_RESTART_BLUETOOTH_SERVICE = 42;
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -0700118 private static final int MESSAGE_BLUETOOTH_STATE_CHANGE = 60;
119 private static final int MESSAGE_TIMEOUT_BIND = 100;
120 private static final int MESSAGE_TIMEOUT_UNBIND = 101;
Ajay Panicker4bb48302016-03-31 14:14:27 -0700121 private static final int MESSAGE_GET_NAME_AND_ADDRESS = 200;
Zhihai Xu40874a02012-10-08 17:57:03 -0700122 private static final int MESSAGE_USER_SWITCHED = 300;
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -0700123 private static final int MESSAGE_USER_UNLOCKED = 301;
Benjamin Franze8b98922014-11-12 15:57:54 +0000124 private static final int MESSAGE_ADD_PROXY_DELAYED = 400;
125 private static final int MESSAGE_BIND_PROFILE_SERVICE = 401;
Stanley Tng873b5702017-05-01 21:27:31 -0700126 private static final int MESSAGE_RESTORE_USER_SETTING = 500;
127
128 private static final int RESTORE_SETTING_TO_ON = 1;
129 private static final int RESTORE_SETTING_TO_OFF = 0;
Marie Janssencb21ad72016-12-13 10:51:02 -0800130
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -0700131 private static final int MAX_ERROR_RESTART_RETRIES = 6;
Zhihai Xudd9d17d2013-01-08 17:05:58 -0800132
Zhihai Xu401202b2012-12-03 11:36:21 -0800133 // Bluetooth persisted setting is off
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800134 private static final int BLUETOOTH_OFF = 0;
Zhihai Xu401202b2012-12-03 11:36:21 -0800135 // Bluetooth persisted setting is on
136 // and Airplane mode won't affect Bluetooth state at start up
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800137 private static final int BLUETOOTH_ON_BLUETOOTH = 1;
Zhihai Xu401202b2012-12-03 11:36:21 -0800138 // Bluetooth persisted setting is on
139 // but Airplane mode will affect Bluetooth state at start up
140 // and Airplane mode will have higher priority.
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800141 private static final int BLUETOOTH_ON_AIRPLANE = 2;
fredc0f420372012-04-12 00:02:00 -0700142
Matthew Xieddf7e472013-03-01 18:41:02 -0800143 private static final int SERVICE_IBLUETOOTH = 1;
144 private static final int SERVICE_IBLUETOOTHGATT = 2;
145
fredc0f420372012-04-12 00:02:00 -0700146 private final Context mContext;
Matthew Xiecdce0b92012-07-12 19:06:15 -0700147
148 // Locks are not provided for mName and mAddress.
149 // They are accessed in handler or broadcast receiver, same thread context.
fredc0f420372012-04-12 00:02:00 -0700150 private String mAddress;
151 private String mName;
Matthew Xie6fde3092012-07-11 17:10:07 -0700152 private final ContentResolver mContentResolver;
153 private final RemoteCallbackList<IBluetoothManagerCallback> mCallbacks;
154 private final RemoteCallbackList<IBluetoothStateChangeCallback> mStateChangeCallbacks;
Marie Janssen9db28eb2016-01-12 16:05:15 -0800155 private IBinder mBluetoothBinder;
fredc649fe492012-04-19 01:07:18 -0700156 private IBluetooth mBluetooth;
Matthew Xieddf7e472013-03-01 18:41:02 -0800157 private IBluetoothGatt mBluetoothGatt;
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800158 private final ReentrantReadWriteLock mBluetoothLock = new ReentrantReadWriteLock();
fredc649fe492012-04-19 01:07:18 -0700159 private boolean mBinding;
160 private boolean mUnbinding;
Marie Janssen59804562016-12-28 14:13:21 -0800161
Zhihai Xu401202b2012-12-03 11:36:21 -0800162 // used inside handler thread
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700163 private boolean mQuietEnable = false;
Marie Janssen59804562016-12-28 14:13:21 -0800164 private boolean mEnable;
165
Jack He8caab152018-03-02 13:08:36 -0800166 private static CharSequence timeToLog(long timestamp) {
Marie Janssene54b4222017-03-16 18:10:59 -0700167 return android.text.format.DateFormat.format("MM-dd HH:mm:ss", timestamp);
168 }
169
Marie Janssen59804562016-12-28 14:13:21 -0800170 /**
171 * Used for tracking apps that enabled / disabled Bluetooth.
172 */
173 private class ActiveLog {
Jack He8caab152018-03-02 13:08:36 -0800174 private int mReason;
Marie Janssen59804562016-12-28 14:13:21 -0800175 private String mPackageName;
176 private boolean mEnable;
177 private long mTimestamp;
178
Jack He8caab152018-03-02 13:08:36 -0800179 ActiveLog(int reason, String packageName, boolean enable, long timestamp) {
180 mReason = reason;
Marie Janssen59804562016-12-28 14:13:21 -0800181 mPackageName = packageName;
182 mEnable = enable;
183 mTimestamp = timestamp;
184 }
185
Marie Janssen59804562016-12-28 14:13:21 -0800186 public String toString() {
Jack He8caab152018-03-02 13:08:36 -0800187 return timeToLog(mTimestamp) + (mEnable ? " Enabled " : " Disabled ")
188 + " due to " + getEnableDisableReasonString(mReason) + " by " + mPackageName;
Marie Janssen59804562016-12-28 14:13:21 -0800189 }
190
191 }
192
Jack He8caab152018-03-02 13:08:36 -0800193 private final LinkedList<ActiveLog> mActiveLogs = new LinkedList<>();
194 private final LinkedList<Long> mCrashTimestamps = new LinkedList<>();
Marie Janssene54b4222017-03-16 18:10:59 -0700195 private int mCrashes;
Marie Janssen12a35012017-06-26 07:21:03 -0700196 private long mLastEnabledTime;
Marie Janssen59804562016-12-28 14:13:21 -0800197
198 // configuration from external IBinder call which is used to
Zhihai Xu401202b2012-12-03 11:36:21 -0800199 // synchronize with broadcast receiver.
200 private boolean mQuietEnableExternal;
Zhihai Xu401202b2012-12-03 11:36:21 -0800201 private boolean mEnableExternal;
Marie Janssen59804562016-12-28 14:13:21 -0800202
203 // Map of apps registered to keep BLE scanning on.
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800204 private Map<IBinder, ClientDeathRecipient> mBleApps =
205 new ConcurrentHashMap<IBinder, ClientDeathRecipient>();
Marie Janssen59804562016-12-28 14:13:21 -0800206
Zhihai Xu40874a02012-10-08 17:57:03 -0700207 private int mState;
Zhihai Xu40874a02012-10-08 17:57:03 -0700208 private final BluetoothHandler mHandler;
Zhihai Xudd9d17d2013-01-08 17:05:58 -0800209 private int mErrorRecoveryRetryCounter;
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200210 private final int mSystemUiUid;
fredc0f420372012-04-12 00:02:00 -0700211
Stanley Tng61dbd812019-01-13 16:04:31 -0800212 private boolean mIsHearingAidProfileSupported;
213
Jack Hea80cead2019-04-23 20:00:18 -0700214 private AppOpsManager mAppOps;
215
Benjamin Franze8b98922014-11-12 15:57:54 +0000216 // Save a ProfileServiceConnections object for each of the bound
217 // bluetooth profile services
Jack He8caab152018-03-02 13:08:36 -0800218 private final Map<Integer, ProfileServiceConnections> mProfileServices = new HashMap<>();
Benjamin Franze8b98922014-11-12 15:57:54 +0000219
Philip P. Moltmann6c644e62018-07-18 15:41:24 -0700220 private final boolean mWirelessConsentRequired;
Svetoslav Ganovac69be52016-06-29 17:31:44 -0700221
Marie Janssen59804562016-12-28 14:13:21 -0800222 private final IBluetoothCallback mBluetoothCallback = new IBluetoothCallback.Stub() {
fredcbf072a72012-05-09 16:52:50 -0700223 @Override
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800224 public void onBluetoothStateChange(int prevState, int newState) throws RemoteException {
225 Message msg =
226 mHandler.obtainMessage(MESSAGE_BLUETOOTH_STATE_CHANGE, prevState, newState);
fredcbf072a72012-05-09 16:52:50 -0700227 mHandler.sendMessage(msg);
228 }
229 };
230
Lenka Trochtova63d5e4a72016-12-02 12:19:39 +0100231 private final UserRestrictionsListener mUserRestrictionsListener =
232 new UserRestrictionsListener() {
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800233 @Override
234 public void onUserRestrictionsChanged(int userId, Bundle newRestrictions,
235 Bundle prevRestrictions) {
Myles Watson6291fae2017-06-29 03:12:02 -0700236
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800237 if (UserRestrictionsUtils.restrictionsChanged(prevRestrictions, newRestrictions,
238 UserManager.DISALLOW_BLUETOOTH_SHARING)) {
239 updateOppLauncherComponentState(userId,
240 newRestrictions.getBoolean(UserManager.DISALLOW_BLUETOOTH_SHARING));
241 }
Pavel Grafov4f4f6f82017-03-28 13:44:04 +0100242
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800243 // DISALLOW_BLUETOOTH can only be set by DO or PO on the system user.
244 if (userId == UserHandle.USER_SYSTEM
245 && UserRestrictionsUtils.restrictionsChanged(prevRestrictions,
246 newRestrictions, UserManager.DISALLOW_BLUETOOTH)) {
247 if (userId == UserHandle.USER_SYSTEM && newRestrictions.getBoolean(
248 UserManager.DISALLOW_BLUETOOTH)) {
249 updateOppLauncherComponentState(userId, true); // Sharing disallowed
Jack He8caab152018-03-02 13:08:36 -0800250 sendDisableMsg(BluetoothProtoEnums.ENABLE_DISABLE_REASON_DISALLOWED,
251 mContext.getPackageName());
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800252 } else {
253 updateOppLauncherComponentState(userId, newRestrictions.getBoolean(
254 UserManager.DISALLOW_BLUETOOTH_SHARING));
255 }
256 }
Lenka Trochtova63d5e4a72016-12-02 12:19:39 +0100257 }
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800258 };
Lenka Trochtova63d5e4a72016-12-02 12:19:39 +0100259
Ajay Panicker467bc042017-02-22 12:23:15 -0800260 private final ContentObserver mAirplaneModeObserver = new ContentObserver(null) {
261 @Override
262 public void onChange(boolean unused) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800263 synchronized (this) {
Ajay Panicker467bc042017-02-22 12:23:15 -0800264 if (isBluetoothPersistedStateOn()) {
265 if (isAirplaneModeOn()) {
266 persistBluetoothSetting(BLUETOOTH_ON_AIRPLANE);
267 } else {
268 persistBluetoothSetting(BLUETOOTH_ON_BLUETOOTH);
269 }
270 }
271
272 int st = BluetoothAdapter.STATE_OFF;
273 try {
274 mBluetoothLock.readLock().lock();
275 if (mBluetooth != null) {
276 st = mBluetooth.getState();
277 }
278 } catch (RemoteException e) {
279 Slog.e(TAG, "Unable to call getState", e);
280 return;
281 } finally {
282 mBluetoothLock.readLock().unlock();
283 }
284
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800285 Slog.d(TAG,
286 "Airplane Mode change - current state: " + BluetoothAdapter.nameForState(
Rene Mayrhofer7d6c8e52018-11-28 11:32:40 -0800287 st) + ", isAirplaneModeOn()=" + isAirplaneModeOn());
Ajay Panicker467bc042017-02-22 12:23:15 -0800288
289 if (isAirplaneModeOn()) {
290 // Clear registered LE apps to force shut-off
291 clearBleApps();
292
293 // If state is BLE_ON make sure we trigger disableBLE
294 if (st == BluetoothAdapter.STATE_BLE_ON) {
295 try {
296 mBluetoothLock.readLock().lock();
297 if (mBluetooth != null) {
Hansong Zhang276eb1b2018-04-23 11:17:17 -0700298 addActiveLog(
299 BluetoothProtoEnums.ENABLE_DISABLE_REASON_AIRPLANE_MODE,
300 mContext.getPackageName(), false);
Ajay Panicker467bc042017-02-22 12:23:15 -0800301 mBluetooth.onBrEdrDown();
302 mEnable = false;
303 mEnableExternal = false;
304 }
305 } catch (RemoteException e) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800306 Slog.e(TAG, "Unable to call onBrEdrDown", e);
Ajay Panicker467bc042017-02-22 12:23:15 -0800307 } finally {
308 mBluetoothLock.readLock().unlock();
309 }
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800310 } else if (st == BluetoothAdapter.STATE_ON) {
Jack He8caab152018-03-02 13:08:36 -0800311 sendDisableMsg(BluetoothProtoEnums.ENABLE_DISABLE_REASON_AIRPLANE_MODE,
312 mContext.getPackageName());
Ajay Panicker467bc042017-02-22 12:23:15 -0800313 }
314 } else if (mEnableExternal) {
Jack He8caab152018-03-02 13:08:36 -0800315 sendEnableMsg(mQuietEnableExternal,
316 BluetoothProtoEnums.ENABLE_DISABLE_REASON_AIRPLANE_MODE,
317 mContext.getPackageName());
Ajay Panicker467bc042017-02-22 12:23:15 -0800318 }
319 }
320 }
321 };
322
fredcbf072a72012-05-09 16:52:50 -0700323 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
fredc0f420372012-04-12 00:02:00 -0700324 @Override
325 public void onReceive(Context context, Intent intent) {
326 String action = intent.getAction();
fredcbf072a72012-05-09 16:52:50 -0700327 if (BluetoothAdapter.ACTION_LOCAL_NAME_CHANGED.equals(action)) {
fredc0f420372012-04-12 00:02:00 -0700328 String newName = intent.getStringExtra(BluetoothAdapter.EXTRA_LOCAL_NAME);
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800329 if (DBG) {
330 Slog.d(TAG, "Bluetooth Adapter name changed to " + newName);
331 }
fredc0f420372012-04-12 00:02:00 -0700332 if (newName != null) {
333 storeNameAndAddress(newName, null);
334 }
Stanley Tngdd749b02017-04-17 22:35:45 -0700335 } else if (BluetoothAdapter.ACTION_BLUETOOTH_ADDRESS_CHANGED.equals(action)) {
336 String newAddress = intent.getStringExtra(BluetoothAdapter.EXTRA_BLUETOOTH_ADDRESS);
337 if (newAddress != null) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800338 if (DBG) {
339 Slog.d(TAG, "Bluetooth Adapter address changed to " + newAddress);
340 }
Stanley Tngdd749b02017-04-17 22:35:45 -0700341 storeNameAndAddress(null, newAddress);
342 } else {
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800343 if (DBG) {
344 Slog.e(TAG, "No Bluetooth Adapter address parameter found");
345 }
Stanley Tngdd749b02017-04-17 22:35:45 -0700346 }
Stanley Tng873b5702017-05-01 21:27:31 -0700347 } else if (Intent.ACTION_SETTING_RESTORED.equals(action)) {
348 final String name = intent.getStringExtra(Intent.EXTRA_SETTING_NAME);
349 if (Settings.Global.BLUETOOTH_ON.equals(name)) {
350 // The Bluetooth On state may be changed during system restore.
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800351 final String prevValue =
352 intent.getStringExtra(Intent.EXTRA_SETTING_PREVIOUS_VALUE);
353 final String newValue = intent.getStringExtra(Intent.EXTRA_SETTING_NEW_VALUE);
Stanley Tng873b5702017-05-01 21:27:31 -0700354
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800355 if (DBG) {
356 Slog.d(TAG,
357 "ACTION_SETTING_RESTORED with BLUETOOTH_ON, prevValue=" + prevValue
358 + ", newValue=" + newValue);
359 }
Stanley Tng873b5702017-05-01 21:27:31 -0700360
361 if ((newValue != null) && (prevValue != null) && !prevValue.equals(newValue)) {
362 Message msg = mHandler.obtainMessage(MESSAGE_RESTORE_USER_SETTING,
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800363 newValue.equals("0") ? RESTORE_SETTING_TO_OFF
364 : RESTORE_SETTING_TO_ON, 0);
Stanley Tng873b5702017-05-01 21:27:31 -0700365 mHandler.sendMessage(msg);
366 }
367 }
fredc0f420372012-04-12 00:02:00 -0700368 }
369 }
370 };
371
372 BluetoothManagerService(Context context) {
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700373 mHandler = new BluetoothHandler(IoThread.get().getLooper());
Zhihai Xu40874a02012-10-08 17:57:03 -0700374
fredc0f420372012-04-12 00:02:00 -0700375 mContext = context;
Svetoslav Ganovac69be52016-06-29 17:31:44 -0700376
Philip P. Moltmann6c644e62018-07-18 15:41:24 -0700377 mWirelessConsentRequired = context.getResources()
378 .getBoolean(com.android.internal.R.bool.config_wirelessConsentRequired);
Svetoslav Ganovac69be52016-06-29 17:31:44 -0700379
Marie Janssene54b4222017-03-16 18:10:59 -0700380 mCrashes = 0;
fredc0f420372012-04-12 00:02:00 -0700381 mBluetooth = null;
Marie Janssen9db28eb2016-01-12 16:05:15 -0800382 mBluetoothBinder = null;
Nitin Arorad055adb2015-03-02 15:03:51 -0800383 mBluetoothGatt = null;
fredc0f420372012-04-12 00:02:00 -0700384 mBinding = false;
385 mUnbinding = false;
Zhihai Xu40874a02012-10-08 17:57:03 -0700386 mEnable = false;
387 mState = BluetoothAdapter.STATE_OFF;
Zhihai Xu401202b2012-12-03 11:36:21 -0800388 mQuietEnableExternal = false;
389 mEnableExternal = false;
fredc0f420372012-04-12 00:02:00 -0700390 mAddress = null;
391 mName = null;
Zhihai Xudd9d17d2013-01-08 17:05:58 -0800392 mErrorRecoveryRetryCounter = 0;
fredc0f420372012-04-12 00:02:00 -0700393 mContentResolver = context.getContentResolver();
Wei Wange4a744b2015-06-11 17:50:29 -0700394 // Observe BLE scan only mode settings change.
395 registerForBleScanModeChange();
fredcd6883532012-04-25 17:46:13 -0700396 mCallbacks = new RemoteCallbackList<IBluetoothManagerCallback>();
397 mStateChangeCallbacks = new RemoteCallbackList<IBluetoothStateChangeCallback>();
Stanley Tng873b5702017-05-01 21:27:31 -0700398
Stanley Tng61dbd812019-01-13 16:04:31 -0800399 mIsHearingAidProfileSupported = context.getResources()
400 .getBoolean(com.android.internal.R.bool.config_hearing_aid_profile_supported);
401
Stanley Tngfe8c8332018-06-19 08:48:10 -0700402 // TODO: We need a more generic way to initialize the persist keys of FeatureFlagUtils
Stanley Tngfe8c8332018-06-19 08:48:10 -0700403 String value = SystemProperties.get(FeatureFlagUtils.PERSIST_PREFIX + FeatureFlagUtils.HEARING_AID_SETTINGS);
404 if (!TextUtils.isEmpty(value)) {
Stanley Tng61dbd812019-01-13 16:04:31 -0800405 boolean isHearingAidEnabled = Boolean.parseBoolean(value);
Stanley Tngfe8c8332018-06-19 08:48:10 -0700406 Log.v(TAG, "set feature flag HEARING_AID_SETTINGS to " + isHearingAidEnabled);
407 FeatureFlagUtils.setEnabled(context, FeatureFlagUtils.HEARING_AID_SETTINGS, isHearingAidEnabled);
Stanley Tng61dbd812019-01-13 16:04:31 -0800408 if (isHearingAidEnabled && !mIsHearingAidProfileSupported) {
409 // Overwrite to enable support by FeatureFlag
410 mIsHearingAidProfileSupported = true;
411 }
Stanley Tngfe8c8332018-06-19 08:48:10 -0700412 }
413
Stanley Tng873b5702017-05-01 21:27:31 -0700414 IntentFilter filter = new IntentFilter();
415 filter.addAction(BluetoothAdapter.ACTION_LOCAL_NAME_CHANGED);
416 filter.addAction(BluetoothAdapter.ACTION_BLUETOOTH_ADDRESS_CHANGED);
417 filter.addAction(Intent.ACTION_SETTING_RESTORED);
Dianne Hackbornd83a0962014-05-02 16:28:33 -0700418 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
Matthew Xie6fde3092012-07-11 17:10:07 -0700419 mContext.registerReceiver(mReceiver, filter);
Stanley Tng873b5702017-05-01 21:27:31 -0700420
fredc0f420372012-04-12 00:02:00 -0700421 loadStoredNameAndAddress();
Zhihai Xu401202b2012-12-03 11:36:21 -0800422 if (isBluetoothPersistedStateOn()) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800423 if (DBG) {
424 Slog.d(TAG, "Startup: Bluetooth persisted state is ON.");
425 }
Zhihai Xu401202b2012-12-03 11:36:21 -0800426 mEnableExternal = true;
fredc0f420372012-04-12 00:02:00 -0700427 }
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200428
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800429 String airplaneModeRadios =
430 Settings.Global.getString(mContentResolver, Settings.Global.AIRPLANE_MODE_RADIOS);
431 if (airplaneModeRadios == null || airplaneModeRadios.contains(
432 Settings.Global.RADIO_BLUETOOTH)) {
Ajay Panicker467bc042017-02-22 12:23:15 -0800433 mContentResolver.registerContentObserver(
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800434 Settings.Global.getUriFor(Settings.Global.AIRPLANE_MODE_ON), true,
435 mAirplaneModeObserver);
Ajay Panicker467bc042017-02-22 12:23:15 -0800436 }
437
Marie Janssen59804562016-12-28 14:13:21 -0800438 int systemUiUid = -1;
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200439 try {
Arthur Hsuf3f95a92018-01-11 16:46:22 -0800440 // Check if device is configured with no home screen, which implies no SystemUI.
441 boolean noHome = mContext.getResources().getBoolean(R.bool.config_noHomeScreen);
442 if (!noHome) {
443 systemUiUid = mContext.getPackageManager()
444 .getPackageUidAsUser("com.android.systemui", PackageManager.MATCH_SYSTEM_ONLY,
445 UserHandle.USER_SYSTEM);
446 }
447 Slog.d(TAG, "Detected SystemUiUid: " + Integer.toString(systemUiUid));
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200448 } catch (PackageManager.NameNotFoundException e) {
Joe LaPennaacddf2b2015-09-04 12:52:42 -0700449 // Some platforms, such as wearables do not have a system ui.
Jeff Sharkey67609c72016-03-05 14:29:13 -0700450 Slog.w(TAG, "Unable to resolve SystemUI's UID.", e);
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200451 }
Marie Janssen59804562016-12-28 14:13:21 -0800452 mSystemUiUid = systemUiUid;
fredc0f420372012-04-12 00:02:00 -0700453 }
454
fredc649fe492012-04-19 01:07:18 -0700455 /**
456 * Returns true if airplane mode is currently on
457 */
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800458 private boolean isAirplaneModeOn() {
Christopher Tatec09cdce2012-09-10 16:50:14 -0700459 return Settings.Global.getInt(mContext.getContentResolver(),
460 Settings.Global.AIRPLANE_MODE_ON, 0) == 1;
fredc649fe492012-04-19 01:07:18 -0700461 }
462
Arthur Hsu2433baf2018-01-11 11:05:11 -0800463 private boolean supportBluetoothPersistedState() {
464 return mContext.getResources().getBoolean(R.bool.config_supportBluetoothPersistedState);
465 }
466
fredc649fe492012-04-19 01:07:18 -0700467 /**
468 * Returns true if the Bluetooth saved state is "on"
469 */
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800470 private boolean isBluetoothPersistedStateOn() {
Arthur Hsu2433baf2018-01-11 11:05:11 -0800471 if (!supportBluetoothPersistedState()) {
472 return false;
473 }
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800474 int state = Settings.Global.getInt(mContentResolver, Settings.Global.BLUETOOTH_ON, -1);
475 if (DBG) {
476 Slog.d(TAG, "Bluetooth persisted state: " + state);
477 }
Marie Janssen9fa24912016-10-18 10:04:24 -0700478 return state != BLUETOOTH_OFF;
Zhihai Xu401202b2012-12-03 11:36:21 -0800479 }
480
481 /**
482 * Returns true if the Bluetooth saved state is BLUETOOTH_ON_BLUETOOTH
483 */
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800484 private boolean isBluetoothPersistedStateOnBluetooth() {
Arthur Hsu2433baf2018-01-11 11:05:11 -0800485 if (!supportBluetoothPersistedState()) {
486 return false;
487 }
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800488 return Settings.Global.getInt(mContentResolver, Settings.Global.BLUETOOTH_ON,
489 BLUETOOTH_ON_BLUETOOTH) == BLUETOOTH_ON_BLUETOOTH;
fredc649fe492012-04-19 01:07:18 -0700490 }
491
492 /**
493 * Save the Bluetooth on/off state
fredc649fe492012-04-19 01:07:18 -0700494 */
Zhihai Xu401202b2012-12-03 11:36:21 -0800495 private void persistBluetoothSetting(int value) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800496 if (DBG) {
497 Slog.d(TAG, "Persisting Bluetooth Setting: " + value);
498 }
Marie Janssenfa630682016-12-15 13:51:30 -0800499 // waive WRITE_SECURE_SETTINGS permission check
500 long callingIdentity = Binder.clearCallingIdentity();
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800501 Settings.Global.putInt(mContext.getContentResolver(), Settings.Global.BLUETOOTH_ON, value);
Marie Janssenfa630682016-12-15 13:51:30 -0800502 Binder.restoreCallingIdentity(callingIdentity);
fredc649fe492012-04-19 01:07:18 -0700503 }
504
505 /**
506 * Returns true if the Bluetooth Adapter's name and address is
507 * locally cached
508 * @return
509 */
fredc0f420372012-04-12 00:02:00 -0700510 private boolean isNameAndAddressSet() {
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800511 return mName != null && mAddress != null && mName.length() > 0 && mAddress.length() > 0;
fredc0f420372012-04-12 00:02:00 -0700512 }
513
fredc649fe492012-04-19 01:07:18 -0700514 /**
515 * Retrieve the Bluetooth Adapter's name and address and save it in
516 * in the local cache
517 */
fredc0f420372012-04-12 00:02:00 -0700518 private void loadStoredNameAndAddress() {
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800519 if (DBG) {
520 Slog.d(TAG, "Loading stored name and address");
521 }
522 if (mContext.getResources()
523 .getBoolean(com.android.internal.R.bool.config_bluetooth_address_validation)
524 && Settings.Secure.getInt(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDR_VALID, 0)
525 == 0) {
Zhihai Xud31c3222012-10-31 16:08:57 -0700526 // if the valid flag is not set, don't load the address and name
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800527 if (DBG) {
528 Slog.d(TAG, "invalid bluetooth name and address stored");
529 }
Zhihai Xud31c3222012-10-31 16:08:57 -0700530 return;
531 }
fredc0f420372012-04-12 00:02:00 -0700532 mName = Settings.Secure.getString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_NAME);
533 mAddress = Settings.Secure.getString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDRESS);
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800534 if (DBG) {
535 Slog.d(TAG, "Stored bluetooth Name=" + mName + ",Address=" + mAddress);
536 }
fredc0f420372012-04-12 00:02:00 -0700537 }
538
fredc649fe492012-04-19 01:07:18 -0700539 /**
540 * Save the Bluetooth name and address in the persistent store.
541 * Only non-null values will be saved.
542 * @param name
543 * @param address
544 */
fredc0f420372012-04-12 00:02:00 -0700545 private void storeNameAndAddress(String name, String address) {
546 if (name != null) {
547 Settings.Secure.putString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_NAME, name);
fredc0f420372012-04-12 00:02:00 -0700548 mName = name;
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800549 if (DBG) {
550 Slog.d(TAG, "Stored Bluetooth name: " + Settings.Secure.getString(mContentResolver,
551 SECURE_SETTINGS_BLUETOOTH_NAME));
552 }
fredc0f420372012-04-12 00:02:00 -0700553 }
554
555 if (address != null) {
556 Settings.Secure.putString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDRESS, address);
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800557 mAddress = address;
558 if (DBG) {
559 Slog.d(TAG,
560 "Stored Bluetoothaddress: " + Settings.Secure.getString(mContentResolver,
561 SECURE_SETTINGS_BLUETOOTH_ADDRESS));
562 }
fredc0f420372012-04-12 00:02:00 -0700563 }
Zhihai Xud31c3222012-10-31 16:08:57 -0700564
565 if ((name != null) && (address != null)) {
566 Settings.Secure.putInt(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDR_VALID, 1);
567 }
fredc0f420372012-04-12 00:02:00 -0700568 }
569
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800570 public IBluetooth registerAdapter(IBluetoothManagerCallback callback) {
Natalie Silvanovich55db6462014-05-01 16:12:23 -0700571 if (callback == null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700572 Slog.w(TAG, "Callback is null in registerAdapter");
Natalie Silvanovich55db6462014-05-01 16:12:23 -0700573 return null;
574 }
fredc0f420372012-04-12 00:02:00 -0700575 Message msg = mHandler.obtainMessage(MESSAGE_REGISTER_ADAPTER);
576 msg.obj = callback;
577 mHandler.sendMessage(msg);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700578
579 return mBluetooth;
fredc0f420372012-04-12 00:02:00 -0700580 }
581
582 public void unregisterAdapter(IBluetoothManagerCallback callback) {
Natalie Silvanovich55db6462014-05-01 16:12:23 -0700583 if (callback == null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700584 Slog.w(TAG, "Callback is null in unregisterAdapter");
Natalie Silvanovich55db6462014-05-01 16:12:23 -0700585 return;
586 }
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800587 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");
fredc0f420372012-04-12 00:02:00 -0700588 Message msg = mHandler.obtainMessage(MESSAGE_UNREGISTER_ADAPTER);
589 msg.obj = callback;
590 mHandler.sendMessage(msg);
591 }
592
593 public void registerStateChangeCallback(IBluetoothStateChangeCallback callback) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800594 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");
Marie Janssencb21ad72016-12-13 10:51:02 -0800595 if (callback == null) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800596 Slog.w(TAG, "registerStateChangeCallback: Callback is null!");
597 return;
Marie Janssencb21ad72016-12-13 10:51:02 -0800598 }
fredc0f420372012-04-12 00:02:00 -0700599 Message msg = mHandler.obtainMessage(MESSAGE_REGISTER_STATE_CHANGE_CALLBACK);
600 msg.obj = callback;
601 mHandler.sendMessage(msg);
602 }
603
604 public void unregisterStateChangeCallback(IBluetoothStateChangeCallback callback) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800605 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");
Marie Janssencb21ad72016-12-13 10:51:02 -0800606 if (callback == null) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800607 Slog.w(TAG, "unregisterStateChangeCallback: Callback is null!");
608 return;
Marie Janssencb21ad72016-12-13 10:51:02 -0800609 }
fredc0f420372012-04-12 00:02:00 -0700610 Message msg = mHandler.obtainMessage(MESSAGE_UNREGISTER_STATE_CHANGE_CALLBACK);
611 msg.obj = callback;
612 mHandler.sendMessage(msg);
613 }
614
615 public boolean isEnabled() {
Zach Johnson76236d72019-11-26 21:30:07 -0800616 return getState() == BluetoothAdapter.STATE_ON;
fredc0f420372012-04-12 00:02:00 -0700617 }
618
Christine Hallstrom995c90a2016-05-25 15:49:08 -0700619 public int getState() {
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800620 if ((Binder.getCallingUid() != Process.SYSTEM_UID) && (!checkIfCallerIsForegroundUser())) {
Marie Janssencb21ad72016-12-13 10:51:02 -0800621 Slog.w(TAG, "getState(): report OFF for non-active and non system user");
Christine Hallstrom995c90a2016-05-25 15:49:08 -0700622 return BluetoothAdapter.STATE_OFF;
623 }
624
625 try {
626 mBluetoothLock.readLock().lock();
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800627 if (mBluetooth != null) {
628 return mBluetooth.getState();
629 }
Christine Hallstrom995c90a2016-05-25 15:49:08 -0700630 } catch (RemoteException e) {
631 Slog.e(TAG, "getState()", e);
632 } finally {
633 mBluetoothLock.readLock().unlock();
634 }
635 return BluetoothAdapter.STATE_OFF;
636 }
637
Nitin Arorad055adb2015-03-02 15:03:51 -0800638 class ClientDeathRecipient implements IBinder.DeathRecipient {
Marie Janssen59804562016-12-28 14:13:21 -0800639 private String mPackageName;
640
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800641 ClientDeathRecipient(String packageName) {
Marie Janssen59804562016-12-28 14:13:21 -0800642 mPackageName = packageName;
643 }
644
Nitin Arorad055adb2015-03-02 15:03:51 -0800645 public void binderDied() {
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800646 if (DBG) {
647 Slog.d(TAG, "Binder is dead - unregister " + mPackageName);
Marie Janssen2977c3e2016-11-09 12:01:24 -0800648 }
Stanley Tng2c5fd282018-03-19 13:06:45 -0700649
650 for (Map.Entry<IBinder, ClientDeathRecipient> entry : mBleApps.entrySet()) {
651 IBinder token = entry.getKey();
652 ClientDeathRecipient deathRec = entry.getValue();
653 if (deathRec.equals(this)) {
Stanley Tng600109c2018-03-20 16:54:27 -0700654 updateBleAppCount(token, false, mPackageName);
Stanley Tng2c5fd282018-03-19 13:06:45 -0700655 break;
656 }
657 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800658 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800659
Marie Janssen59804562016-12-28 14:13:21 -0800660 public String getPackageName() {
661 return mPackageName;
662 }
663 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800664
Wei Wang67d84162015-04-26 17:04:29 -0700665 @Override
666 public boolean isBleScanAlwaysAvailable() {
Marie Janssena80d7452016-10-25 10:47:51 -0700667 if (isAirplaneModeOn() && !mEnable) {
668 return false;
669 }
Wei Wang67d84162015-04-26 17:04:29 -0700670 try {
Jack He8caab152018-03-02 13:08:36 -0800671 return Settings.Global.getInt(mContentResolver,
672 Settings.Global.BLE_SCAN_ALWAYS_AVAILABLE) != 0;
Wei Wang67d84162015-04-26 17:04:29 -0700673 } catch (SettingNotFoundException e) {
674 }
675 return false;
676 }
677
Stanley Tng61dbd812019-01-13 16:04:31 -0800678 @Override
679 public boolean isHearingAidProfileSupported() {
680 return mIsHearingAidProfileSupported;
681 }
682
Wei Wange4a744b2015-06-11 17:50:29 -0700683 // Monitor change of BLE scan only mode settings.
684 private void registerForBleScanModeChange() {
685 ContentObserver contentObserver = new ContentObserver(null) {
686 @Override
687 public void onChange(boolean selfChange) {
Marie Janssen2977c3e2016-11-09 12:01:24 -0800688 if (isBleScanAlwaysAvailable()) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800689 // Nothing to do
690 return;
Marie Janssen2977c3e2016-11-09 12:01:24 -0800691 }
692 // BLE scan is not available.
693 disableBleScanMode();
694 clearBleApps();
695 try {
696 mBluetoothLock.readLock().lock();
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800697 if (mBluetooth != null) {
Hansong Zhang276eb1b2018-04-23 11:17:17 -0700698 addActiveLog(BluetoothProtoEnums.ENABLE_DISABLE_REASON_APPLICATION_REQUEST,
699 mContext.getPackageName(), false);
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800700 mBluetooth.onBrEdrDown();
701 }
Marie Janssen2977c3e2016-11-09 12:01:24 -0800702 } catch (RemoteException e) {
703 Slog.e(TAG, "error when disabling bluetooth", e);
704 } finally {
705 mBluetoothLock.readLock().unlock();
Wei Wange4a744b2015-06-11 17:50:29 -0700706 }
707 }
708 };
709
710 mContentResolver.registerContentObserver(
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800711 Settings.Global.getUriFor(Settings.Global.BLE_SCAN_ALWAYS_AVAILABLE), false,
712 contentObserver);
Wei Wange4a744b2015-06-11 17:50:29 -0700713 }
714
715 // Disable ble scan only mode.
716 private void disableBleScanMode() {
717 try {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700718 mBluetoothLock.writeLock().lock();
Wei Wange4a744b2015-06-11 17:50:29 -0700719 if (mBluetooth != null && (mBluetooth.getState() != BluetoothAdapter.STATE_ON)) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800720 if (DBG) {
721 Slog.d(TAG, "Reseting the mEnable flag for clean disable");
722 }
Wei Wange4a744b2015-06-11 17:50:29 -0700723 mEnable = false;
724 }
725 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700726 Slog.e(TAG, "getState()", e);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700727 } finally {
728 mBluetoothLock.writeLock().unlock();
Wei Wange4a744b2015-06-11 17:50:29 -0700729 }
730 }
731
Marie Janssen59804562016-12-28 14:13:21 -0800732 public int updateBleAppCount(IBinder token, boolean enable, String packageName) {
Jack Hea80cead2019-04-23 20:00:18 -0700733 // Check if packageName belongs to callingUid
734 final int callingUid = Binder.getCallingUid();
735 final boolean isCallerSystem = UserHandle.getAppId(callingUid) == Process.SYSTEM_UID;
736 if (!isCallerSystem) {
737 checkPackage(callingUid, packageName);
738 }
Marie Janssen59804562016-12-28 14:13:21 -0800739 ClientDeathRecipient r = mBleApps.get(token);
740 if (r == null && enable) {
741 ClientDeathRecipient deathRec = new ClientDeathRecipient(packageName);
742 try {
743 token.linkToDeath(deathRec, 0);
744 } catch (RemoteException ex) {
745 throw new IllegalArgumentException("BLE app (" + packageName + ") already dead!");
Nitin Arorad055adb2015-03-02 15:03:51 -0800746 }
Marie Janssen59804562016-12-28 14:13:21 -0800747 mBleApps.put(token, deathRec);
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800748 if (DBG) {
749 Slog.d(TAG, "Registered for death of " + packageName);
750 }
Marie Janssen59804562016-12-28 14:13:21 -0800751 } else if (!enable && r != null) {
752 // Unregister death recipient as the app goes away.
753 token.unlinkToDeath(r, 0);
754 mBleApps.remove(token);
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800755 if (DBG) {
756 Slog.d(TAG, "Unregistered for death of " + packageName);
757 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800758 }
Marie Janssen2977c3e2016-11-09 12:01:24 -0800759 int appCount = mBleApps.size();
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800760 if (DBG) {
761 Slog.d(TAG, appCount + " registered Ble Apps");
762 }
Marie Janssen2977c3e2016-11-09 12:01:24 -0800763 if (appCount == 0 && mEnable) {
Wei Wange4a744b2015-06-11 17:50:29 -0700764 disableBleScanMode();
Nitin Arorad055adb2015-03-02 15:03:51 -0800765 }
Martin Brabhamc2b06222017-02-27 16:55:07 -0800766 if (appCount == 0 && !mEnableExternal) {
767 sendBrEdrDownCallback();
768 }
Marie Janssen2977c3e2016-11-09 12:01:24 -0800769 return appCount;
Nitin Arorad055adb2015-03-02 15:03:51 -0800770 }
771
Wei Wange4a744b2015-06-11 17:50:29 -0700772 // Clear all apps using BLE scan only mode.
773 private void clearBleApps() {
Marie Janssen2977c3e2016-11-09 12:01:24 -0800774 mBleApps.clear();
Wei Wange4a744b2015-06-11 17:50:29 -0700775 }
776
Marie Janssen59804562016-12-28 14:13:21 -0800777 /** @hide */
Nitin Arorad055adb2015-03-02 15:03:51 -0800778 public boolean isBleAppPresent() {
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800779 if (DBG) {
780 Slog.d(TAG, "isBleAppPresent() count: " + mBleApps.size());
781 }
Marie Janssen2977c3e2016-11-09 12:01:24 -0800782 return mBleApps.size() > 0;
Nitin Arorad055adb2015-03-02 15:03:51 -0800783 }
784
785 /**
Myles Watson304ebf22018-05-11 08:47:24 -0700786 * Call IBluetooth.onLeServiceUp() to continue if Bluetooth should be on.
Nitin Arorad055adb2015-03-02 15:03:51 -0800787 */
Myles Watson304ebf22018-05-11 08:47:24 -0700788 private void continueFromBleOnState() {
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800789 if (DBG) {
Myles Watson304ebf22018-05-11 08:47:24 -0700790 Slog.d(TAG, "continueFromBleOnState()");
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800791 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700792 try {
793 mBluetoothLock.readLock().lock();
Marie Janssenfa630682016-12-15 13:51:30 -0800794 if (mBluetooth == null) {
Myles Watson304ebf22018-05-11 08:47:24 -0700795 Slog.e(TAG, "onBluetoothServiceUp: mBluetooth is null!");
Marie Janssenfa630682016-12-15 13:51:30 -0800796 return;
797 }
798 if (isBluetoothPersistedStateOnBluetooth() || !isBleAppPresent()) {
799 // This triggers transition to STATE_ON
Nitin Arorad055adb2015-03-02 15:03:51 -0800800 mBluetooth.onLeServiceUp();
Nitin Arorad055adb2015-03-02 15:03:51 -0800801 persistBluetoothSetting(BLUETOOTH_ON_BLUETOOTH);
Nitin Arorad055adb2015-03-02 15:03:51 -0800802 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700803 } catch (RemoteException e) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800804 Slog.e(TAG, "Unable to call onServiceUp", e);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700805 } finally {
806 mBluetoothLock.readLock().unlock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800807 }
808 }
809
810 /**
811 * Inform BluetoothAdapter instances that BREDR part is down
812 * and turn off all service and stack if no LE app needs it
813 */
814 private void sendBrEdrDownCallback() {
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800815 if (DBG) {
816 Slog.d(TAG, "Calling sendBrEdrDownCallback callbacks");
817 }
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700818
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700819 if (mBluetooth == null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700820 Slog.w(TAG, "Bluetooth handle is null");
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700821 return;
822 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800823
Martin Brabhamc2b06222017-02-27 16:55:07 -0800824 if (isBleAppPresent()) {
825 // Need to stay at BLE ON. Disconnect all Gatt connections
826 try {
827 mBluetoothGatt.unregAll();
828 } catch (RemoteException e) {
829 Slog.e(TAG, "Unable to disconnect all apps.", e);
830 }
831 } else {
Nitin Arorad055adb2015-03-02 15:03:51 -0800832 try {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700833 mBluetoothLock.readLock().lock();
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800834 if (mBluetooth != null) {
835 mBluetooth.onBrEdrDown();
836 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700837 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700838 Slog.e(TAG, "Call to onBrEdrDown() failed.", e);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700839 } finally {
840 mBluetoothLock.readLock().unlock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800841 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800842 }
Martin Brabhamc2b06222017-02-27 16:55:07 -0800843
Nitin Arorad055adb2015-03-02 15:03:51 -0800844 }
845
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800846 public boolean enableNoAutoConnect(String packageName) {
Lenka Trochtova63d5e4a72016-12-02 12:19:39 +0100847 if (isBluetoothDisallowed()) {
848 if (DBG) {
849 Slog.d(TAG, "enableNoAutoConnect(): not enabling - bluetooth disallowed");
850 }
851 return false;
852 }
853
Jack Hea80cead2019-04-23 20:00:18 -0700854 // Check if packageName belongs to callingUid
855 final int callingUid = Binder.getCallingUid();
856 final boolean isCallerSystem = UserHandle.getAppId(callingUid) == Process.SYSTEM_UID;
857 if (!isCallerSystem) {
858 checkPackage(callingUid, packageName);
859 }
860
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700861 mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800862 "Need BLUETOOTH ADMIN permission");
Zhihai Xu40874a02012-10-08 17:57:03 -0700863
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700864 if (DBG) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800865 Slog.d(TAG, "enableNoAutoConnect(): mBluetooth =" + mBluetooth + " mBinding = "
866 + mBinding);
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700867 }
Jack Hea80cead2019-04-23 20:00:18 -0700868 int callingAppId = UserHandle.getAppId(callingUid);
Martijn Coenen8385c5a2012-11-29 10:14:16 -0800869
870 if (callingAppId != Process.NFC_UID) {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700871 throw new SecurityException("no permission to enable Bluetooth quietly");
872 }
Martijn Coenen8385c5a2012-11-29 10:14:16 -0800873
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800874 synchronized (mReceiver) {
Zhihai Xu401202b2012-12-03 11:36:21 -0800875 mQuietEnableExternal = true;
876 mEnableExternal = true;
Jack He8caab152018-03-02 13:08:36 -0800877 sendEnableMsg(true,
878 BluetoothProtoEnums.ENABLE_DISABLE_REASON_APPLICATION_REQUEST, packageName);
Zhihai Xu401202b2012-12-03 11:36:21 -0800879 }
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700880 return true;
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700881 }
Ajay Panicker4bb48302016-03-31 14:14:27 -0700882
Svetoslav Ganovac69be52016-06-29 17:31:44 -0700883 public boolean enable(String packageName) throws RemoteException {
884 final int callingUid = Binder.getCallingUid();
885 final boolean callerSystem = UserHandle.getAppId(callingUid) == Process.SYSTEM_UID;
886
Lenka Trochtova63d5e4a72016-12-02 12:19:39 +0100887 if (isBluetoothDisallowed()) {
888 if (DBG) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800889 Slog.d(TAG, "enable(): not enabling - bluetooth disallowed");
Lenka Trochtova63d5e4a72016-12-02 12:19:39 +0100890 }
891 return false;
892 }
893
Svetoslav Ganovac69be52016-06-29 17:31:44 -0700894 if (!callerSystem) {
Jack Hea80cead2019-04-23 20:00:18 -0700895 // Check if packageName belongs to callingUid
896 checkPackage(callingUid, packageName);
897
Svetoslav Ganovac69be52016-06-29 17:31:44 -0700898 if (!checkIfCallerIsForegroundUser()) {
899 Slog.w(TAG, "enable(): not allowed for non-active and non system user");
900 return false;
901 }
902
903 mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
904 "Need BLUETOOTH ADMIN permission");
905
Philip P. Moltmann6c644e62018-07-18 15:41:24 -0700906 if (!isEnabled() && mWirelessConsentRequired && startConsentUiIfNeeded(packageName,
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800907 callingUid, BluetoothAdapter.ACTION_REQUEST_ENABLE)) {
Svetoslav Ganovac69be52016-06-29 17:31:44 -0700908 return false;
909 }
fredcf2458862012-04-16 15:18:27 -0700910 }
911
Zhihai Xu401202b2012-12-03 11:36:21 -0800912 if (DBG) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800913 Slog.d(TAG, "enable(" + packageName + "): mBluetooth =" + mBluetooth + " mBinding = "
914 + mBinding + " mState = " + BluetoothAdapter.nameForState(mState));
Sanket Agarwal090bf552016-04-21 14:10:55 -0700915 }
Zhihai Xu401202b2012-12-03 11:36:21 -0800916
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800917 synchronized (mReceiver) {
Zhihai Xu401202b2012-12-03 11:36:21 -0800918 mQuietEnableExternal = false;
919 mEnableExternal = true;
920 // waive WRITE_SECURE_SETTINGS permission check
Jack He8caab152018-03-02 13:08:36 -0800921 sendEnableMsg(false,
922 BluetoothProtoEnums.ENABLE_DISABLE_REASON_APPLICATION_REQUEST, packageName);
Zhihai Xu401202b2012-12-03 11:36:21 -0800923 }
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800924 if (DBG) {
925 Slog.d(TAG, "enable returning");
926 }
Zhihai Xu401202b2012-12-03 11:36:21 -0800927 return true;
fredc0f420372012-04-12 00:02:00 -0700928 }
929
Svetoslav Ganovac69be52016-06-29 17:31:44 -0700930 public boolean disable(String packageName, boolean persist) throws RemoteException {
931 final int callingUid = Binder.getCallingUid();
932 final boolean callerSystem = UserHandle.getAppId(callingUid) == Process.SYSTEM_UID;
Zhihai Xu40874a02012-10-08 17:57:03 -0700933
Svetoslav Ganovac69be52016-06-29 17:31:44 -0700934 if (!callerSystem) {
Jack Hea80cead2019-04-23 20:00:18 -0700935 // Check if packageName belongs to callingUid
936 checkPackage(callingUid, packageName);
937
Svetoslav Ganovac69be52016-06-29 17:31:44 -0700938 if (!checkIfCallerIsForegroundUser()) {
939 Slog.w(TAG, "disable(): not allowed for non-active and non system user");
940 return false;
941 }
942
943 mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
944 "Need BLUETOOTH ADMIN permission");
945
Philip P. Moltmann6c644e62018-07-18 15:41:24 -0700946 if (isEnabled() && mWirelessConsentRequired && startConsentUiIfNeeded(packageName,
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800947 callingUid, BluetoothAdapter.ACTION_REQUEST_DISABLE)) {
Svetoslav Ganovac69be52016-06-29 17:31:44 -0700948 return false;
949 }
Zhihai Xu40874a02012-10-08 17:57:03 -0700950 }
951
fredcf2458862012-04-16 15:18:27 -0700952 if (DBG) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800953 Slog.d(TAG, "disable(): mBluetooth = " + mBluetooth + " mBinding = " + mBinding);
Matthew Xiecdce0b92012-07-12 19:06:15 -0700954 }
fredcf2458862012-04-16 15:18:27 -0700955
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800956 synchronized (mReceiver) {
Zhihai Xu401202b2012-12-03 11:36:21 -0800957 if (persist) {
Zhihai Xu401202b2012-12-03 11:36:21 -0800958 persistBluetoothSetting(BLUETOOTH_OFF);
Zhihai Xu401202b2012-12-03 11:36:21 -0800959 }
960 mEnableExternal = false;
Jack He8caab152018-03-02 13:08:36 -0800961 sendDisableMsg(BluetoothProtoEnums.ENABLE_DISABLE_REASON_APPLICATION_REQUEST,
962 packageName);
Zhihai Xu401202b2012-12-03 11:36:21 -0800963 }
fredc0f420372012-04-12 00:02:00 -0700964 return true;
965 }
966
baishengf62d8692018-01-25 18:07:24 +0800967 private boolean startConsentUiIfNeeded(String packageName,
968 int callingUid, String intentAction) throws RemoteException {
Philip P. Moltmann6c644e62018-07-18 15:41:24 -0700969 if (checkBluetoothPermissionWhenWirelessConsentRequired()) {
baishengf62d8692018-01-25 18:07:24 +0800970 return false;
971 }
Svetoslav Ganovac69be52016-06-29 17:31:44 -0700972 try {
973 // Validate the package only if we are going to use it
974 ApplicationInfo applicationInfo = mContext.getPackageManager()
975 .getApplicationInfoAsUser(packageName,
976 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
977 UserHandle.getUserId(callingUid));
978 if (applicationInfo.uid != callingUid) {
baishengf62d8692018-01-25 18:07:24 +0800979 throw new SecurityException("Package " + packageName
980 + " not in uid " + callingUid);
Svetoslav Ganovac69be52016-06-29 17:31:44 -0700981 }
982
Ivan Podogovd2d32b12016-12-05 16:46:52 +0000983 Intent intent = new Intent(intentAction);
Ivan Podogov1ab87252017-01-03 12:02:18 +0000984 intent.putExtra(Intent.EXTRA_PACKAGE_NAME, packageName);
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800985 intent.setFlags(
986 Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
Ivan Podogov1ab87252017-01-03 12:02:18 +0000987 try {
988 mContext.startActivity(intent);
989 } catch (ActivityNotFoundException e) {
990 // Shouldn't happen
991 Slog.e(TAG, "Intent to handle action " + intentAction + " missing");
992 return false;
Svetoslav Ganovac69be52016-06-29 17:31:44 -0700993 }
Ivan Podogov1ab87252017-01-03 12:02:18 +0000994 return true;
Svetoslav Ganovac69be52016-06-29 17:31:44 -0700995 } catch (PackageManager.NameNotFoundException e) {
996 throw new RemoteException(e.getMessage());
997 }
Svetoslav Ganovac69be52016-06-29 17:31:44 -0700998 }
999
baishengf62d8692018-01-25 18:07:24 +08001000 /**
Jack Hea80cead2019-04-23 20:00:18 -07001001 * Check if AppOpsManager is available and the packageName belongs to uid
1002 *
1003 * A null package belongs to any uid
1004 */
1005 private void checkPackage(int uid, String packageName) {
1006 if (mAppOps == null) {
1007 Slog.w(TAG, "checkPackage(): called before system boot up, uid "
1008 + uid + ", packageName " + packageName);
1009 throw new IllegalStateException("System has not boot yet");
1010 }
1011 if (packageName == null) {
1012 Slog.w(TAG, "checkPackage(): called with null packageName from " + uid);
1013 return;
1014 }
1015 try {
1016 mAppOps.checkPackage(uid, packageName);
1017 } catch (SecurityException e) {
1018 Slog.w(TAG, "checkPackage(): " + packageName + " does not belong to uid " + uid);
Jack Hea80cead2019-04-23 20:00:18 -07001019 throw new SecurityException(e.getMessage());
1020 }
1021 }
1022
1023 /**
baishengf62d8692018-01-25 18:07:24 +08001024 * Check if the caller must still pass permission check or if the caller is exempted
Philip P. Moltmann6c644e62018-07-18 15:41:24 -07001025 * from the consent UI via the MANAGE_BLUETOOTH_WHEN_WIRELESS_CONSENT_REQUIRED check.
baishengf62d8692018-01-25 18:07:24 +08001026 *
1027 * Commands from some callers may be exempted from triggering the consent UI when
1028 * enabling bluetooth. This exemption is checked via the
Philip P. Moltmann6c644e62018-07-18 15:41:24 -07001029 * MANAGE_BLUETOOTH_WHEN_WIRELESS_CONSENT_REQUIRED and allows calls to skip
baishengf62d8692018-01-25 18:07:24 +08001030 * the consent UI where it may otherwise be required.
1031 *
1032 * @hide
1033 */
Philip P. Moltmann6c644e62018-07-18 15:41:24 -07001034 private boolean checkBluetoothPermissionWhenWirelessConsentRequired() {
baishengf62d8692018-01-25 18:07:24 +08001035 int result = mContext.checkCallingPermission(
Philip P. Moltmann6c644e62018-07-18 15:41:24 -07001036 android.Manifest.permission.MANAGE_BLUETOOTH_WHEN_WIRELESS_CONSENT_REQUIRED);
baishengf62d8692018-01-25 18:07:24 +08001037 return result == PackageManager.PERMISSION_GRANTED;
1038 }
1039
fredc649fe492012-04-19 01:07:18 -07001040 public void unbindAndFinish() {
fredcf2458862012-04-16 15:18:27 -07001041 if (DBG) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001042 Slog.d(TAG, "unbindAndFinish(): " + mBluetooth + " mBinding = " + mBinding
1043 + " mUnbinding = " + mUnbinding);
fredcf2458862012-04-16 15:18:27 -07001044 }
1045
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001046 try {
1047 mBluetoothLock.writeLock().lock();
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001048 if (mUnbinding) {
1049 return;
1050 }
fredc0f420372012-04-12 00:02:00 -07001051 mUnbinding = true;
Pavlin Radoslavove47ec142016-06-01 22:25:18 -07001052 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
Pavlin Radoslavov74f60c02016-09-21 17:28:11 -07001053 mHandler.removeMessages(MESSAGE_BIND_PROFILE_SERVICE);
Zhihai Xu40874a02012-10-08 17:57:03 -07001054 if (mBluetooth != null) {
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001055 //Unregister callback object
1056 try {
1057 mBluetooth.unregisterCallback(mBluetoothCallback);
1058 } catch (RemoteException re) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001059 Slog.e(TAG, "Unable to unregister BluetoothCallback", re);
fredcbf072a72012-05-09 16:52:50 -07001060 }
Marie Janssen9db28eb2016-01-12 16:05:15 -08001061 mBluetoothBinder = null;
fredcd6883532012-04-25 17:46:13 -07001062 mBluetooth = null;
fredc0f420372012-04-12 00:02:00 -07001063 mContext.unbindService(mConnection);
fredcd6883532012-04-25 17:46:13 -07001064 mUnbinding = false;
Zhihai Xu40874a02012-10-08 17:57:03 -07001065 mBinding = false;
fredcf2458862012-04-16 15:18:27 -07001066 } else {
Marie Janssencb21ad72016-12-13 10:51:02 -08001067 mUnbinding = false;
fredc0f420372012-04-12 00:02:00 -07001068 }
Nitin Arorad055adb2015-03-02 15:03:51 -08001069 mBluetoothGatt = null;
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001070 } finally {
1071 mBluetoothLock.writeLock().unlock();
fredc0f420372012-04-12 00:02:00 -07001072 }
1073 }
1074
Matthew Xieddf7e472013-03-01 18:41:02 -08001075 public IBluetoothGatt getBluetoothGatt() {
1076 // sync protection
1077 return mBluetoothGatt;
1078 }
1079
Benjamin Franze8b98922014-11-12 15:57:54 +00001080 @Override
1081 public boolean bindBluetoothProfileService(int bluetoothProfile,
1082 IBluetoothProfileServiceConnection proxy) {
1083 if (!mEnable) {
1084 if (DBG) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001085 Slog.d(TAG, "Trying to bind to profile: " + bluetoothProfile
1086 + ", while Bluetooth was disabled");
Benjamin Franze8b98922014-11-12 15:57:54 +00001087 }
1088 return false;
1089 }
1090 synchronized (mProfileServices) {
1091 ProfileServiceConnections psc = mProfileServices.get(new Integer(bluetoothProfile));
1092 if (psc == null) {
1093 if (DBG) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001094 Slog.d(TAG, "Creating new ProfileServiceConnections object for" + " profile: "
1095 + bluetoothProfile);
Benjamin Franze8b98922014-11-12 15:57:54 +00001096 }
Benjamin Franz5b614592014-12-09 18:58:45 +00001097
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001098 if (bluetoothProfile != BluetoothProfile.HEADSET) {
1099 return false;
1100 }
Benjamin Franz5b614592014-12-09 18:58:45 +00001101
1102 Intent intent = new Intent(IBluetoothHeadset.class.getName());
Benjamin Franze8b98922014-11-12 15:57:54 +00001103 psc = new ProfileServiceConnections(intent);
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001104 if (!psc.bindService()) {
1105 return false;
1106 }
Benjamin Franz5b614592014-12-09 18:58:45 +00001107
Benjamin Franze8b98922014-11-12 15:57:54 +00001108 mProfileServices.put(new Integer(bluetoothProfile), psc);
Benjamin Franze8b98922014-11-12 15:57:54 +00001109 }
1110 }
1111
1112 // Introducing a delay to give the client app time to prepare
1113 Message addProxyMsg = mHandler.obtainMessage(MESSAGE_ADD_PROXY_DELAYED);
1114 addProxyMsg.arg1 = bluetoothProfile;
1115 addProxyMsg.obj = proxy;
1116 mHandler.sendMessageDelayed(addProxyMsg, ADD_PROXY_DELAY_MS);
1117 return true;
1118 }
1119
1120 @Override
1121 public void unbindBluetoothProfileService(int bluetoothProfile,
1122 IBluetoothProfileServiceConnection proxy) {
1123 synchronized (mProfileServices) {
Ugo Yu6d9cfce2019-03-26 21:38:08 +08001124 Integer profile = new Integer(bluetoothProfile);
1125 ProfileServiceConnections psc = mProfileServices.get(profile);
Benjamin Franze8b98922014-11-12 15:57:54 +00001126 if (psc == null) {
1127 return;
1128 }
1129 psc.removeProxy(proxy);
Ugo Yu6d9cfce2019-03-26 21:38:08 +08001130 if (psc.isEmpty()) {
1131 // All prxoies are disconnected, unbind with the service.
1132 try {
1133 mContext.unbindService(psc);
1134 } catch (IllegalArgumentException e) {
1135 Slog.e(TAG, "Unable to unbind service with intent: " + psc.mIntent, e);
1136 }
1137 mProfileServices.remove(profile);
1138 }
Benjamin Franze8b98922014-11-12 15:57:54 +00001139 }
1140 }
1141
1142 private void unbindAllBluetoothProfileServices() {
1143 synchronized (mProfileServices) {
1144 for (Integer i : mProfileServices.keySet()) {
1145 ProfileServiceConnections psc = mProfileServices.get(i);
Benjamin Franz5b614592014-12-09 18:58:45 +00001146 try {
1147 mContext.unbindService(psc);
1148 } catch (IllegalArgumentException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001149 Slog.e(TAG, "Unable to unbind service with intent: " + psc.mIntent, e);
Benjamin Franz5b614592014-12-09 18:58:45 +00001150 }
Benjamin Franze8b98922014-11-12 15:57:54 +00001151 psc.removeAllProxies();
1152 }
1153 mProfileServices.clear();
1154 }
1155 }
1156
1157 /**
Miao Chou658bf2f2015-06-26 17:14:35 -07001158 * Send enable message and set adapter name and address. Called when the boot phase becomes
1159 * PHASE_SYSTEM_SERVICES_READY.
1160 */
1161 public void handleOnBootPhase() {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001162 if (DBG) {
1163 Slog.d(TAG, "Bluetooth boot completed");
1164 }
Jack Hea80cead2019-04-23 20:00:18 -07001165 mAppOps = mContext.getSystemService(AppOpsManager.class);
Lenka Trochtova63d5e4a72016-12-02 12:19:39 +01001166 UserManagerInternal userManagerInternal =
1167 LocalServices.getService(UserManagerInternal.class);
1168 userManagerInternal.addUserRestrictionsListener(mUserRestrictionsListener);
Lenka Trochtovac6f0e232017-01-17 10:35:49 +01001169 final boolean isBluetoothDisallowed = isBluetoothDisallowed();
Lenka Trochtovac6f0e232017-01-17 10:35:49 +01001170 if (isBluetoothDisallowed) {
Lenka Trochtova63d5e4a72016-12-02 12:19:39 +01001171 return;
1172 }
Zongheng Wang79e0bf62019-07-08 15:22:04 -07001173 final boolean isSafeMode = mContext.getPackageManager().isSafeMode();
1174 if (mEnableExternal && isBluetoothPersistedStateOnBluetooth() && !isSafeMode) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001175 if (DBG) {
1176 Slog.d(TAG, "Auto-enabling Bluetooth.");
1177 }
Jack He8caab152018-03-02 13:08:36 -08001178 sendEnableMsg(mQuietEnableExternal,
1179 BluetoothProtoEnums.ENABLE_DISABLE_REASON_SYSTEM_BOOT,
1180 mContext.getPackageName());
Ajay Panickerbf796d82016-03-11 13:47:20 -08001181 } else if (!isNameAndAddressSet()) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001182 if (DBG) {
1183 Slog.d(TAG, "Getting adapter name and address");
1184 }
Ajay Panicker4bb48302016-03-31 14:14:27 -07001185 Message getMsg = mHandler.obtainMessage(MESSAGE_GET_NAME_AND_ADDRESS);
1186 mHandler.sendMessage(getMsg);
Miao Chou658bf2f2015-06-26 17:14:35 -07001187 }
Miao Chou658bf2f2015-06-26 17:14:35 -07001188 }
1189
1190 /**
1191 * Called when switching to a different foreground user.
1192 */
1193 public void handleOnSwitchUser(int userHandle) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001194 if (DBG) {
1195 Slog.d(TAG, "User " + userHandle + " switched");
1196 }
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001197 mHandler.obtainMessage(MESSAGE_USER_SWITCHED, userHandle, 0).sendToTarget();
1198 }
1199
1200 /**
1201 * Called when user is unlocked.
1202 */
1203 public void handleOnUnlockUser(int userHandle) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001204 if (DBG) {
1205 Slog.d(TAG, "User " + userHandle + " unlocked");
1206 }
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001207 mHandler.obtainMessage(MESSAGE_USER_UNLOCKED, userHandle, 0).sendToTarget();
Miao Chou658bf2f2015-06-26 17:14:35 -07001208 }
1209
1210 /**
Benjamin Franze8b98922014-11-12 15:57:54 +00001211 * This class manages the clients connected to a given ProfileService
1212 * and maintains the connection with that service.
1213 */
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001214 private final class ProfileServiceConnections
1215 implements ServiceConnection, IBinder.DeathRecipient {
Benjamin Franze8b98922014-11-12 15:57:54 +00001216 final RemoteCallbackList<IBluetoothProfileServiceConnection> mProxies =
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001217 new RemoteCallbackList<IBluetoothProfileServiceConnection>();
Benjamin Franze8b98922014-11-12 15:57:54 +00001218 IBinder mService;
1219 ComponentName mClassName;
1220 Intent mIntent;
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001221 boolean mInvokingProxyCallbacks = false;
Benjamin Franze8b98922014-11-12 15:57:54 +00001222
1223 ProfileServiceConnections(Intent intent) {
1224 mService = null;
1225 mClassName = null;
1226 mIntent = intent;
1227 }
1228
Benjamin Franz5b614592014-12-09 18:58:45 +00001229 private boolean bindService() {
jonerlin37fc85d2018-08-09 16:39:43 +08001230 int state = BluetoothAdapter.STATE_OFF;
1231 try {
1232 mBluetoothLock.readLock().lock();
1233 if (mBluetooth != null) {
1234 state = mBluetooth.getState();
1235 }
1236 } catch (RemoteException e) {
1237 Slog.e(TAG, "Unable to call getState", e);
1238 return false;
1239 } finally {
1240 mBluetoothLock.readLock().unlock();
1241 }
1242
1243 if (!mEnable || state != BluetoothAdapter.STATE_ON) {
1244 if (DBG) {
1245 Slog.d(TAG, "Unable to bindService while Bluetooth is disabled");
1246 }
1247 return false;
1248 }
1249
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001250 if (mIntent != null && mService == null && doBind(mIntent, this, 0,
1251 UserHandle.CURRENT_OR_SELF)) {
Benjamin Franze8b98922014-11-12 15:57:54 +00001252 Message msg = mHandler.obtainMessage(MESSAGE_BIND_PROFILE_SERVICE);
1253 msg.obj = this;
1254 mHandler.sendMessageDelayed(msg, TIMEOUT_BIND_MS);
Benjamin Franz5b614592014-12-09 18:58:45 +00001255 return true;
Benjamin Franze8b98922014-11-12 15:57:54 +00001256 }
Jeff Sharkey67609c72016-03-05 14:29:13 -07001257 Slog.w(TAG, "Unable to bind with intent: " + mIntent);
Benjamin Franz5b614592014-12-09 18:58:45 +00001258 return false;
Benjamin Franze8b98922014-11-12 15:57:54 +00001259 }
1260
1261 private void addProxy(IBluetoothProfileServiceConnection proxy) {
1262 mProxies.register(proxy);
1263 if (mService != null) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001264 try {
Benjamin Franze8b98922014-11-12 15:57:54 +00001265 proxy.onServiceConnected(mClassName, mService);
1266 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001267 Slog.e(TAG, "Unable to connect to proxy", e);
Benjamin Franze8b98922014-11-12 15:57:54 +00001268 }
1269 } else {
1270 if (!mHandler.hasMessages(MESSAGE_BIND_PROFILE_SERVICE, this)) {
1271 Message msg = mHandler.obtainMessage(MESSAGE_BIND_PROFILE_SERVICE);
1272 msg.obj = this;
1273 mHandler.sendMessage(msg);
1274 }
1275 }
1276 }
1277
1278 private void removeProxy(IBluetoothProfileServiceConnection proxy) {
1279 if (proxy != null) {
1280 if (mProxies.unregister(proxy)) {
1281 try {
1282 proxy.onServiceDisconnected(mClassName);
1283 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001284 Slog.e(TAG, "Unable to disconnect proxy", e);
Benjamin Franze8b98922014-11-12 15:57:54 +00001285 }
1286 }
1287 } else {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001288 Slog.w(TAG, "Trying to remove a null proxy");
Benjamin Franze8b98922014-11-12 15:57:54 +00001289 }
1290 }
1291
1292 private void removeAllProxies() {
1293 onServiceDisconnected(mClassName);
1294 mProxies.kill();
1295 }
1296
Ugo Yu6d9cfce2019-03-26 21:38:08 +08001297 private boolean isEmpty() {
1298 return mProxies.getRegisteredCallbackCount() == 0;
1299 }
1300
Benjamin Franze8b98922014-11-12 15:57:54 +00001301 @Override
1302 public void onServiceConnected(ComponentName className, IBinder service) {
1303 // remove timeout message
1304 mHandler.removeMessages(MESSAGE_BIND_PROFILE_SERVICE, this);
1305 mService = service;
1306 mClassName = className;
1307 try {
1308 mService.linkToDeath(this, 0);
1309 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001310 Slog.e(TAG, "Unable to linkToDeath", e);
Benjamin Franze8b98922014-11-12 15:57:54 +00001311 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001312
1313 if (mInvokingProxyCallbacks) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001314 Slog.e(TAG, "Proxy callbacks already in progress.");
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001315 return;
Benjamin Franze8b98922014-11-12 15:57:54 +00001316 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001317 mInvokingProxyCallbacks = true;
1318
1319 final int n = mProxies.beginBroadcast();
1320 try {
1321 for (int i = 0; i < n; i++) {
1322 try {
1323 mProxies.getBroadcastItem(i).onServiceConnected(className, service);
1324 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001325 Slog.e(TAG, "Unable to connect to proxy", e);
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001326 }
1327 }
1328 } finally {
1329 mProxies.finishBroadcast();
1330 mInvokingProxyCallbacks = false;
1331 }
Benjamin Franze8b98922014-11-12 15:57:54 +00001332 }
1333
1334 @Override
1335 public void onServiceDisconnected(ComponentName className) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001336 if (mService == null) {
1337 return;
1338 }
Chienyuan177156b2018-12-18 10:40:25 +08001339 try {
1340 mService.unlinkToDeath(this, 0);
1341 } catch (NoSuchElementException e) {
1342 Log.e(TAG, "error unlinking to death", e);
1343 }
Benjamin Franze8b98922014-11-12 15:57:54 +00001344 mService = null;
1345 mClassName = null;
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001346
1347 if (mInvokingProxyCallbacks) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001348 Slog.e(TAG, "Proxy callbacks already in progress.");
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001349 return;
Benjamin Franze8b98922014-11-12 15:57:54 +00001350 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001351 mInvokingProxyCallbacks = true;
1352
1353 final int n = mProxies.beginBroadcast();
1354 try {
1355 for (int i = 0; i < n; i++) {
1356 try {
1357 mProxies.getBroadcastItem(i).onServiceDisconnected(className);
1358 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001359 Slog.e(TAG, "Unable to disconnect from proxy", e);
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001360 }
1361 }
1362 } finally {
1363 mProxies.finishBroadcast();
1364 mInvokingProxyCallbacks = false;
1365 }
Benjamin Franze8b98922014-11-12 15:57:54 +00001366 }
1367
1368 @Override
1369 public void binderDied() {
1370 if (DBG) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001371 Slog.w(TAG, "Profile service for profile: " + mClassName + " died.");
Benjamin Franze8b98922014-11-12 15:57:54 +00001372 }
1373 onServiceDisconnected(mClassName);
1374 // Trigger rebind
1375 Message msg = mHandler.obtainMessage(MESSAGE_BIND_PROFILE_SERVICE);
1376 msg.obj = this;
1377 mHandler.sendMessageDelayed(msg, TIMEOUT_BIND_MS);
1378 }
1379 }
1380
fredcbf072a72012-05-09 16:52:50 -07001381 private void sendBluetoothStateCallback(boolean isUp) {
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001382 try {
1383 int n = mStateChangeCallbacks.beginBroadcast();
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001384 if (DBG) {
1385 Slog.d(TAG, "Broadcasting onBluetoothStateChange(" + isUp + ") to " + n
1386 + " receivers.");
1387 }
1388 for (int i = 0; i < n; i++) {
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001389 try {
1390 mStateChangeCallbacks.getBroadcastItem(i).onBluetoothStateChange(isUp);
1391 } catch (RemoteException e) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001392 Slog.e(TAG, "Unable to call onBluetoothStateChange() on callback #" + i, e);
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001393 }
fredcbf072a72012-05-09 16:52:50 -07001394 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001395 } finally {
1396 mStateChangeCallbacks.finishBroadcast();
fredcbf072a72012-05-09 16:52:50 -07001397 }
fredcbf072a72012-05-09 16:52:50 -07001398 }
1399
1400 /**
Zhihai Xu40874a02012-10-08 17:57:03 -07001401 * Inform BluetoothAdapter instances that Adapter service is up
1402 */
1403 private void sendBluetoothServiceUpCallback() {
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001404 try {
1405 int n = mCallbacks.beginBroadcast();
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001406 Slog.d(TAG, "Broadcasting onBluetoothServiceUp() to " + n + " receivers.");
1407 for (int i = 0; i < n; i++) {
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001408 try {
1409 mCallbacks.getBroadcastItem(i).onBluetoothServiceUp(mBluetooth);
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001410 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001411 Slog.e(TAG, "Unable to call onBluetoothServiceUp() on callback #" + i, e);
Zhihai Xu40874a02012-10-08 17:57:03 -07001412 }
1413 }
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001414 } finally {
1415 mCallbacks.finishBroadcast();
Zhihai Xu40874a02012-10-08 17:57:03 -07001416 }
1417 }
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001418
Zhihai Xu40874a02012-10-08 17:57:03 -07001419 /**
fredcbf072a72012-05-09 16:52:50 -07001420 * Inform BluetoothAdapter instances that Adapter service is down
1421 */
1422 private void sendBluetoothServiceDownCallback() {
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001423 try {
1424 int n = mCallbacks.beginBroadcast();
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001425 Slog.d(TAG, "Broadcasting onBluetoothServiceDown() to " + n + " receivers.");
1426 for (int i = 0; i < n; i++) {
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001427 try {
1428 mCallbacks.getBroadcastItem(i).onBluetoothServiceDown();
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001429 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001430 Slog.e(TAG, "Unable to call onBluetoothServiceDown() on callback #" + i, e);
fredcd6883532012-04-25 17:46:13 -07001431 }
1432 }
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001433 } finally {
1434 mCallbacks.finishBroadcast();
fredcd6883532012-04-25 17:46:13 -07001435 }
1436 }
Svet Ganov408abf72015-05-12 19:13:36 -07001437
fredc0f420372012-04-12 00:02:00 -07001438 public String getAddress() {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001439 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");
Zhihai Xu40874a02012-10-08 17:57:03 -07001440
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001441 if ((Binder.getCallingUid() != Process.SYSTEM_UID) && (!checkIfCallerIsForegroundUser())) {
1442 Slog.w(TAG, "getAddress(): not allowed for non-active and non system user");
Zhihai Xu6eb76522012-11-29 15:41:04 -08001443 return null;
Zhihai Xu40874a02012-10-08 17:57:03 -07001444 }
1445
Svet Ganov408abf72015-05-12 19:13:36 -07001446 if (mContext.checkCallingOrSelfPermission(Manifest.permission.LOCAL_MAC_ADDRESS)
1447 != PackageManager.PERMISSION_GRANTED) {
1448 return BluetoothAdapter.DEFAULT_MAC_ADDRESS;
1449 }
1450
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001451 try {
1452 mBluetoothLock.readLock().lock();
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001453 if (mBluetooth != null) {
1454 return mBluetooth.getAddress();
1455 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001456 } catch (RemoteException e) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001457 Slog.e(TAG,
1458 "getAddress(): Unable to retrieve address remotely. Returning cached address",
1459 e);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001460 } finally {
1461 mBluetoothLock.readLock().unlock();
fredc116d1d462012-04-20 14:47:08 -07001462 }
Ajay Panickerbf796d82016-03-11 13:47:20 -08001463
Matthew Xiecdce0b92012-07-12 19:06:15 -07001464 // mAddress is accessed from outside.
1465 // It is alright without a lock. Here, bluetooth is off, no other thread is
1466 // changing mAddress
fredc0f420372012-04-12 00:02:00 -07001467 return mAddress;
1468 }
fredc649fe492012-04-19 01:07:18 -07001469
fredc0f420372012-04-12 00:02:00 -07001470 public String getName() {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001471 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");
Zhihai Xu40874a02012-10-08 17:57:03 -07001472
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001473 if ((Binder.getCallingUid() != Process.SYSTEM_UID) && (!checkIfCallerIsForegroundUser())) {
1474 Slog.w(TAG, "getName(): not allowed for non-active and non system user");
Zhihai Xu6eb76522012-11-29 15:41:04 -08001475 return null;
Zhihai Xu40874a02012-10-08 17:57:03 -07001476 }
1477
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001478 try {
1479 mBluetoothLock.readLock().lock();
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001480 if (mBluetooth != null) {
1481 return mBluetooth.getName();
1482 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001483 } catch (RemoteException e) {
1484 Slog.e(TAG, "getName(): Unable to retrieve name remotely. Returning cached name", e);
1485 } finally {
1486 mBluetoothLock.readLock().unlock();
fredc116d1d462012-04-20 14:47:08 -07001487 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001488
Matthew Xiecdce0b92012-07-12 19:06:15 -07001489 // mName is accessed from outside.
1490 // It alright without a lock. Here, bluetooth is off, no other thread is
1491 // changing mName
fredc0f420372012-04-12 00:02:00 -07001492 return mName;
1493 }
1494
fredc0f420372012-04-12 00:02:00 -07001495 private class BluetoothServiceConnection implements ServiceConnection {
Marie Janssencb21ad72016-12-13 10:51:02 -08001496 public void onServiceConnected(ComponentName componentName, IBinder service) {
1497 String name = componentName.getClassName();
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001498 if (DBG) {
1499 Slog.d(TAG, "BluetoothServiceConnection: " + name);
1500 }
fredc0f420372012-04-12 00:02:00 -07001501 Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_SERVICE_CONNECTED);
Marie Janssencb21ad72016-12-13 10:51:02 -08001502 if (name.equals("com.android.bluetooth.btservice.AdapterService")) {
Matthew Xieddf7e472013-03-01 18:41:02 -08001503 msg.arg1 = SERVICE_IBLUETOOTH;
Marie Janssencb21ad72016-12-13 10:51:02 -08001504 } else if (name.equals("com.android.bluetooth.gatt.GattService")) {
Matthew Xieddf7e472013-03-01 18:41:02 -08001505 msg.arg1 = SERVICE_IBLUETOOTHGATT;
1506 } else {
Marie Janssencb21ad72016-12-13 10:51:02 -08001507 Slog.e(TAG, "Unknown service connected: " + name);
Matthew Xieddf7e472013-03-01 18:41:02 -08001508 return;
1509 }
fredc0f420372012-04-12 00:02:00 -07001510 msg.obj = service;
1511 mHandler.sendMessage(msg);
1512 }
1513
Marie Janssencb21ad72016-12-13 10:51:02 -08001514 public void onServiceDisconnected(ComponentName componentName) {
1515 // Called if we unexpectedly disconnect.
1516 String name = componentName.getClassName();
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001517 if (DBG) {
1518 Slog.d(TAG, "BluetoothServiceConnection, disconnected: " + name);
1519 }
fredc0f420372012-04-12 00:02:00 -07001520 Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED);
Marie Janssencb21ad72016-12-13 10:51:02 -08001521 if (name.equals("com.android.bluetooth.btservice.AdapterService")) {
Matthew Xieddf7e472013-03-01 18:41:02 -08001522 msg.arg1 = SERVICE_IBLUETOOTH;
Marie Janssencb21ad72016-12-13 10:51:02 -08001523 } else if (name.equals("com.android.bluetooth.gatt.GattService")) {
Matthew Xieddf7e472013-03-01 18:41:02 -08001524 msg.arg1 = SERVICE_IBLUETOOTHGATT;
1525 } else {
Marie Janssencb21ad72016-12-13 10:51:02 -08001526 Slog.e(TAG, "Unknown service disconnected: " + name);
Matthew Xieddf7e472013-03-01 18:41:02 -08001527 return;
1528 }
fredc0f420372012-04-12 00:02:00 -07001529 mHandler.sendMessage(msg);
1530 }
1531 }
1532
1533 private BluetoothServiceConnection mConnection = new BluetoothServiceConnection();
1534
Zhihai Xu40874a02012-10-08 17:57:03 -07001535 private class BluetoothHandler extends Handler {
Ajay Panicker4bb48302016-03-31 14:14:27 -07001536 boolean mGetNameAddressOnly = false;
1537
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001538 BluetoothHandler(Looper looper) {
Zhihai Xu40874a02012-10-08 17:57:03 -07001539 super(looper);
1540 }
1541
fredc0f420372012-04-12 00:02:00 -07001542 @Override
1543 public void handleMessage(Message msg) {
fredc0f420372012-04-12 00:02:00 -07001544 switch (msg.what) {
Ajay Panicker4bb48302016-03-31 14:14:27 -07001545 case MESSAGE_GET_NAME_AND_ADDRESS:
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001546 if (DBG) {
1547 Slog.d(TAG, "MESSAGE_GET_NAME_AND_ADDRESS");
1548 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001549 try {
1550 mBluetoothLock.writeLock().lock();
Ajay Panicker4bb48302016-03-31 14:14:27 -07001551 if ((mBluetooth == null) && (!mBinding)) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001552 if (DBG) {
1553 Slog.d(TAG, "Binding to service to get name and address");
1554 }
Ajay Panicker4bb48302016-03-31 14:14:27 -07001555 mGetNameAddressOnly = true;
1556 Message timeoutMsg = mHandler.obtainMessage(MESSAGE_TIMEOUT_BIND);
1557 mHandler.sendMessageDelayed(timeoutMsg, TIMEOUT_BIND_MS);
1558 Intent i = new Intent(IBluetooth.class.getName());
1559 if (!doBind(i, mConnection,
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001560 Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT,
1561 UserHandle.CURRENT)) {
Ajay Panicker4bb48302016-03-31 14:14:27 -07001562 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
1563 } else {
1564 mBinding = true;
1565 }
1566 } else if (mBluetooth != null) {
1567 try {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001568 storeNameAndAddress(mBluetooth.getName(), mBluetooth.getAddress());
Ajay Panicker4bb48302016-03-31 14:14:27 -07001569 } catch (RemoteException re) {
1570 Slog.e(TAG, "Unable to grab names", re);
1571 }
1572 if (mGetNameAddressOnly && !mEnable) {
1573 unbindAndFinish();
1574 }
1575 mGetNameAddressOnly = false;
1576 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001577 } finally {
1578 mBluetoothLock.writeLock().unlock();
Ajay Panicker4bb48302016-03-31 14:14:27 -07001579 }
1580 break;
1581
Matthew Xiecdce0b92012-07-12 19:06:15 -07001582 case MESSAGE_ENABLE:
fredcf2458862012-04-16 15:18:27 -07001583 if (DBG) {
Marie Janssencb21ad72016-12-13 10:51:02 -08001584 Slog.d(TAG, "MESSAGE_ENABLE(" + msg.arg1 + "): mBluetooth = " + mBluetooth);
fredc649fe492012-04-19 01:07:18 -07001585 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001586 mHandler.removeMessages(MESSAGE_RESTART_BLUETOOTH_SERVICE);
1587 mEnable = true;
Calvin Ona0b91d72016-06-15 17:58:23 -07001588
1589 // Use service interface to get the exact state
1590 try {
1591 mBluetoothLock.readLock().lock();
1592 if (mBluetooth != null) {
1593 int state = mBluetooth.getState();
1594 if (state == BluetoothAdapter.STATE_BLE_ON) {
Marie Janssene0bfa2e2016-12-20 11:21:12 -08001595 Slog.w(TAG, "BT Enable in BLE_ON State, going to ON");
Calvin Ona0b91d72016-06-15 17:58:23 -07001596 mBluetooth.onLeServiceUp();
Marie Janssene0bfa2e2016-12-20 11:21:12 -08001597 persistBluetoothSetting(BLUETOOTH_ON_BLUETOOTH);
Calvin Ona0b91d72016-06-15 17:58:23 -07001598 break;
1599 }
1600 }
1601 } catch (RemoteException e) {
1602 Slog.e(TAG, "", e);
1603 } finally {
1604 mBluetoothLock.readLock().unlock();
1605 }
1606
1607 mQuietEnable = (msg.arg1 == 1);
Pavlin Radoslavove47ec142016-06-01 22:25:18 -07001608 if (mBluetooth == null) {
Calvin Ona0b91d72016-06-15 17:58:23 -07001609 handleEnable(mQuietEnable);
Pavlin Radoslavove47ec142016-06-01 22:25:18 -07001610 } else {
1611 //
1612 // We need to wait until transitioned to STATE_OFF and
1613 // the previous Bluetooth process has exited. The
1614 // waiting period has three components:
1615 // (a) Wait until the local state is STATE_OFF. This
1616 // is accomplished by "waitForOnOff(false, true)".
1617 // (b) Wait until the STATE_OFF state is updated to
1618 // all components.
1619 // (c) Wait until the Bluetooth process exits, and
1620 // ActivityManager detects it.
1621 // The waiting for (b) and (c) is accomplished by
1622 // delaying the MESSAGE_RESTART_BLUETOOTH_SERVICE
1623 // message. On slower devices, that delay needs to be
1624 // on the order of (2 * SERVICE_RESTART_TIME_MS).
1625 //
1626 waitForOnOff(false, true);
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001627 Message restartMsg =
1628 mHandler.obtainMessage(MESSAGE_RESTART_BLUETOOTH_SERVICE);
1629 mHandler.sendMessageDelayed(restartMsg, 2 * SERVICE_RESTART_TIME_MS);
Pavlin Radoslavove47ec142016-06-01 22:25:18 -07001630 }
fredc649fe492012-04-19 01:07:18 -07001631 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001632
fredc0f420372012-04-12 00:02:00 -07001633 case MESSAGE_DISABLE:
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001634 if (DBG) {
1635 Slog.d(TAG, "MESSAGE_DISABLE: mBluetooth = " + mBluetooth);
1636 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001637 mHandler.removeMessages(MESSAGE_RESTART_BLUETOOTH_SERVICE);
1638 if (mEnable && mBluetooth != null) {
1639 waitForOnOff(true, false);
1640 mEnable = false;
Zhihai Xu401202b2012-12-03 11:36:21 -08001641 handleDisable();
Zhihai Xu40874a02012-10-08 17:57:03 -07001642 waitForOnOff(false, false);
1643 } else {
1644 mEnable = false;
Zhihai Xu401202b2012-12-03 11:36:21 -08001645 handleDisable();
Zhihai Xu40874a02012-10-08 17:57:03 -07001646 }
fredc0f420372012-04-12 00:02:00 -07001647 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001648
Stanley Tng873b5702017-05-01 21:27:31 -07001649 case MESSAGE_RESTORE_USER_SETTING:
Jack He8caab152018-03-02 13:08:36 -08001650 if ((msg.arg1 == RESTORE_SETTING_TO_OFF) && mEnable) {
1651 if (DBG) {
1652 Slog.d(TAG, "Restore Bluetooth state to disabled");
Stanley Tng873b5702017-05-01 21:27:31 -07001653 }
Jack He8caab152018-03-02 13:08:36 -08001654 persistBluetoothSetting(BLUETOOTH_OFF);
1655 mEnableExternal = false;
1656 sendDisableMsg(
1657 BluetoothProtoEnums.ENABLE_DISABLE_REASON_RESTORE_USER_SETTING,
1658 mContext.getPackageName());
1659 } else if ((msg.arg1 == RESTORE_SETTING_TO_ON) && !mEnable) {
1660 if (DBG) {
1661 Slog.d(TAG, "Restore Bluetooth state to enabled");
1662 }
1663 mQuietEnableExternal = false;
1664 mEnableExternal = true;
1665 // waive WRITE_SECURE_SETTINGS permission check
1666 sendEnableMsg(false,
1667 BluetoothProtoEnums.ENABLE_DISABLE_REASON_RESTORE_USER_SETTING,
1668 mContext.getPackageName());
Stanley Tng873b5702017-05-01 21:27:31 -07001669 }
1670 break;
1671
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001672 case MESSAGE_REGISTER_ADAPTER: {
fredc0f420372012-04-12 00:02:00 -07001673 IBluetoothManagerCallback callback = (IBluetoothManagerCallback) msg.obj;
Marie Janssencb21ad72016-12-13 10:51:02 -08001674 mCallbacks.register(callback);
fredc0f420372012-04-12 00:02:00 -07001675 break;
Marie Janssencb21ad72016-12-13 10:51:02 -08001676 }
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001677 case MESSAGE_UNREGISTER_ADAPTER: {
fredc0f420372012-04-12 00:02:00 -07001678 IBluetoothManagerCallback callback = (IBluetoothManagerCallback) msg.obj;
Marie Janssencb21ad72016-12-13 10:51:02 -08001679 mCallbacks.unregister(callback);
fredc0f420372012-04-12 00:02:00 -07001680 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001681 }
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001682 case MESSAGE_REGISTER_STATE_CHANGE_CALLBACK: {
1683 IBluetoothStateChangeCallback callback =
1684 (IBluetoothStateChangeCallback) msg.obj;
Marie Janssencb21ad72016-12-13 10:51:02 -08001685 mStateChangeCallbacks.register(callback);
fredc0f420372012-04-12 00:02:00 -07001686 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001687 }
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001688 case MESSAGE_UNREGISTER_STATE_CHANGE_CALLBACK: {
1689 IBluetoothStateChangeCallback callback =
1690 (IBluetoothStateChangeCallback) msg.obj;
Marie Janssencb21ad72016-12-13 10:51:02 -08001691 mStateChangeCallbacks.unregister(callback);
fredc0f420372012-04-12 00:02:00 -07001692 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001693 }
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001694 case MESSAGE_ADD_PROXY_DELAYED: {
Jack He8caab152018-03-02 13:08:36 -08001695 ProfileServiceConnections psc = mProfileServices.get(msg.arg1);
Benjamin Franze8b98922014-11-12 15:57:54 +00001696 if (psc == null) {
1697 break;
1698 }
1699 IBluetoothProfileServiceConnection proxy =
1700 (IBluetoothProfileServiceConnection) msg.obj;
1701 psc.addProxy(proxy);
1702 break;
1703 }
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001704 case MESSAGE_BIND_PROFILE_SERVICE: {
Benjamin Franze8b98922014-11-12 15:57:54 +00001705 ProfileServiceConnections psc = (ProfileServiceConnections) msg.obj;
1706 removeMessages(MESSAGE_BIND_PROFILE_SERVICE, msg.obj);
1707 if (psc == null) {
1708 break;
1709 }
1710 psc.bindService();
1711 break;
1712 }
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001713 case MESSAGE_BLUETOOTH_SERVICE_CONNECTED: {
1714 if (DBG) {
1715 Slog.d(TAG, "MESSAGE_BLUETOOTH_SERVICE_CONNECTED: " + msg.arg1);
1716 }
fredc0f420372012-04-12 00:02:00 -07001717
1718 IBinder service = (IBinder) msg.obj;
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001719 try {
1720 mBluetoothLock.writeLock().lock();
Matthew Xieddf7e472013-03-01 18:41:02 -08001721 if (msg.arg1 == SERVICE_IBLUETOOTHGATT) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001722 mBluetoothGatt =
1723 IBluetoothGatt.Stub.asInterface(Binder.allowBlocking(service));
Myles Watson304ebf22018-05-11 08:47:24 -07001724 continueFromBleOnState();
Matthew Xieddf7e472013-03-01 18:41:02 -08001725 break;
1726 } // else must be SERVICE_IBLUETOOTH
1727
1728 //Remove timeout
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001729 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
Matthew Xieddf7e472013-03-01 18:41:02 -08001730
fredc0f420372012-04-12 00:02:00 -07001731 mBinding = false;
Marie Janssen9db28eb2016-01-12 16:05:15 -08001732 mBluetoothBinder = service;
Jeff Sharkey0a17db12016-11-04 11:23:46 -06001733 mBluetooth = IBluetooth.Stub.asInterface(Binder.allowBlocking(service));
fredc0f420372012-04-12 00:02:00 -07001734
Ajay Panicker4bb48302016-03-31 14:14:27 -07001735 if (!isNameAndAddressSet()) {
1736 Message getMsg = mHandler.obtainMessage(MESSAGE_GET_NAME_AND_ADDRESS);
1737 mHandler.sendMessage(getMsg);
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001738 if (mGetNameAddressOnly) {
1739 return;
1740 }
Ajay Panicker4bb48302016-03-31 14:14:27 -07001741 }
1742
Matthew Xiecdce0b92012-07-12 19:06:15 -07001743 //Register callback object
fredcbf072a72012-05-09 16:52:50 -07001744 try {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001745 mBluetooth.registerCallback(mBluetoothCallback);
1746 } catch (RemoteException re) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001747 Slog.e(TAG, "Unable to register BluetoothCallback", re);
fredcbf072a72012-05-09 16:52:50 -07001748 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001749 //Inform BluetoothAdapter instances that service is up
Zhihai Xu40874a02012-10-08 17:57:03 -07001750 sendBluetoothServiceUpCallback();
1751
Matthew Xiecdce0b92012-07-12 19:06:15 -07001752 //Do enable request
1753 try {
Jack Hea6e031c2017-12-08 12:21:37 -08001754 if (!mQuietEnable) {
Marie Janssencb21ad72016-12-13 10:51:02 -08001755 if (!mBluetooth.enable()) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001756 Slog.e(TAG, "IBluetooth.enable() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001757 }
Marie Janssencb21ad72016-12-13 10:51:02 -08001758 } else {
1759 if (!mBluetooth.enableNoAutoConnect()) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001760 Slog.e(TAG, "IBluetooth.enableNoAutoConnect() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001761 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001762 }
1763 } catch (RemoteException e) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001764 Slog.e(TAG, "Unable to call enable()", e);
Matthew Xiecdce0b92012-07-12 19:06:15 -07001765 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001766 } finally {
1767 mBluetoothLock.writeLock().unlock();
Freda8c6df02012-07-11 10:25:23 -07001768 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001769
1770 if (!mEnable) {
1771 waitForOnOff(true, false);
Zhihai Xu401202b2012-12-03 11:36:21 -08001772 handleDisable();
Zhihai Xu40874a02012-10-08 17:57:03 -07001773 waitForOnOff(false, false);
1774 }
fredc649fe492012-04-19 01:07:18 -07001775 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001776 }
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001777 case MESSAGE_BLUETOOTH_STATE_CHANGE: {
fredcbf072a72012-05-09 16:52:50 -07001778 int prevState = msg.arg1;
1779 int newState = msg.arg2;
Marie Janssencb21ad72016-12-13 10:51:02 -08001780 if (DBG) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001781 Slog.d(TAG,
1782 "MESSAGE_BLUETOOTH_STATE_CHANGE: " + BluetoothAdapter.nameForState(
1783 prevState) + " > " + BluetoothAdapter.nameForState(
1784 newState));
Marie Janssencb21ad72016-12-13 10:51:02 -08001785 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001786 mState = newState;
1787 bluetoothStateChangeHandler(prevState, newState);
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001788 // handle error state transition case from TURNING_ON to OFF
1789 // unbind and rebind bluetooth service and enable bluetooth
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001790 if ((prevState == BluetoothAdapter.STATE_BLE_TURNING_ON) && (newState
1791 == BluetoothAdapter.STATE_OFF) && (mBluetooth != null) && mEnable) {
Marie Janssen2977c3e2016-11-09 12:01:24 -08001792 recoverBluetoothServiceFromError(false);
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001793 }
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001794 if ((prevState == BluetoothAdapter.STATE_TURNING_ON) && (newState
1795 == BluetoothAdapter.STATE_BLE_ON) && (mBluetooth != null) && mEnable) {
Marie Janssen2977c3e2016-11-09 12:01:24 -08001796 recoverBluetoothServiceFromError(true);
Nitin Arorad055adb2015-03-02 15:03:51 -08001797 }
Calvin Ona0b91d72016-06-15 17:58:23 -07001798 // If we tried to enable BT while BT was in the process of shutting down,
1799 // wait for the BT process to fully tear down and then force a restart
1800 // here. This is a bit of a hack (b/29363429).
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001801 if ((prevState == BluetoothAdapter.STATE_BLE_TURNING_OFF) && (newState
1802 == BluetoothAdapter.STATE_OFF)) {
Calvin Ona0b91d72016-06-15 17:58:23 -07001803 if (mEnable) {
1804 Slog.d(TAG, "Entering STATE_OFF but mEnabled is true; restarting.");
1805 waitForOnOff(false, true);
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001806 Message restartMsg =
1807 mHandler.obtainMessage(MESSAGE_RESTART_BLUETOOTH_SERVICE);
Calvin Ona0b91d72016-06-15 17:58:23 -07001808 mHandler.sendMessageDelayed(restartMsg, 2 * SERVICE_RESTART_TIME_MS);
1809 }
1810 }
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001811 if (newState == BluetoothAdapter.STATE_ON
1812 || newState == BluetoothAdapter.STATE_BLE_ON) {
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001813 // bluetooth is working, reset the counter
1814 if (mErrorRecoveryRetryCounter != 0) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001815 Slog.w(TAG, "bluetooth is recovered from error");
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001816 mErrorRecoveryRetryCounter = 0;
1817 }
1818 }
fredc649fe492012-04-19 01:07:18 -07001819 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001820 }
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001821 case MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED: {
Marie Janssencb21ad72016-12-13 10:51:02 -08001822 Slog.e(TAG, "MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED(" + msg.arg1 + ")");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001823 try {
1824 mBluetoothLock.writeLock().lock();
Matthew Xieddf7e472013-03-01 18:41:02 -08001825 if (msg.arg1 == SERVICE_IBLUETOOTH) {
1826 // if service is unbinded already, do nothing and return
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001827 if (mBluetooth == null) {
1828 break;
1829 }
Matthew Xieddf7e472013-03-01 18:41:02 -08001830 mBluetooth = null;
1831 } else if (msg.arg1 == SERVICE_IBLUETOOTHGATT) {
1832 mBluetoothGatt = null;
1833 break;
1834 } else {
Marie Janssencb21ad72016-12-13 10:51:02 -08001835 Slog.e(TAG, "Unknown argument for service disconnect!");
Matthew Xieddf7e472013-03-01 18:41:02 -08001836 break;
1837 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001838 } finally {
1839 mBluetoothLock.writeLock().unlock();
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301840 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001841
Marie Janssene54b4222017-03-16 18:10:59 -07001842 // log the unexpected crash
1843 addCrashLog();
Jack He8caab152018-03-02 13:08:36 -08001844 addActiveLog(BluetoothProtoEnums.ENABLE_DISABLE_REASON_CRASH,
1845 mContext.getPackageName(), false);
Zhihai Xu40874a02012-10-08 17:57:03 -07001846 if (mEnable) {
1847 mEnable = false;
1848 // Send a Bluetooth Restart message
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001849 Message restartMsg =
1850 mHandler.obtainMessage(MESSAGE_RESTART_BLUETOOTH_SERVICE);
1851 mHandler.sendMessageDelayed(restartMsg, SERVICE_RESTART_TIME_MS);
Zhihai Xu40874a02012-10-08 17:57:03 -07001852 }
1853
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001854 sendBluetoothServiceDownCallback();
Zhihai Xu40874a02012-10-08 17:57:03 -07001855
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001856 // Send BT state broadcast to update
1857 // the BT icon correctly
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001858 if ((mState == BluetoothAdapter.STATE_TURNING_ON) || (mState
1859 == BluetoothAdapter.STATE_ON)) {
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001860 bluetoothStateChangeHandler(BluetoothAdapter.STATE_ON,
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001861 BluetoothAdapter.STATE_TURNING_OFF);
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001862 mState = BluetoothAdapter.STATE_TURNING_OFF;
Zhihai Xu40874a02012-10-08 17:57:03 -07001863 }
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001864 if (mState == BluetoothAdapter.STATE_TURNING_OFF) {
1865 bluetoothStateChangeHandler(BluetoothAdapter.STATE_TURNING_OFF,
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001866 BluetoothAdapter.STATE_OFF);
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001867 }
1868
1869 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
1870 mState = BluetoothAdapter.STATE_OFF;
fredc649fe492012-04-19 01:07:18 -07001871 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001872 }
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001873 case MESSAGE_RESTART_BLUETOOTH_SERVICE: {
Marie Janssencb21ad72016-12-13 10:51:02 -08001874 Slog.d(TAG, "MESSAGE_RESTART_BLUETOOTH_SERVICE");
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301875 /* Enable without persisting the setting as
1876 it doesnt change when IBluetooth
1877 service restarts */
Zhihai Xu40874a02012-10-08 17:57:03 -07001878 mEnable = true;
Jack He8caab152018-03-02 13:08:36 -08001879 addActiveLog(BluetoothProtoEnums.ENABLE_DISABLE_REASON_RESTARTED,
1880 mContext.getPackageName(), true);
Zhihai Xu401202b2012-12-03 11:36:21 -08001881 handleEnable(mQuietEnable);
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301882 break;
1883 }
Marie Janssencb21ad72016-12-13 10:51:02 -08001884 case MESSAGE_TIMEOUT_BIND: {
1885 Slog.e(TAG, "MESSAGE_TIMEOUT_BIND");
1886 mBluetoothLock.writeLock().lock();
1887 mBinding = false;
1888 mBluetoothLock.writeLock().unlock();
1889 break;
1890 }
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001891 case MESSAGE_TIMEOUT_UNBIND: {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001892 Slog.e(TAG, "MESSAGE_TIMEOUT_UNBIND");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001893 mBluetoothLock.writeLock().lock();
1894 mUnbinding = false;
1895 mBluetoothLock.writeLock().unlock();
fredc649fe492012-04-19 01:07:18 -07001896 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001897 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001898
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001899 case MESSAGE_USER_SWITCHED: {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001900 if (DBG) {
1901 Slog.d(TAG, "MESSAGE_USER_SWITCHED");
1902 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001903 mHandler.removeMessages(MESSAGE_USER_SWITCHED);
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001904
Zhihai Xu40874a02012-10-08 17:57:03 -07001905 /* disable and enable BT when detect a user switch */
Ram Periathiruvadi88256d12017-05-03 19:11:20 -07001906 if (mBluetooth != null && isEnabled()) {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001907 try {
1908 mBluetoothLock.readLock().lock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001909 if (mBluetooth != null) {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001910 mBluetooth.unregisterCallback(mBluetoothCallback);
Zhihai Xu40874a02012-10-08 17:57:03 -07001911 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001912 } catch (RemoteException re) {
1913 Slog.e(TAG, "Unable to unregister", re);
1914 } finally {
1915 mBluetoothLock.readLock().unlock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001916 }
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001917
1918 if (mState == BluetoothAdapter.STATE_TURNING_OFF) {
1919 // MESSAGE_USER_SWITCHED happened right after MESSAGE_ENABLE
1920 bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_OFF);
1921 mState = BluetoothAdapter.STATE_OFF;
1922 }
1923 if (mState == BluetoothAdapter.STATE_OFF) {
1924 bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_TURNING_ON);
1925 mState = BluetoothAdapter.STATE_TURNING_ON;
1926 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001927
1928 waitForOnOff(true, false);
1929
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001930 if (mState == BluetoothAdapter.STATE_TURNING_ON) {
1931 bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_ON);
1932 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001933
Benjamin Franze8b98922014-11-12 15:57:54 +00001934 unbindAllBluetoothProfileServices();
Zhihai Xu40874a02012-10-08 17:57:03 -07001935 // disable
Jack He8caab152018-03-02 13:08:36 -08001936 addActiveLog(BluetoothProtoEnums.ENABLE_DISABLE_REASON_USER_SWITCH,
1937 mContext.getPackageName(), false);
Zhihai Xu401202b2012-12-03 11:36:21 -08001938 handleDisable();
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001939 // Pbap service need receive STATE_TURNING_OFF intent to close
1940 bluetoothStateChangeHandler(BluetoothAdapter.STATE_ON,
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001941 BluetoothAdapter.STATE_TURNING_OFF);
Zhihai Xu40874a02012-10-08 17:57:03 -07001942
Pavlin Radoslavov41401112016-06-27 15:25:18 -07001943 boolean didDisableTimeout = !waitForOnOff(false, true);
Zhihai Xu40874a02012-10-08 17:57:03 -07001944
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001945 bluetoothStateChangeHandler(BluetoothAdapter.STATE_TURNING_OFF,
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001946 BluetoothAdapter.STATE_OFF);
Zhihai Xu40874a02012-10-08 17:57:03 -07001947 sendBluetoothServiceDownCallback();
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001948
Pavlin Radoslavove957a8a2016-05-24 15:28:41 -07001949 try {
1950 mBluetoothLock.writeLock().lock();
1951 if (mBluetooth != null) {
1952 mBluetooth = null;
1953 // Unbind
1954 mContext.unbindService(mConnection);
1955 }
1956 mBluetoothGatt = null;
1957 } finally {
1958 mBluetoothLock.writeLock().unlock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001959 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001960
Pavlin Radoslavov41401112016-06-27 15:25:18 -07001961 //
1962 // If disabling Bluetooth times out, wait for an
1963 // additional amount of time to ensure the process is
1964 // shut down completely before attempting to restart.
1965 //
1966 if (didDisableTimeout) {
1967 SystemClock.sleep(3000);
1968 } else {
1969 SystemClock.sleep(100);
1970 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001971
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001972 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
1973 mState = BluetoothAdapter.STATE_OFF;
Zhihai Xu40874a02012-10-08 17:57:03 -07001974 // enable
Jack He8caab152018-03-02 13:08:36 -08001975 addActiveLog(BluetoothProtoEnums.ENABLE_DISABLE_REASON_USER_SWITCH,
1976 mContext.getPackageName(), true);
Ram Periathiruvadi88256d12017-05-03 19:11:20 -07001977 // mEnable flag could have been reset on disableBLE. Reenable it.
1978 mEnable = true;
Zhihai Xu401202b2012-12-03 11:36:21 -08001979 handleEnable(mQuietEnable);
John Spurlock8a985d22014-02-25 09:40:05 -05001980 } else if (mBinding || mBluetooth != null) {
Zhihai Xu40874a02012-10-08 17:57:03 -07001981 Message userMsg = mHandler.obtainMessage(MESSAGE_USER_SWITCHED);
1982 userMsg.arg2 = 1 + msg.arg2;
Marie Janssencb21ad72016-12-13 10:51:02 -08001983 // if user is switched when service is binding retry after a delay
Zhihai Xu40874a02012-10-08 17:57:03 -07001984 mHandler.sendMessageDelayed(userMsg, USER_SWITCHED_TIME_MS);
1985 if (DBG) {
Marie Janssencb21ad72016-12-13 10:51:02 -08001986 Slog.d(TAG, "Retry MESSAGE_USER_SWITCHED " + userMsg.arg2);
Zhihai Xu40874a02012-10-08 17:57:03 -07001987 }
John Spurlock8a985d22014-02-25 09:40:05 -05001988 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001989 break;
1990 }
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001991 case MESSAGE_USER_UNLOCKED: {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001992 if (DBG) {
1993 Slog.d(TAG, "MESSAGE_USER_UNLOCKED");
1994 }
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001995 mHandler.removeMessages(MESSAGE_USER_SWITCHED);
1996
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001997 if (mEnable && !mBinding && (mBluetooth == null)) {
1998 // We should be connected, but we gave up for some
1999 // reason; maybe the Bluetooth service wasn't encryption
2000 // aware, so try binding again.
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002001 if (DBG) {
2002 Slog.d(TAG, "Enabled but not bound; retrying after unlock");
2003 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07002004 handleEnable(mQuietEnable);
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07002005 }
2006 }
fredc0f420372012-04-12 00:02:00 -07002007 }
2008 }
Zhihai Xu40874a02012-10-08 17:57:03 -07002009 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07002010
Zhihai Xu401202b2012-12-03 11:36:21 -08002011 private void handleEnable(boolean quietMode) {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07002012 mQuietEnable = quietMode;
2013
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07002014 try {
2015 mBluetoothLock.writeLock().lock();
Zhihai Xu40874a02012-10-08 17:57:03 -07002016 if ((mBluetooth == null) && (!mBinding)) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07002017 //Start bind timeout and bind
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002018 Message timeoutMsg = mHandler.obtainMessage(MESSAGE_TIMEOUT_BIND);
2019 mHandler.sendMessageDelayed(timeoutMsg, TIMEOUT_BIND_MS);
Matthew Xiecdce0b92012-07-12 19:06:15 -07002020 Intent i = new Intent(IBluetooth.class.getName());
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002021 if (!doBind(i, mConnection, Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT,
Dianne Hackbornce09f5a2014-10-10 15:03:13 -07002022 UserHandle.CURRENT)) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07002023 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
Zhihai Xu40874a02012-10-08 17:57:03 -07002024 } else {
2025 mBinding = true;
Matthew Xiecdce0b92012-07-12 19:06:15 -07002026 }
Zhihai Xu40874a02012-10-08 17:57:03 -07002027 } else if (mBluetooth != null) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07002028 //Enable bluetooth
2029 try {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07002030 if (!mQuietEnable) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002031 if (!mBluetooth.enable()) {
2032 Slog.e(TAG, "IBluetooth.enable() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07002033 }
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002034 } else {
2035 if (!mBluetooth.enableNoAutoConnect()) {
2036 Slog.e(TAG, "IBluetooth.enableNoAutoConnect() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07002037 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07002038 }
2039 } catch (RemoteException e) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002040 Slog.e(TAG, "Unable to call enable()", e);
Matthew Xiecdce0b92012-07-12 19:06:15 -07002041 }
2042 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07002043 } finally {
2044 mBluetoothLock.writeLock().unlock();
Matthew Xiecdce0b92012-07-12 19:06:15 -07002045 }
2046 }
2047
Dianne Hackborn221ea892013-08-04 16:50:16 -07002048 boolean doBind(Intent intent, ServiceConnection conn, int flags, UserHandle user) {
2049 ComponentName comp = intent.resolveSystemService(mContext.getPackageManager(), 0);
2050 intent.setComponent(comp);
2051 if (comp == null || !mContext.bindServiceAsUser(intent, conn, flags, user)) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07002052 Slog.e(TAG, "Fail to bind to: " + intent);
Dianne Hackborn221ea892013-08-04 16:50:16 -07002053 return false;
2054 }
2055 return true;
2056 }
2057
Zhihai Xu401202b2012-12-03 11:36:21 -08002058 private void handleDisable() {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07002059 try {
2060 mBluetoothLock.readLock().lock();
Andre Eisenbach305fdab2015-11-11 21:43:26 -08002061 if (mBluetooth != null) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002062 if (DBG) {
2063 Slog.d(TAG, "Sending off request.");
2064 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07002065 if (!mBluetooth.disable()) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002066 Slog.e(TAG, "IBluetooth.disable() returned false");
Matthew Xiecdce0b92012-07-12 19:06:15 -07002067 }
2068 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07002069 } catch (RemoteException e) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002070 Slog.e(TAG, "Unable to call disable()", e);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07002071 } finally {
2072 mBluetoothLock.readLock().unlock();
Matthew Xiecdce0b92012-07-12 19:06:15 -07002073 }
2074 }
Zhihai Xu40874a02012-10-08 17:57:03 -07002075
2076 private boolean checkIfCallerIsForegroundUser() {
2077 int foregroundUser;
2078 int callingUser = UserHandle.getCallingUserId();
Martijn Coenen8385c5a2012-11-29 10:14:16 -08002079 int callingUid = Binder.getCallingUid();
Zhihai Xu40874a02012-10-08 17:57:03 -07002080 long callingIdentity = Binder.clearCallingIdentity();
Benjamin Franze8b98922014-11-12 15:57:54 +00002081 UserManager um = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
2082 UserInfo ui = um.getProfileParent(callingUser);
2083 int parentUser = (ui != null) ? ui.id : UserHandle.USER_NULL;
Martijn Coenen8385c5a2012-11-29 10:14:16 -08002084 int callingAppId = UserHandle.getAppId(callingUid);
Zhihai Xu40874a02012-10-08 17:57:03 -07002085 boolean valid = false;
2086 try {
2087 foregroundUser = ActivityManager.getCurrentUser();
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002088 valid = (callingUser == foregroundUser) || parentUser == foregroundUser
2089 || callingAppId == Process.NFC_UID || callingAppId == mSystemUiUid;
Marie Janssencb21ad72016-12-13 10:51:02 -08002090 if (DBG && !valid) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002091 Slog.d(TAG, "checkIfCallerIsForegroundUser: valid=" + valid + " callingUser="
2092 + callingUser + " parentUser=" + parentUser + " foregroundUser="
2093 + foregroundUser);
Zhihai Xu40874a02012-10-08 17:57:03 -07002094 }
2095 } finally {
2096 Binder.restoreCallingIdentity(callingIdentity);
2097 }
2098 return valid;
2099 }
2100
Nitin Arorad055adb2015-03-02 15:03:51 -08002101 private void sendBleStateChanged(int prevState, int newState) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002102 if (DBG) {
2103 Slog.d(TAG,
2104 "Sending BLE State Change: " + BluetoothAdapter.nameForState(prevState) + " > "
2105 + BluetoothAdapter.nameForState(newState));
2106 }
Nitin Arorad055adb2015-03-02 15:03:51 -08002107 // Send broadcast message to everyone else
2108 Intent intent = new Intent(BluetoothAdapter.ACTION_BLE_STATE_CHANGED);
2109 intent.putExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE, prevState);
2110 intent.putExtra(BluetoothAdapter.EXTRA_STATE, newState);
2111 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
2112 mContext.sendBroadcastAsUser(intent, UserHandle.ALL, BLUETOOTH_PERM);
2113 }
2114
Zhihai Xu40874a02012-10-08 17:57:03 -07002115 private void bluetoothStateChangeHandler(int prevState, int newState) {
Nitin Arorad055adb2015-03-02 15:03:51 -08002116 boolean isStandardBroadcast = true;
Marie Janssencb21ad72016-12-13 10:51:02 -08002117 if (prevState == newState) { // No change. Nothing to do.
2118 return;
2119 }
2120 // Notify all proxy objects first of adapter state change
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002121 if (newState == BluetoothAdapter.STATE_BLE_ON || newState == BluetoothAdapter.STATE_OFF) {
Marie Janssencb21ad72016-12-13 10:51:02 -08002122 boolean intermediate_off = (prevState == BluetoothAdapter.STATE_TURNING_OFF
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002123 && newState == BluetoothAdapter.STATE_BLE_ON);
Zhihai Xu40874a02012-10-08 17:57:03 -07002124
Marie Janssencb21ad72016-12-13 10:51:02 -08002125 if (newState == BluetoothAdapter.STATE_OFF) {
2126 // If Bluetooth is off, send service down event to proxy objects, and unbind
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002127 if (DBG) {
2128 Slog.d(TAG, "Bluetooth is complete send Service Down");
2129 }
Marie Janssencb21ad72016-12-13 10:51:02 -08002130 sendBluetoothServiceDownCallback();
2131 unbindAndFinish();
Nitin Arorad055adb2015-03-02 15:03:51 -08002132 sendBleStateChanged(prevState, newState);
Marie Janssencb21ad72016-12-13 10:51:02 -08002133 // Don't broadcast as it has already been broadcast before
Nitin Arorad055adb2015-03-02 15:03:51 -08002134 isStandardBroadcast = false;
2135
Marie Janssencb21ad72016-12-13 10:51:02 -08002136 } else if (!intermediate_off) {
2137 // connect to GattService
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002138 if (DBG) {
2139 Slog.d(TAG, "Bluetooth is in LE only mode");
2140 }
Myles Watson304ebf22018-05-11 08:47:24 -07002141 if (mBluetoothGatt != null || !mContext.getPackageManager()
2142 .hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
2143 continueFromBleOnState();
Marie Janssencb21ad72016-12-13 10:51:02 -08002144 } else {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002145 if (DBG) {
2146 Slog.d(TAG, "Binding Bluetooth GATT service");
2147 }
Myles Watson304ebf22018-05-11 08:47:24 -07002148 Intent i = new Intent(IBluetoothGatt.class.getName());
2149 doBind(i, mConnection, Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT,
2150 UserHandle.CURRENT);
Nitin Arorad055adb2015-03-02 15:03:51 -08002151 }
Marie Janssencb21ad72016-12-13 10:51:02 -08002152 sendBleStateChanged(prevState, newState);
2153 //Don't broadcase this as std intent
2154 isStandardBroadcast = false;
2155
2156 } else if (intermediate_off) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002157 if (DBG) {
2158 Slog.d(TAG, "Intermediate off, back to LE only mode");
2159 }
Marie Janssencb21ad72016-12-13 10:51:02 -08002160 // For LE only mode, broadcast as is
2161 sendBleStateChanged(prevState, newState);
2162 sendBluetoothStateCallback(false); // BT is OFF for general users
2163 // Broadcast as STATE_OFF
2164 newState = BluetoothAdapter.STATE_OFF;
2165 sendBrEdrDownCallback();
Nitin Arorad055adb2015-03-02 15:03:51 -08002166 }
Marie Janssencb21ad72016-12-13 10:51:02 -08002167 } else if (newState == BluetoothAdapter.STATE_ON) {
2168 boolean isUp = (newState == BluetoothAdapter.STATE_ON);
2169 sendBluetoothStateCallback(isUp);
2170 sendBleStateChanged(prevState, newState);
2171
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002172 } else if (newState == BluetoothAdapter.STATE_BLE_TURNING_ON
2173 || newState == BluetoothAdapter.STATE_BLE_TURNING_OFF) {
Marie Janssencb21ad72016-12-13 10:51:02 -08002174 sendBleStateChanged(prevState, newState);
2175 isStandardBroadcast = false;
2176
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002177 } else if (newState == BluetoothAdapter.STATE_TURNING_ON
2178 || newState == BluetoothAdapter.STATE_TURNING_OFF) {
Marie Janssencb21ad72016-12-13 10:51:02 -08002179 sendBleStateChanged(prevState, newState);
2180 }
2181
2182 if (isStandardBroadcast) {
2183 if (prevState == BluetoothAdapter.STATE_BLE_ON) {
2184 // Show prevState of BLE_ON as OFF to standard users
2185 prevState = BluetoothAdapter.STATE_OFF;
2186 }
2187 Intent intent = new Intent(BluetoothAdapter.ACTION_STATE_CHANGED);
2188 intent.putExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE, prevState);
2189 intent.putExtra(BluetoothAdapter.EXTRA_STATE, newState);
2190 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
2191 mContext.sendBroadcastAsUser(intent, UserHandle.ALL, BLUETOOTH_PERM);
Zhihai Xu40874a02012-10-08 17:57:03 -07002192 }
2193 }
2194
2195 /**
2196 * if on is true, wait for state become ON
2197 * if off is true, wait for state become OFF
2198 * if both on and off are false, wait for state not ON
2199 */
2200 private boolean waitForOnOff(boolean on, boolean off) {
2201 int i = 0;
2202 while (i < 10) {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07002203 try {
2204 mBluetoothLock.readLock().lock();
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002205 if (mBluetooth == null) {
2206 break;
2207 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07002208 if (on) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002209 if (mBluetooth.getState() == BluetoothAdapter.STATE_ON) {
2210 return true;
2211 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07002212 } else if (off) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002213 if (mBluetooth.getState() == BluetoothAdapter.STATE_OFF) {
2214 return true;
2215 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07002216 } else {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002217 if (mBluetooth.getState() != BluetoothAdapter.STATE_ON) {
2218 return true;
2219 }
Zhihai Xu40874a02012-10-08 17:57:03 -07002220 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07002221 } catch (RemoteException e) {
2222 Slog.e(TAG, "getState()", e);
2223 break;
2224 } finally {
2225 mBluetoothLock.readLock().unlock();
Zhihai Xu40874a02012-10-08 17:57:03 -07002226 }
2227 if (on || off) {
2228 SystemClock.sleep(300);
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07002229 } else {
Zhihai Xu40874a02012-10-08 17:57:03 -07002230 SystemClock.sleep(50);
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07002231 }
Zhihai Xu40874a02012-10-08 17:57:03 -07002232 i++;
2233 }
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002234 Slog.e(TAG, "waitForOnOff time out");
Zhihai Xu40874a02012-10-08 17:57:03 -07002235 return false;
2236 }
Zhihai Xu681ae7f2012-11-12 15:14:18 -08002237
Jack He8caab152018-03-02 13:08:36 -08002238 private void sendDisableMsg(int reason, String packageName) {
Zhihai Xu401202b2012-12-03 11:36:21 -08002239 mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_DISABLE));
Jack He8caab152018-03-02 13:08:36 -08002240 addActiveLog(reason, packageName, false);
Zhihai Xu401202b2012-12-03 11:36:21 -08002241 }
2242
Jack He8caab152018-03-02 13:08:36 -08002243 private void sendEnableMsg(boolean quietMode, int reason, String packageName) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002244 mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_ENABLE, quietMode ? 1 : 0, 0));
Jack He8caab152018-03-02 13:08:36 -08002245 addActiveLog(reason, packageName, true);
Marie Janssen12a35012017-06-26 07:21:03 -07002246 mLastEnabledTime = SystemClock.elapsedRealtime();
Marie Janssen59804562016-12-28 14:13:21 -08002247 }
2248
Jack He8caab152018-03-02 13:08:36 -08002249 private void addActiveLog(int reason, String packageName, boolean enable) {
Marie Janssen59804562016-12-28 14:13:21 -08002250 synchronized (mActiveLogs) {
Marie Janssene54b4222017-03-16 18:10:59 -07002251 if (mActiveLogs.size() > ACTIVE_LOG_MAX_SIZE) {
Marie Janssen59804562016-12-28 14:13:21 -08002252 mActiveLogs.remove();
2253 }
Jack He8caab152018-03-02 13:08:36 -08002254 mActiveLogs.add(
2255 new ActiveLog(reason, packageName, enable, System.currentTimeMillis()));
Marie Janssen59804562016-12-28 14:13:21 -08002256 }
Tej Singhd8e7cc62018-03-22 18:30:31 +00002257
2258 int state = enable ? StatsLog.BLUETOOTH_ENABLED_STATE_CHANGED__STATE__ENABLED :
2259 StatsLog.BLUETOOTH_ENABLED_STATE_CHANGED__STATE__DISABLED;
2260 StatsLog.write_non_chained(StatsLog.BLUETOOTH_ENABLED_STATE_CHANGED,
2261 Binder.getCallingUid(), null, state, reason, packageName);
Zhihai Xu401202b2012-12-03 11:36:21 -08002262 }
2263
Marie Janssene54b4222017-03-16 18:10:59 -07002264 private void addCrashLog() {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002265 synchronized (mCrashTimestamps) {
2266 if (mCrashTimestamps.size() == CRASH_LOG_MAX_SIZE) {
2267 mCrashTimestamps.removeFirst();
2268 }
2269 mCrashTimestamps.add(System.currentTimeMillis());
2270 mCrashes++;
2271 }
Marie Janssene54b4222017-03-16 18:10:59 -07002272 }
2273
Marie Janssen2977c3e2016-11-09 12:01:24 -08002274 private void recoverBluetoothServiceFromError(boolean clearBle) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002275 Slog.e(TAG, "recoverBluetoothServiceFromError");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07002276 try {
2277 mBluetoothLock.readLock().lock();
Zhihai Xudd9d17d2013-01-08 17:05:58 -08002278 if (mBluetooth != null) {
2279 //Unregister callback object
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07002280 mBluetooth.unregisterCallback(mBluetoothCallback);
Zhihai Xudd9d17d2013-01-08 17:05:58 -08002281 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07002282 } catch (RemoteException re) {
2283 Slog.e(TAG, "Unable to unregister", re);
2284 } finally {
2285 mBluetoothLock.readLock().unlock();
Zhihai Xudd9d17d2013-01-08 17:05:58 -08002286 }
2287
2288 SystemClock.sleep(500);
2289
2290 // disable
Jack He8caab152018-03-02 13:08:36 -08002291 addActiveLog(BluetoothProtoEnums.ENABLE_DISABLE_REASON_START_ERROR,
2292 mContext.getPackageName(), false);
Zhihai Xudd9d17d2013-01-08 17:05:58 -08002293 handleDisable();
2294
2295 waitForOnOff(false, true);
2296
2297 sendBluetoothServiceDownCallback();
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07002298
Pavlin Radoslavove957a8a2016-05-24 15:28:41 -07002299 try {
2300 mBluetoothLock.writeLock().lock();
2301 if (mBluetooth != null) {
2302 mBluetooth = null;
2303 // Unbind
2304 mContext.unbindService(mConnection);
2305 }
2306 mBluetoothGatt = null;
2307 } finally {
2308 mBluetoothLock.writeLock().unlock();
Zhihai Xudd9d17d2013-01-08 17:05:58 -08002309 }
2310
2311 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
2312 mState = BluetoothAdapter.STATE_OFF;
2313
Marie Janssen2977c3e2016-11-09 12:01:24 -08002314 if (clearBle) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002315 clearBleApps();
Marie Janssen2977c3e2016-11-09 12:01:24 -08002316 }
2317
Zhihai Xudd9d17d2013-01-08 17:05:58 -08002318 mEnable = false;
2319
2320 if (mErrorRecoveryRetryCounter++ < MAX_ERROR_RESTART_RETRIES) {
2321 // Send a Bluetooth Restart message to reenable bluetooth
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002322 Message restartMsg = mHandler.obtainMessage(MESSAGE_RESTART_BLUETOOTH_SERVICE);
Zhihai Xudd9d17d2013-01-08 17:05:58 -08002323 mHandler.sendMessageDelayed(restartMsg, ERROR_RESTART_TIME_MS);
2324 } else {
2325 // todo: notify user to power down and power up phone to make bluetooth work.
2326 }
2327 }
Mike Lockwood726d4de2014-10-28 14:06:28 -07002328
Lenka Trochtova63d5e4a72016-12-02 12:19:39 +01002329 private boolean isBluetoothDisallowed() {
2330 long callingIdentity = Binder.clearCallingIdentity();
2331 try {
2332 return mContext.getSystemService(UserManager.class)
2333 .hasUserRestriction(UserManager.DISALLOW_BLUETOOTH, UserHandle.SYSTEM);
2334 } finally {
2335 Binder.restoreCallingIdentity(callingIdentity);
2336 }
2337 }
2338
Lenka Trochtovac6f0e232017-01-17 10:35:49 +01002339 /**
2340 * Disables BluetoothOppLauncherActivity component, so the Bluetooth sharing option is not
Pavel Grafov4f4f6f82017-03-28 13:44:04 +01002341 * offered to the user if Bluetooth or sharing is disallowed. Puts the component to its default
2342 * state if Bluetooth is not disallowed.
Lenka Trochtovac6f0e232017-01-17 10:35:49 +01002343 *
Pavel Grafov4f4f6f82017-03-28 13:44:04 +01002344 * @param userId user to disable bluetooth sharing for.
2345 * @param bluetoothSharingDisallowed whether bluetooth sharing is disallowed.
Lenka Trochtovac6f0e232017-01-17 10:35:49 +01002346 */
Pavel Grafov4f4f6f82017-03-28 13:44:04 +01002347 private void updateOppLauncherComponentState(int userId, boolean bluetoothSharingDisallowed) {
Lenka Trochtovac6f0e232017-01-17 10:35:49 +01002348 final ComponentName oppLauncherComponent = new ComponentName("com.android.bluetooth",
2349 "com.android.bluetooth.opp.BluetoothOppLauncherActivity");
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002350 final int newState =
2351 bluetoothSharingDisallowed ? PackageManager.COMPONENT_ENABLED_STATE_DISABLED
2352 : PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
Lenka Trochtovac6f0e232017-01-17 10:35:49 +01002353 try {
Pavel Grafov4f4f6f82017-03-28 13:44:04 +01002354 final IPackageManager imp = AppGlobals.getPackageManager();
Myles Watson6291fae2017-06-29 03:12:02 -07002355 imp.setComponentEnabledSetting(oppLauncherComponent, newState,
2356 PackageManager.DONT_KILL_APP, userId);
Lenka Trochtovac6f0e232017-01-17 10:35:49 +01002357 } catch (Exception e) {
2358 // The component was not found, do nothing.
2359 }
2360 }
2361
Mike Lockwood726d4de2014-10-28 14:06:28 -07002362 @Override
Pavlin Radoslavov6e8faff2016-02-23 11:54:37 -08002363 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002364 if (!DumpUtils.checkDumpPermission(mContext, TAG, writer)) {
2365 return;
2366 }
Pavlin Radoslavov6e8faff2016-02-23 11:54:37 -08002367 String errorMsg = null;
Marie Janssen59804562016-12-28 14:13:21 -08002368
2369 boolean protoOut = (args.length > 0) && args[0].startsWith("--proto");
2370
2371 if (!protoOut) {
2372 writer.println("Bluetooth Status");
2373 writer.println(" enabled: " + isEnabled());
2374 writer.println(" state: " + BluetoothAdapter.nameForState(mState));
2375 writer.println(" address: " + mAddress);
2376 writer.println(" name: " + mName);
2377 if (mEnable) {
Marie Janssen12a35012017-06-26 07:21:03 -07002378 long onDuration = SystemClock.elapsedRealtime() - mLastEnabledTime;
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002379 String onDurationString = String.format(Locale.US, "%02d:%02d:%02d.%03d",
2380 (int) (onDuration / (1000 * 60 * 60)),
2381 (int) ((onDuration / (1000 * 60)) % 60), (int) ((onDuration / 1000) % 60),
2382 (int) (onDuration % 1000));
Andre Eisenbache66e1682017-04-10 13:49:13 -07002383 writer.println(" time since enabled: " + onDurationString);
Marie Janssen59804562016-12-28 14:13:21 -08002384 }
2385
Marie Janssena95924d2017-01-18 09:37:52 -08002386 if (mActiveLogs.size() == 0) {
Andre Eisenbache66e1682017-04-10 13:49:13 -07002387 writer.println("\nBluetooth never enabled!");
Marie Janssena95924d2017-01-18 09:37:52 -08002388 } else {
Andre Eisenbache66e1682017-04-10 13:49:13 -07002389 writer.println("\nEnable log:");
Marie Janssena95924d2017-01-18 09:37:52 -08002390 for (ActiveLog log : mActiveLogs) {
2391 writer.println(" " + log);
2392 }
Marie Janssen59804562016-12-28 14:13:21 -08002393 }
2394
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002395 writer.println(
2396 "\nBluetooth crashed " + mCrashes + " time" + (mCrashes == 1 ? "" : "s"));
2397 if (mCrashes == CRASH_LOG_MAX_SIZE) {
2398 writer.println("(last " + CRASH_LOG_MAX_SIZE + ")");
2399 }
Marie Janssene54b4222017-03-16 18:10:59 -07002400 for (Long time : mCrashTimestamps) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002401 writer.println(" " + timeToLog(time));
Marie Janssene54b4222017-03-16 18:10:59 -07002402 }
2403
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002404 writer.println("\n" + mBleApps.size() + " BLE app" + (mBleApps.size() == 1 ? "" : "s")
2405 + "registered");
Marie Janssen59804562016-12-28 14:13:21 -08002406 for (ClientDeathRecipient app : mBleApps.values()) {
Marie Janssena95924d2017-01-18 09:37:52 -08002407 writer.println(" " + app.getPackageName());
Marie Janssen59804562016-12-28 14:13:21 -08002408 }
2409
Marie Janssena95924d2017-01-18 09:37:52 -08002410 writer.println("");
Marie Janssen59804562016-12-28 14:13:21 -08002411 writer.flush();
Marie Janssenf5ec5382017-01-03 11:37:38 -08002412 if (args.length == 0) {
Marie Janssena95924d2017-01-18 09:37:52 -08002413 // Add arg to produce output
2414 args = new String[1];
2415 args[0] = "--print";
Marie Janssenf5ec5382017-01-03 11:37:38 -08002416 }
Marie Janssen59804562016-12-28 14:13:21 -08002417 }
2418
Pavlin Radoslavov6e8faff2016-02-23 11:54:37 -08002419 if (mBluetoothBinder == null) {
2420 errorMsg = "Bluetooth Service not connected";
2421 } else {
2422 try {
2423 mBluetoothBinder.dump(fd, args);
2424 } catch (RemoteException re) {
Marie Janssen59804562016-12-28 14:13:21 -08002425 errorMsg = "RemoteException while dumping Bluetooth Service";
Pavlin Radoslavov6e8faff2016-02-23 11:54:37 -08002426 }
Mike Lockwood726d4de2014-10-28 14:06:28 -07002427 }
Pavlin Radoslavov6e8faff2016-02-23 11:54:37 -08002428 if (errorMsg != null) {
2429 // Silently return if we are extracting metrics in Protobuf format
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002430 if (protoOut) {
2431 return;
2432 }
Pavlin Radoslavov6e8faff2016-02-23 11:54:37 -08002433 writer.println(errorMsg);
2434 }
Mike Lockwood726d4de2014-10-28 14:06:28 -07002435 }
Jack He8caab152018-03-02 13:08:36 -08002436
2437 private static String getEnableDisableReasonString(int reason) {
2438 switch (reason) {
2439 case BluetoothProtoEnums.ENABLE_DISABLE_REASON_APPLICATION_REQUEST:
2440 return "APPLICATION_REQUEST";
2441 case BluetoothProtoEnums.ENABLE_DISABLE_REASON_AIRPLANE_MODE:
2442 return "AIRPLANE_MODE";
2443 case BluetoothProtoEnums.ENABLE_DISABLE_REASON_DISALLOWED:
2444 return "DISALLOWED";
2445 case BluetoothProtoEnums.ENABLE_DISABLE_REASON_RESTARTED:
2446 return "RESTARTED";
2447 case BluetoothProtoEnums.ENABLE_DISABLE_REASON_START_ERROR:
2448 return "START_ERROR";
2449 case BluetoothProtoEnums.ENABLE_DISABLE_REASON_SYSTEM_BOOT:
2450 return "SYSTEM_BOOT";
2451 case BluetoothProtoEnums.ENABLE_DISABLE_REASON_CRASH:
2452 return "CRASH";
2453 case BluetoothProtoEnums.ENABLE_DISABLE_REASON_USER_SWITCH:
2454 return "USER_SWITCH";
2455 case BluetoothProtoEnums.ENABLE_DISABLE_REASON_RESTORE_USER_SETTING:
2456 return "RESTORE_USER_SETTING";
2457 case BluetoothProtoEnums.ENABLE_DISABLE_REASON_UNSPECIFIED:
2458 default: return "UNKNOWN[" + reason + "]";
2459 }
2460 }
fredc0f420372012-04-12 00:02:00 -07002461}