blob: 02b1380715475a6484e3042c8c724679c1c2da2d [file] [log] [blame]
fredc0f420372012-04-12 00:02:00 -07001/*
Zhihai Xufa0fd392012-10-23 17:31:56 -07002 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
fredc0f420372012-04-12 00:02:00 -070015 */
16
17package com.android.server;
18
Svet Ganov408abf72015-05-12 19:13:36 -070019import android.Manifest;
Zhihai Xu40874a02012-10-08 17:57:03 -070020import android.app.ActivityManager;
Pavel Grafov4f4f6f82017-03-28 13:44:04 +010021import android.app.AppGlobals;
fredc0f420372012-04-12 00:02:00 -070022import android.bluetooth.BluetoothAdapter;
Benjamin Franze8b98922014-11-12 15:57:54 +000023import android.bluetooth.BluetoothProfile;
Jack He8caab152018-03-02 13:08:36 -080024import android.bluetooth.BluetoothProtoEnums;
fredc0f420372012-04-12 00:02:00 -070025import android.bluetooth.IBluetooth;
fredcbf072a72012-05-09 16:52:50 -070026import android.bluetooth.IBluetoothCallback;
Wei Wange4a744b2015-06-11 17:50:29 -070027import android.bluetooth.IBluetoothGatt;
Benjamin Franze8b98922014-11-12 15:57:54 +000028import android.bluetooth.IBluetoothHeadset;
fredc0f420372012-04-12 00:02:00 -070029import android.bluetooth.IBluetoothManager;
30import android.bluetooth.IBluetoothManagerCallback;
Benjamin Franze8b98922014-11-12 15:57:54 +000031import android.bluetooth.IBluetoothProfileServiceConnection;
fredc0f420372012-04-12 00:02:00 -070032import android.bluetooth.IBluetoothStateChangeCallback;
Svet Ganov77df6f32016-08-17 11:46:34 -070033import android.content.ActivityNotFoundException;
fredc0f420372012-04-12 00:02:00 -070034import android.content.BroadcastReceiver;
35import android.content.ComponentName;
36import android.content.ContentResolver;
37import android.content.Context;
38import android.content.Intent;
39import android.content.IntentFilter;
40import android.content.ServiceConnection;
Svetoslav Ganovac69be52016-06-29 17:31:44 -070041import android.content.pm.ApplicationInfo;
Pavel Grafov4f4f6f82017-03-28 13:44:04 +010042import android.content.pm.IPackageManager;
Matthew Xie32ab77b2013-05-08 19:26:57 -070043import android.content.pm.PackageManager;
Benjamin Franze8b98922014-11-12 15:57:54 +000044import android.content.pm.UserInfo;
Wei Wange4a744b2015-06-11 17:50:29 -070045import android.database.ContentObserver;
Zhihai Xu40874a02012-10-08 17:57:03 -070046import android.os.Binder;
Lenka Trochtova63d5e4a72016-12-02 12:19:39 +010047import android.os.Bundle;
fredc0f420372012-04-12 00:02:00 -070048import android.os.Handler;
fredc0f420372012-04-12 00:02:00 -070049import android.os.IBinder;
Zhihai Xu40874a02012-10-08 17:57:03 -070050import android.os.Looper;
fredc0f420372012-04-12 00:02:00 -070051import android.os.Message;
Zhihai Xu40874a02012-10-08 17:57:03 -070052import android.os.Process;
fredcd6883532012-04-25 17:46:13 -070053import android.os.RemoteCallbackList;
fredc0f420372012-04-12 00:02:00 -070054import android.os.RemoteException;
Zhihai Xu40874a02012-10-08 17:57:03 -070055import android.os.SystemClock;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070056import android.os.UserHandle;
Benjamin Franze8b98922014-11-12 15:57:54 +000057import android.os.UserManager;
Lenka Trochtova63d5e4a72016-12-02 12:19:39 +010058import android.os.UserManagerInternal;
59import android.os.UserManagerInternal.UserRestrictionsListener;
fredc0f420372012-04-12 00:02:00 -070060import android.provider.Settings;
Wei Wang67d84162015-04-26 17:04:29 -070061import android.provider.Settings.SettingNotFoundException;
Jeff Sharkey67609c72016-03-05 14:29:13 -070062import android.util.Slog;
Mike Lockwood726d4de2014-10-28 14:06:28 -070063
Arthur Hsuf3f95a92018-01-11 16:46:22 -080064import com.android.internal.R;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060065import com.android.internal.util.DumpUtils;
Pavel Grafov4f4f6f82017-03-28 13:44:04 +010066import com.android.server.pm.UserRestrictionsUtils;
Lenka Trochtovac6f0e232017-01-17 10:35:49 +010067
Mike Lockwood726d4de2014-10-28 14:06:28 -070068import java.io.FileDescriptor;
69import java.io.PrintWriter;
Benjamin Franze8b98922014-11-12 15:57:54 +000070import java.util.HashMap;
Marie Janssen59804562016-12-28 14:13:21 -080071import java.util.LinkedList;
Myles Watsonb5cd11a2017-11-27 16:42:11 -080072import java.util.Locale;
Benjamin Franze8b98922014-11-12 15:57:54 +000073import java.util.Map;
Pavel Grafov4f4f6f82017-03-28 13:44:04 +010074import java.util.concurrent.ConcurrentHashMap;
75import java.util.concurrent.locks.ReentrantReadWriteLock;
Miao Chou658bf2f2015-06-26 17:14:35 -070076
Marie Janssen59804562016-12-28 14:13:21 -080077
fredc0f420372012-04-12 00:02:00 -070078class BluetoothManagerService extends IBluetoothManager.Stub {
79 private static final String TAG = "BluetoothManagerService";
Pavlin Radoslavov41401112016-06-27 15:25:18 -070080 private static final boolean DBG = true;
fredc0f420372012-04-12 00:02:00 -070081
fredc0f420372012-04-12 00:02:00 -070082 private static final String BLUETOOTH_ADMIN_PERM = android.Manifest.permission.BLUETOOTH_ADMIN;
83 private static final String BLUETOOTH_PERM = android.Manifest.permission.BLUETOOTH;
Marie Janssene54b4222017-03-16 18:10:59 -070084
Myles Watsonb5cd11a2017-11-27 16:42:11 -080085 private static final String SECURE_SETTINGS_BLUETOOTH_ADDR_VALID = "bluetooth_addr_valid";
86 private static final String SECURE_SETTINGS_BLUETOOTH_ADDRESS = "bluetooth_address";
87 private static final String SECURE_SETTINGS_BLUETOOTH_NAME = "bluetooth_name";
Marie Janssene54b4222017-03-16 18:10:59 -070088
89 private static final int ACTIVE_LOG_MAX_SIZE = 20;
90 private static final int CRASH_LOG_MAX_SIZE = 100;
Marie Janssene54b4222017-03-16 18:10:59 -070091
fredc0f420372012-04-12 00:02:00 -070092 private static final int TIMEOUT_BIND_MS = 3000; //Maximum msec to wait for a bind
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +053093 //Maximum msec to wait for service restart
94 private static final int SERVICE_RESTART_TIME_MS = 200;
Zhihai Xudd9d17d2013-01-08 17:05:58 -080095 //Maximum msec to wait for restart due to error
96 private static final int ERROR_RESTART_TIME_MS = 3000;
Zhihai Xu40874a02012-10-08 17:57:03 -070097 //Maximum msec to delay MESSAGE_USER_SWITCHED
98 private static final int USER_SWITCHED_TIME_MS = 200;
Benjamin Franze8b98922014-11-12 15:57:54 +000099 // Delay for the addProxy function in msec
100 private static final int ADD_PROXY_DELAY_MS = 100;
fredc0f420372012-04-12 00:02:00 -0700101
102 private static final int MESSAGE_ENABLE = 1;
103 private static final int MESSAGE_DISABLE = 2;
fredc649fe492012-04-19 01:07:18 -0700104 private static final int MESSAGE_REGISTER_ADAPTER = 20;
105 private static final int MESSAGE_UNREGISTER_ADAPTER = 21;
106 private static final int MESSAGE_REGISTER_STATE_CHANGE_CALLBACK = 30;
107 private static final int MESSAGE_UNREGISTER_STATE_CHANGE_CALLBACK = 31;
108 private static final int MESSAGE_BLUETOOTH_SERVICE_CONNECTED = 40;
109 private static final int MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED = 41;
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +0530110 private static final int MESSAGE_RESTART_BLUETOOTH_SERVICE = 42;
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -0700111 private static final int MESSAGE_BLUETOOTH_STATE_CHANGE = 60;
112 private static final int MESSAGE_TIMEOUT_BIND = 100;
113 private static final int MESSAGE_TIMEOUT_UNBIND = 101;
Ajay Panicker4bb48302016-03-31 14:14:27 -0700114 private static final int MESSAGE_GET_NAME_AND_ADDRESS = 200;
Zhihai Xu40874a02012-10-08 17:57:03 -0700115 private static final int MESSAGE_USER_SWITCHED = 300;
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -0700116 private static final int MESSAGE_USER_UNLOCKED = 301;
Benjamin Franze8b98922014-11-12 15:57:54 +0000117 private static final int MESSAGE_ADD_PROXY_DELAYED = 400;
118 private static final int MESSAGE_BIND_PROFILE_SERVICE = 401;
Stanley Tng873b5702017-05-01 21:27:31 -0700119 private static final int MESSAGE_RESTORE_USER_SETTING = 500;
120
121 private static final int RESTORE_SETTING_TO_ON = 1;
122 private static final int RESTORE_SETTING_TO_OFF = 0;
Marie Janssencb21ad72016-12-13 10:51:02 -0800123
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -0700124 private static final int MAX_ERROR_RESTART_RETRIES = 6;
Zhihai Xudd9d17d2013-01-08 17:05:58 -0800125
Zhihai Xu401202b2012-12-03 11:36:21 -0800126 // Bluetooth persisted setting is off
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800127 private static final int BLUETOOTH_OFF = 0;
Zhihai Xu401202b2012-12-03 11:36:21 -0800128 // Bluetooth persisted setting is on
129 // and Airplane mode won't affect Bluetooth state at start up
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800130 private static final int BLUETOOTH_ON_BLUETOOTH = 1;
Zhihai Xu401202b2012-12-03 11:36:21 -0800131 // Bluetooth persisted setting is on
132 // but Airplane mode will affect Bluetooth state at start up
133 // and Airplane mode will have higher priority.
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800134 private static final int BLUETOOTH_ON_AIRPLANE = 2;
fredc0f420372012-04-12 00:02:00 -0700135
Matthew Xieddf7e472013-03-01 18:41:02 -0800136 private static final int SERVICE_IBLUETOOTH = 1;
137 private static final int SERVICE_IBLUETOOTHGATT = 2;
138
fredc0f420372012-04-12 00:02:00 -0700139 private final Context mContext;
Matthew Xiecdce0b92012-07-12 19:06:15 -0700140
141 // Locks are not provided for mName and mAddress.
142 // They are accessed in handler or broadcast receiver, same thread context.
fredc0f420372012-04-12 00:02:00 -0700143 private String mAddress;
144 private String mName;
Matthew Xie6fde3092012-07-11 17:10:07 -0700145 private final ContentResolver mContentResolver;
146 private final RemoteCallbackList<IBluetoothManagerCallback> mCallbacks;
147 private final RemoteCallbackList<IBluetoothStateChangeCallback> mStateChangeCallbacks;
Marie Janssen9db28eb2016-01-12 16:05:15 -0800148 private IBinder mBluetoothBinder;
fredc649fe492012-04-19 01:07:18 -0700149 private IBluetooth mBluetooth;
Matthew Xieddf7e472013-03-01 18:41:02 -0800150 private IBluetoothGatt mBluetoothGatt;
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800151 private final ReentrantReadWriteLock mBluetoothLock = new ReentrantReadWriteLock();
fredc649fe492012-04-19 01:07:18 -0700152 private boolean mBinding;
153 private boolean mUnbinding;
Marie Janssen59804562016-12-28 14:13:21 -0800154
Zhihai Xu401202b2012-12-03 11:36:21 -0800155 // used inside handler thread
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700156 private boolean mQuietEnable = false;
Marie Janssen59804562016-12-28 14:13:21 -0800157 private boolean mEnable;
158
Jack He8caab152018-03-02 13:08:36 -0800159 private static CharSequence timeToLog(long timestamp) {
Marie Janssene54b4222017-03-16 18:10:59 -0700160 return android.text.format.DateFormat.format("MM-dd HH:mm:ss", timestamp);
161 }
162
Marie Janssen59804562016-12-28 14:13:21 -0800163 /**
164 * Used for tracking apps that enabled / disabled Bluetooth.
165 */
166 private class ActiveLog {
Jack He8caab152018-03-02 13:08:36 -0800167 private int mReason;
Marie Janssen59804562016-12-28 14:13:21 -0800168 private String mPackageName;
169 private boolean mEnable;
170 private long mTimestamp;
171
Jack He8caab152018-03-02 13:08:36 -0800172 ActiveLog(int reason, String packageName, boolean enable, long timestamp) {
173 mReason = reason;
Marie Janssen59804562016-12-28 14:13:21 -0800174 mPackageName = packageName;
175 mEnable = enable;
176 mTimestamp = timestamp;
177 }
178
Marie Janssen59804562016-12-28 14:13:21 -0800179 public String toString() {
Jack He8caab152018-03-02 13:08:36 -0800180 return timeToLog(mTimestamp) + (mEnable ? " Enabled " : " Disabled ")
181 + " due to " + getEnableDisableReasonString(mReason) + " by " + mPackageName;
Marie Janssen59804562016-12-28 14:13:21 -0800182 }
183
184 }
185
Jack He8caab152018-03-02 13:08:36 -0800186 private final LinkedList<ActiveLog> mActiveLogs = new LinkedList<>();
187 private final LinkedList<Long> mCrashTimestamps = new LinkedList<>();
Marie Janssene54b4222017-03-16 18:10:59 -0700188 private int mCrashes;
Marie Janssen12a35012017-06-26 07:21:03 -0700189 private long mLastEnabledTime;
Marie Janssen59804562016-12-28 14:13:21 -0800190
191 // configuration from external IBinder call which is used to
Zhihai Xu401202b2012-12-03 11:36:21 -0800192 // synchronize with broadcast receiver.
193 private boolean mQuietEnableExternal;
Zhihai Xu401202b2012-12-03 11:36:21 -0800194 private boolean mEnableExternal;
Marie Janssen59804562016-12-28 14:13:21 -0800195
196 // Map of apps registered to keep BLE scanning on.
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800197 private Map<IBinder, ClientDeathRecipient> mBleApps =
198 new ConcurrentHashMap<IBinder, ClientDeathRecipient>();
Marie Janssen59804562016-12-28 14:13:21 -0800199
Zhihai Xu40874a02012-10-08 17:57:03 -0700200 private int mState;
Zhihai Xu40874a02012-10-08 17:57:03 -0700201 private final BluetoothHandler mHandler;
Zhihai Xudd9d17d2013-01-08 17:05:58 -0800202 private int mErrorRecoveryRetryCounter;
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200203 private final int mSystemUiUid;
fredc0f420372012-04-12 00:02:00 -0700204
Benjamin Franze8b98922014-11-12 15:57:54 +0000205 // Save a ProfileServiceConnections object for each of the bound
206 // bluetooth profile services
Jack He8caab152018-03-02 13:08:36 -0800207 private final Map<Integer, ProfileServiceConnections> mProfileServices = new HashMap<>();
Benjamin Franze8b98922014-11-12 15:57:54 +0000208
Svetoslav Ganovac69be52016-06-29 17:31:44 -0700209 private final boolean mPermissionReviewRequired;
210
Marie Janssen59804562016-12-28 14:13:21 -0800211 private final IBluetoothCallback mBluetoothCallback = new IBluetoothCallback.Stub() {
fredcbf072a72012-05-09 16:52:50 -0700212 @Override
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800213 public void onBluetoothStateChange(int prevState, int newState) throws RemoteException {
214 Message msg =
215 mHandler.obtainMessage(MESSAGE_BLUETOOTH_STATE_CHANGE, prevState, newState);
fredcbf072a72012-05-09 16:52:50 -0700216 mHandler.sendMessage(msg);
217 }
218 };
219
Lenka Trochtova63d5e4a72016-12-02 12:19:39 +0100220 private final UserRestrictionsListener mUserRestrictionsListener =
221 new UserRestrictionsListener() {
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800222 @Override
223 public void onUserRestrictionsChanged(int userId, Bundle newRestrictions,
224 Bundle prevRestrictions) {
Myles Watson6291fae2017-06-29 03:12:02 -0700225
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800226 if (UserRestrictionsUtils.restrictionsChanged(prevRestrictions, newRestrictions,
227 UserManager.DISALLOW_BLUETOOTH_SHARING)) {
228 updateOppLauncherComponentState(userId,
229 newRestrictions.getBoolean(UserManager.DISALLOW_BLUETOOTH_SHARING));
230 }
Pavel Grafov4f4f6f82017-03-28 13:44:04 +0100231
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800232 // DISALLOW_BLUETOOTH can only be set by DO or PO on the system user.
233 if (userId == UserHandle.USER_SYSTEM
234 && UserRestrictionsUtils.restrictionsChanged(prevRestrictions,
235 newRestrictions, UserManager.DISALLOW_BLUETOOTH)) {
236 if (userId == UserHandle.USER_SYSTEM && newRestrictions.getBoolean(
237 UserManager.DISALLOW_BLUETOOTH)) {
238 updateOppLauncherComponentState(userId, true); // Sharing disallowed
Jack He8caab152018-03-02 13:08:36 -0800239 sendDisableMsg(BluetoothProtoEnums.ENABLE_DISABLE_REASON_DISALLOWED,
240 mContext.getPackageName());
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800241 } else {
242 updateOppLauncherComponentState(userId, newRestrictions.getBoolean(
243 UserManager.DISALLOW_BLUETOOTH_SHARING));
244 }
245 }
Lenka Trochtova63d5e4a72016-12-02 12:19:39 +0100246 }
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800247 };
Lenka Trochtova63d5e4a72016-12-02 12:19:39 +0100248
Ajay Panicker467bc042017-02-22 12:23:15 -0800249 private final ContentObserver mAirplaneModeObserver = new ContentObserver(null) {
250 @Override
251 public void onChange(boolean unused) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800252 synchronized (this) {
Ajay Panicker467bc042017-02-22 12:23:15 -0800253 if (isBluetoothPersistedStateOn()) {
254 if (isAirplaneModeOn()) {
255 persistBluetoothSetting(BLUETOOTH_ON_AIRPLANE);
256 } else {
257 persistBluetoothSetting(BLUETOOTH_ON_BLUETOOTH);
258 }
259 }
260
261 int st = BluetoothAdapter.STATE_OFF;
262 try {
263 mBluetoothLock.readLock().lock();
264 if (mBluetooth != null) {
265 st = mBluetooth.getState();
266 }
267 } catch (RemoteException e) {
268 Slog.e(TAG, "Unable to call getState", e);
269 return;
270 } finally {
271 mBluetoothLock.readLock().unlock();
272 }
273
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800274 Slog.d(TAG,
275 "Airplane Mode change - current state: " + BluetoothAdapter.nameForState(
276 st));
Ajay Panicker467bc042017-02-22 12:23:15 -0800277
278 if (isAirplaneModeOn()) {
279 // Clear registered LE apps to force shut-off
280 clearBleApps();
281
282 // If state is BLE_ON make sure we trigger disableBLE
283 if (st == BluetoothAdapter.STATE_BLE_ON) {
284 try {
285 mBluetoothLock.readLock().lock();
286 if (mBluetooth != null) {
287 mBluetooth.onBrEdrDown();
288 mEnable = false;
289 mEnableExternal = false;
290 }
291 } catch (RemoteException e) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800292 Slog.e(TAG, "Unable to call onBrEdrDown", e);
Ajay Panicker467bc042017-02-22 12:23:15 -0800293 } finally {
294 mBluetoothLock.readLock().unlock();
295 }
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800296 } else if (st == BluetoothAdapter.STATE_ON) {
Jack He8caab152018-03-02 13:08:36 -0800297 sendDisableMsg(BluetoothProtoEnums.ENABLE_DISABLE_REASON_AIRPLANE_MODE,
298 mContext.getPackageName());
Ajay Panicker467bc042017-02-22 12:23:15 -0800299 }
300 } else if (mEnableExternal) {
Jack He8caab152018-03-02 13:08:36 -0800301 sendEnableMsg(mQuietEnableExternal,
302 BluetoothProtoEnums.ENABLE_DISABLE_REASON_AIRPLANE_MODE,
303 mContext.getPackageName());
Ajay Panicker467bc042017-02-22 12:23:15 -0800304 }
305 }
306 }
307 };
308
fredcbf072a72012-05-09 16:52:50 -0700309 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
fredc0f420372012-04-12 00:02:00 -0700310 @Override
311 public void onReceive(Context context, Intent intent) {
312 String action = intent.getAction();
fredcbf072a72012-05-09 16:52:50 -0700313 if (BluetoothAdapter.ACTION_LOCAL_NAME_CHANGED.equals(action)) {
fredc0f420372012-04-12 00:02:00 -0700314 String newName = intent.getStringExtra(BluetoothAdapter.EXTRA_LOCAL_NAME);
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800315 if (DBG) {
316 Slog.d(TAG, "Bluetooth Adapter name changed to " + newName);
317 }
fredc0f420372012-04-12 00:02:00 -0700318 if (newName != null) {
319 storeNameAndAddress(newName, null);
320 }
Stanley Tngdd749b02017-04-17 22:35:45 -0700321 } else if (BluetoothAdapter.ACTION_BLUETOOTH_ADDRESS_CHANGED.equals(action)) {
322 String newAddress = intent.getStringExtra(BluetoothAdapter.EXTRA_BLUETOOTH_ADDRESS);
323 if (newAddress != null) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800324 if (DBG) {
325 Slog.d(TAG, "Bluetooth Adapter address changed to " + newAddress);
326 }
Stanley Tngdd749b02017-04-17 22:35:45 -0700327 storeNameAndAddress(null, newAddress);
328 } else {
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800329 if (DBG) {
330 Slog.e(TAG, "No Bluetooth Adapter address parameter found");
331 }
Stanley Tngdd749b02017-04-17 22:35:45 -0700332 }
Stanley Tng873b5702017-05-01 21:27:31 -0700333 } else if (Intent.ACTION_SETTING_RESTORED.equals(action)) {
334 final String name = intent.getStringExtra(Intent.EXTRA_SETTING_NAME);
335 if (Settings.Global.BLUETOOTH_ON.equals(name)) {
336 // The Bluetooth On state may be changed during system restore.
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800337 final String prevValue =
338 intent.getStringExtra(Intent.EXTRA_SETTING_PREVIOUS_VALUE);
339 final String newValue = intent.getStringExtra(Intent.EXTRA_SETTING_NEW_VALUE);
Stanley Tng873b5702017-05-01 21:27:31 -0700340
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800341 if (DBG) {
342 Slog.d(TAG,
343 "ACTION_SETTING_RESTORED with BLUETOOTH_ON, prevValue=" + prevValue
344 + ", newValue=" + newValue);
345 }
Stanley Tng873b5702017-05-01 21:27:31 -0700346
347 if ((newValue != null) && (prevValue != null) && !prevValue.equals(newValue)) {
348 Message msg = mHandler.obtainMessage(MESSAGE_RESTORE_USER_SETTING,
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800349 newValue.equals("0") ? RESTORE_SETTING_TO_OFF
350 : RESTORE_SETTING_TO_ON, 0);
Stanley Tng873b5702017-05-01 21:27:31 -0700351 mHandler.sendMessage(msg);
352 }
353 }
fredc0f420372012-04-12 00:02:00 -0700354 }
355 }
356 };
357
358 BluetoothManagerService(Context context) {
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700359 mHandler = new BluetoothHandler(IoThread.get().getLooper());
Zhihai Xu40874a02012-10-08 17:57:03 -0700360
fredc0f420372012-04-12 00:02:00 -0700361 mContext = context;
Svetoslav Ganovac69be52016-06-29 17:31:44 -0700362
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800363 mPermissionReviewRequired = context.getResources()
364 .getBoolean(com.android.internal.R.bool.config_permissionReviewRequired);
Svetoslav Ganovac69be52016-06-29 17:31:44 -0700365
Marie Janssene54b4222017-03-16 18:10:59 -0700366 mCrashes = 0;
fredc0f420372012-04-12 00:02:00 -0700367 mBluetooth = null;
Marie Janssen9db28eb2016-01-12 16:05:15 -0800368 mBluetoothBinder = null;
Nitin Arorad055adb2015-03-02 15:03:51 -0800369 mBluetoothGatt = null;
fredc0f420372012-04-12 00:02:00 -0700370 mBinding = false;
371 mUnbinding = false;
Zhihai Xu40874a02012-10-08 17:57:03 -0700372 mEnable = false;
373 mState = BluetoothAdapter.STATE_OFF;
Zhihai Xu401202b2012-12-03 11:36:21 -0800374 mQuietEnableExternal = false;
375 mEnableExternal = false;
fredc0f420372012-04-12 00:02:00 -0700376 mAddress = null;
377 mName = null;
Zhihai Xudd9d17d2013-01-08 17:05:58 -0800378 mErrorRecoveryRetryCounter = 0;
fredc0f420372012-04-12 00:02:00 -0700379 mContentResolver = context.getContentResolver();
Wei Wange4a744b2015-06-11 17:50:29 -0700380 // Observe BLE scan only mode settings change.
381 registerForBleScanModeChange();
fredcd6883532012-04-25 17:46:13 -0700382 mCallbacks = new RemoteCallbackList<IBluetoothManagerCallback>();
383 mStateChangeCallbacks = new RemoteCallbackList<IBluetoothStateChangeCallback>();
Stanley Tng873b5702017-05-01 21:27:31 -0700384
385 IntentFilter filter = new IntentFilter();
386 filter.addAction(BluetoothAdapter.ACTION_LOCAL_NAME_CHANGED);
387 filter.addAction(BluetoothAdapter.ACTION_BLUETOOTH_ADDRESS_CHANGED);
388 filter.addAction(Intent.ACTION_SETTING_RESTORED);
Dianne Hackbornd83a0962014-05-02 16:28:33 -0700389 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
Matthew Xie6fde3092012-07-11 17:10:07 -0700390 mContext.registerReceiver(mReceiver, filter);
Stanley Tng873b5702017-05-01 21:27:31 -0700391
fredc0f420372012-04-12 00:02:00 -0700392 loadStoredNameAndAddress();
Zhihai Xu401202b2012-12-03 11:36:21 -0800393 if (isBluetoothPersistedStateOn()) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800394 if (DBG) {
395 Slog.d(TAG, "Startup: Bluetooth persisted state is ON.");
396 }
Zhihai Xu401202b2012-12-03 11:36:21 -0800397 mEnableExternal = true;
fredc0f420372012-04-12 00:02:00 -0700398 }
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200399
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800400 String airplaneModeRadios =
401 Settings.Global.getString(mContentResolver, Settings.Global.AIRPLANE_MODE_RADIOS);
402 if (airplaneModeRadios == null || airplaneModeRadios.contains(
403 Settings.Global.RADIO_BLUETOOTH)) {
Ajay Panicker467bc042017-02-22 12:23:15 -0800404 mContentResolver.registerContentObserver(
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800405 Settings.Global.getUriFor(Settings.Global.AIRPLANE_MODE_ON), true,
406 mAirplaneModeObserver);
Ajay Panicker467bc042017-02-22 12:23:15 -0800407 }
408
Marie Janssen59804562016-12-28 14:13:21 -0800409 int systemUiUid = -1;
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200410 try {
Arthur Hsuf3f95a92018-01-11 16:46:22 -0800411 // Check if device is configured with no home screen, which implies no SystemUI.
412 boolean noHome = mContext.getResources().getBoolean(R.bool.config_noHomeScreen);
413 if (!noHome) {
414 systemUiUid = mContext.getPackageManager()
415 .getPackageUidAsUser("com.android.systemui", PackageManager.MATCH_SYSTEM_ONLY,
416 UserHandle.USER_SYSTEM);
417 }
418 Slog.d(TAG, "Detected SystemUiUid: " + Integer.toString(systemUiUid));
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200419 } catch (PackageManager.NameNotFoundException e) {
Joe LaPennaacddf2b2015-09-04 12:52:42 -0700420 // Some platforms, such as wearables do not have a system ui.
Jeff Sharkey67609c72016-03-05 14:29:13 -0700421 Slog.w(TAG, "Unable to resolve SystemUI's UID.", e);
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200422 }
Marie Janssen59804562016-12-28 14:13:21 -0800423 mSystemUiUid = systemUiUid;
fredc0f420372012-04-12 00:02:00 -0700424 }
425
fredc649fe492012-04-19 01:07:18 -0700426 /**
427 * Returns true if airplane mode is currently on
428 */
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800429 private boolean isAirplaneModeOn() {
Christopher Tatec09cdce2012-09-10 16:50:14 -0700430 return Settings.Global.getInt(mContext.getContentResolver(),
431 Settings.Global.AIRPLANE_MODE_ON, 0) == 1;
fredc649fe492012-04-19 01:07:18 -0700432 }
433
Arthur Hsu2433baf2018-01-11 11:05:11 -0800434 private boolean supportBluetoothPersistedState() {
435 return mContext.getResources().getBoolean(R.bool.config_supportBluetoothPersistedState);
436 }
437
fredc649fe492012-04-19 01:07:18 -0700438 /**
439 * Returns true if the Bluetooth saved state is "on"
440 */
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800441 private boolean isBluetoothPersistedStateOn() {
Arthur Hsu2433baf2018-01-11 11:05:11 -0800442 if (!supportBluetoothPersistedState()) {
443 return false;
444 }
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800445 int state = Settings.Global.getInt(mContentResolver, Settings.Global.BLUETOOTH_ON, -1);
446 if (DBG) {
447 Slog.d(TAG, "Bluetooth persisted state: " + state);
448 }
Marie Janssen9fa24912016-10-18 10:04:24 -0700449 return state != BLUETOOTH_OFF;
Zhihai Xu401202b2012-12-03 11:36:21 -0800450 }
451
452 /**
453 * Returns true if the Bluetooth saved state is BLUETOOTH_ON_BLUETOOTH
454 */
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800455 private boolean isBluetoothPersistedStateOnBluetooth() {
Arthur Hsu2433baf2018-01-11 11:05:11 -0800456 if (!supportBluetoothPersistedState()) {
457 return false;
458 }
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800459 return Settings.Global.getInt(mContentResolver, Settings.Global.BLUETOOTH_ON,
460 BLUETOOTH_ON_BLUETOOTH) == BLUETOOTH_ON_BLUETOOTH;
fredc649fe492012-04-19 01:07:18 -0700461 }
462
463 /**
464 * Save the Bluetooth on/off state
fredc649fe492012-04-19 01:07:18 -0700465 */
Zhihai Xu401202b2012-12-03 11:36:21 -0800466 private void persistBluetoothSetting(int value) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800467 if (DBG) {
468 Slog.d(TAG, "Persisting Bluetooth Setting: " + value);
469 }
Marie Janssenfa630682016-12-15 13:51:30 -0800470 // waive WRITE_SECURE_SETTINGS permission check
471 long callingIdentity = Binder.clearCallingIdentity();
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800472 Settings.Global.putInt(mContext.getContentResolver(), Settings.Global.BLUETOOTH_ON, value);
Marie Janssenfa630682016-12-15 13:51:30 -0800473 Binder.restoreCallingIdentity(callingIdentity);
fredc649fe492012-04-19 01:07:18 -0700474 }
475
476 /**
477 * Returns true if the Bluetooth Adapter's name and address is
478 * locally cached
479 * @return
480 */
fredc0f420372012-04-12 00:02:00 -0700481 private boolean isNameAndAddressSet() {
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800482 return mName != null && mAddress != null && mName.length() > 0 && mAddress.length() > 0;
fredc0f420372012-04-12 00:02:00 -0700483 }
484
fredc649fe492012-04-19 01:07:18 -0700485 /**
486 * Retrieve the Bluetooth Adapter's name and address and save it in
487 * in the local cache
488 */
fredc0f420372012-04-12 00:02:00 -0700489 private void loadStoredNameAndAddress() {
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800490 if (DBG) {
491 Slog.d(TAG, "Loading stored name and address");
492 }
493 if (mContext.getResources()
494 .getBoolean(com.android.internal.R.bool.config_bluetooth_address_validation)
495 && Settings.Secure.getInt(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDR_VALID, 0)
496 == 0) {
Zhihai Xud31c3222012-10-31 16:08:57 -0700497 // if the valid flag is not set, don't load the address and name
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800498 if (DBG) {
499 Slog.d(TAG, "invalid bluetooth name and address stored");
500 }
Zhihai Xud31c3222012-10-31 16:08:57 -0700501 return;
502 }
fredc0f420372012-04-12 00:02:00 -0700503 mName = Settings.Secure.getString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_NAME);
504 mAddress = Settings.Secure.getString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDRESS);
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800505 if (DBG) {
506 Slog.d(TAG, "Stored bluetooth Name=" + mName + ",Address=" + mAddress);
507 }
fredc0f420372012-04-12 00:02:00 -0700508 }
509
fredc649fe492012-04-19 01:07:18 -0700510 /**
511 * Save the Bluetooth name and address in the persistent store.
512 * Only non-null values will be saved.
513 * @param name
514 * @param address
515 */
fredc0f420372012-04-12 00:02:00 -0700516 private void storeNameAndAddress(String name, String address) {
517 if (name != null) {
518 Settings.Secure.putString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_NAME, name);
fredc0f420372012-04-12 00:02:00 -0700519 mName = name;
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800520 if (DBG) {
521 Slog.d(TAG, "Stored Bluetooth name: " + Settings.Secure.getString(mContentResolver,
522 SECURE_SETTINGS_BLUETOOTH_NAME));
523 }
fredc0f420372012-04-12 00:02:00 -0700524 }
525
526 if (address != null) {
527 Settings.Secure.putString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDRESS, address);
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800528 mAddress = address;
529 if (DBG) {
530 Slog.d(TAG,
531 "Stored Bluetoothaddress: " + Settings.Secure.getString(mContentResolver,
532 SECURE_SETTINGS_BLUETOOTH_ADDRESS));
533 }
fredc0f420372012-04-12 00:02:00 -0700534 }
Zhihai Xud31c3222012-10-31 16:08:57 -0700535
536 if ((name != null) && (address != null)) {
537 Settings.Secure.putInt(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDR_VALID, 1);
538 }
fredc0f420372012-04-12 00:02:00 -0700539 }
540
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800541 public IBluetooth registerAdapter(IBluetoothManagerCallback callback) {
Natalie Silvanovich55db6462014-05-01 16:12:23 -0700542 if (callback == null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700543 Slog.w(TAG, "Callback is null in registerAdapter");
Natalie Silvanovich55db6462014-05-01 16:12:23 -0700544 return null;
545 }
fredc0f420372012-04-12 00:02:00 -0700546 Message msg = mHandler.obtainMessage(MESSAGE_REGISTER_ADAPTER);
547 msg.obj = callback;
548 mHandler.sendMessage(msg);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700549
550 return mBluetooth;
fredc0f420372012-04-12 00:02:00 -0700551 }
552
553 public void unregisterAdapter(IBluetoothManagerCallback callback) {
Natalie Silvanovich55db6462014-05-01 16:12:23 -0700554 if (callback == null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700555 Slog.w(TAG, "Callback is null in unregisterAdapter");
Natalie Silvanovich55db6462014-05-01 16:12:23 -0700556 return;
557 }
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800558 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");
fredc0f420372012-04-12 00:02:00 -0700559 Message msg = mHandler.obtainMessage(MESSAGE_UNREGISTER_ADAPTER);
560 msg.obj = callback;
561 mHandler.sendMessage(msg);
562 }
563
564 public void registerStateChangeCallback(IBluetoothStateChangeCallback callback) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800565 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");
Marie Janssencb21ad72016-12-13 10:51:02 -0800566 if (callback == null) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800567 Slog.w(TAG, "registerStateChangeCallback: Callback is null!");
568 return;
Marie Janssencb21ad72016-12-13 10:51:02 -0800569 }
fredc0f420372012-04-12 00:02:00 -0700570 Message msg = mHandler.obtainMessage(MESSAGE_REGISTER_STATE_CHANGE_CALLBACK);
571 msg.obj = callback;
572 mHandler.sendMessage(msg);
573 }
574
575 public void unregisterStateChangeCallback(IBluetoothStateChangeCallback callback) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800576 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");
Marie Janssencb21ad72016-12-13 10:51:02 -0800577 if (callback == null) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800578 Slog.w(TAG, "unregisterStateChangeCallback: Callback is null!");
579 return;
Marie Janssencb21ad72016-12-13 10:51:02 -0800580 }
fredc0f420372012-04-12 00:02:00 -0700581 Message msg = mHandler.obtainMessage(MESSAGE_UNREGISTER_STATE_CHANGE_CALLBACK);
582 msg.obj = callback;
583 mHandler.sendMessage(msg);
584 }
585
586 public boolean isEnabled() {
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800587 if ((Binder.getCallingUid() != Process.SYSTEM_UID) && (!checkIfCallerIsForegroundUser())) {
588 Slog.w(TAG, "isEnabled(): not allowed for non-active and non system user");
Zhihai Xu40874a02012-10-08 17:57:03 -0700589 return false;
590 }
591
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700592 try {
593 mBluetoothLock.readLock().lock();
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800594 if (mBluetooth != null) {
595 return mBluetooth.isEnabled();
596 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700597 } catch (RemoteException e) {
598 Slog.e(TAG, "isEnabled()", e);
599 } finally {
600 mBluetoothLock.readLock().unlock();
fredc0f420372012-04-12 00:02:00 -0700601 }
602 return false;
603 }
604
Christine Hallstrom995c90a2016-05-25 15:49:08 -0700605 public int getState() {
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800606 if ((Binder.getCallingUid() != Process.SYSTEM_UID) && (!checkIfCallerIsForegroundUser())) {
Marie Janssencb21ad72016-12-13 10:51:02 -0800607 Slog.w(TAG, "getState(): report OFF for non-active and non system user");
Christine Hallstrom995c90a2016-05-25 15:49:08 -0700608 return BluetoothAdapter.STATE_OFF;
609 }
610
611 try {
612 mBluetoothLock.readLock().lock();
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800613 if (mBluetooth != null) {
614 return mBluetooth.getState();
615 }
Christine Hallstrom995c90a2016-05-25 15:49:08 -0700616 } catch (RemoteException e) {
617 Slog.e(TAG, "getState()", e);
618 } finally {
619 mBluetoothLock.readLock().unlock();
620 }
621 return BluetoothAdapter.STATE_OFF;
622 }
623
Nitin Arorad055adb2015-03-02 15:03:51 -0800624 class ClientDeathRecipient implements IBinder.DeathRecipient {
Marie Janssen59804562016-12-28 14:13:21 -0800625 private String mPackageName;
626
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800627 ClientDeathRecipient(String packageName) {
Marie Janssen59804562016-12-28 14:13:21 -0800628 mPackageName = packageName;
629 }
630
Nitin Arorad055adb2015-03-02 15:03:51 -0800631 public void binderDied() {
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800632 if (DBG) {
633 Slog.d(TAG, "Binder is dead - unregister " + mPackageName);
Marie Janssen2977c3e2016-11-09 12:01:24 -0800634 }
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800635 if (isBleAppPresent()) {
636 // Nothing to do, another app is here.
637 return;
638 }
639 if (DBG) {
640 Slog.d(TAG, "Disabling LE only mode after application crash");
641 }
Marie Janssen2977c3e2016-11-09 12:01:24 -0800642 try {
643 mBluetoothLock.readLock().lock();
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800644 if (mBluetooth != null && mBluetooth.getState() == BluetoothAdapter.STATE_BLE_ON) {
Marie Janssen2977c3e2016-11-09 12:01:24 -0800645 mEnable = false;
646 mBluetooth.onBrEdrDown();
Nitin Arorad055adb2015-03-02 15:03:51 -0800647 }
Marie Janssen2977c3e2016-11-09 12:01:24 -0800648 } catch (RemoteException e) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800649 Slog.e(TAG, "Unable to call onBrEdrDown", e);
Marie Janssen2977c3e2016-11-09 12:01:24 -0800650 } finally {
651 mBluetoothLock.readLock().unlock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800652 }
653 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800654
Marie Janssen59804562016-12-28 14:13:21 -0800655 public String getPackageName() {
656 return mPackageName;
657 }
658 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800659
Wei Wang67d84162015-04-26 17:04:29 -0700660 @Override
661 public boolean isBleScanAlwaysAvailable() {
Marie Janssena80d7452016-10-25 10:47:51 -0700662 if (isAirplaneModeOn() && !mEnable) {
663 return false;
664 }
Wei Wang67d84162015-04-26 17:04:29 -0700665 try {
Jack He8caab152018-03-02 13:08:36 -0800666 return Settings.Global.getInt(mContentResolver,
667 Settings.Global.BLE_SCAN_ALWAYS_AVAILABLE) != 0;
Wei Wang67d84162015-04-26 17:04:29 -0700668 } catch (SettingNotFoundException e) {
669 }
670 return false;
671 }
672
Wei Wange4a744b2015-06-11 17:50:29 -0700673 // Monitor change of BLE scan only mode settings.
674 private void registerForBleScanModeChange() {
675 ContentObserver contentObserver = new ContentObserver(null) {
676 @Override
677 public void onChange(boolean selfChange) {
Marie Janssen2977c3e2016-11-09 12:01:24 -0800678 if (isBleScanAlwaysAvailable()) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800679 // Nothing to do
680 return;
Marie Janssen2977c3e2016-11-09 12:01:24 -0800681 }
682 // BLE scan is not available.
683 disableBleScanMode();
684 clearBleApps();
685 try {
686 mBluetoothLock.readLock().lock();
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800687 if (mBluetooth != null) {
688 mBluetooth.onBrEdrDown();
689 }
Marie Janssen2977c3e2016-11-09 12:01:24 -0800690 } catch (RemoteException e) {
691 Slog.e(TAG, "error when disabling bluetooth", e);
692 } finally {
693 mBluetoothLock.readLock().unlock();
Wei Wange4a744b2015-06-11 17:50:29 -0700694 }
695 }
696 };
697
698 mContentResolver.registerContentObserver(
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800699 Settings.Global.getUriFor(Settings.Global.BLE_SCAN_ALWAYS_AVAILABLE), false,
700 contentObserver);
Wei Wange4a744b2015-06-11 17:50:29 -0700701 }
702
703 // Disable ble scan only mode.
704 private void disableBleScanMode() {
705 try {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700706 mBluetoothLock.writeLock().lock();
Wei Wange4a744b2015-06-11 17:50:29 -0700707 if (mBluetooth != null && (mBluetooth.getState() != BluetoothAdapter.STATE_ON)) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800708 if (DBG) {
709 Slog.d(TAG, "Reseting the mEnable flag for clean disable");
710 }
Wei Wange4a744b2015-06-11 17:50:29 -0700711 mEnable = false;
712 }
713 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700714 Slog.e(TAG, "getState()", e);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700715 } finally {
716 mBluetoothLock.writeLock().unlock();
Wei Wange4a744b2015-06-11 17:50:29 -0700717 }
718 }
719
Marie Janssen59804562016-12-28 14:13:21 -0800720 public int updateBleAppCount(IBinder token, boolean enable, String packageName) {
721 ClientDeathRecipient r = mBleApps.get(token);
722 if (r == null && enable) {
723 ClientDeathRecipient deathRec = new ClientDeathRecipient(packageName);
724 try {
725 token.linkToDeath(deathRec, 0);
726 } catch (RemoteException ex) {
727 throw new IllegalArgumentException("BLE app (" + packageName + ") already dead!");
Nitin Arorad055adb2015-03-02 15:03:51 -0800728 }
Marie Janssen59804562016-12-28 14:13:21 -0800729 mBleApps.put(token, deathRec);
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800730 if (DBG) {
731 Slog.d(TAG, "Registered for death of " + packageName);
732 }
Marie Janssen59804562016-12-28 14:13:21 -0800733 } else if (!enable && r != null) {
734 // Unregister death recipient as the app goes away.
735 token.unlinkToDeath(r, 0);
736 mBleApps.remove(token);
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800737 if (DBG) {
738 Slog.d(TAG, "Unregistered for death of " + packageName);
739 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800740 }
Marie Janssen2977c3e2016-11-09 12:01:24 -0800741 int appCount = mBleApps.size();
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800742 if (DBG) {
743 Slog.d(TAG, appCount + " registered Ble Apps");
744 }
Marie Janssen2977c3e2016-11-09 12:01:24 -0800745 if (appCount == 0 && mEnable) {
Wei Wange4a744b2015-06-11 17:50:29 -0700746 disableBleScanMode();
Nitin Arorad055adb2015-03-02 15:03:51 -0800747 }
Martin Brabhamc2b06222017-02-27 16:55:07 -0800748 if (appCount == 0 && !mEnableExternal) {
749 sendBrEdrDownCallback();
750 }
Marie Janssen2977c3e2016-11-09 12:01:24 -0800751 return appCount;
Nitin Arorad055adb2015-03-02 15:03:51 -0800752 }
753
Wei Wange4a744b2015-06-11 17:50:29 -0700754 // Clear all apps using BLE scan only mode.
755 private void clearBleApps() {
Marie Janssen2977c3e2016-11-09 12:01:24 -0800756 mBleApps.clear();
Wei Wange4a744b2015-06-11 17:50:29 -0700757 }
758
Marie Janssen59804562016-12-28 14:13:21 -0800759 /** @hide */
Nitin Arorad055adb2015-03-02 15:03:51 -0800760 public boolean isBleAppPresent() {
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800761 if (DBG) {
762 Slog.d(TAG, "isBleAppPresent() count: " + mBleApps.size());
763 }
Marie Janssen2977c3e2016-11-09 12:01:24 -0800764 return mBleApps.size() > 0;
Nitin Arorad055adb2015-03-02 15:03:51 -0800765 }
766
767 /**
Marie Janssenfa630682016-12-15 13:51:30 -0800768 * Action taken when GattService is turned on
Nitin Arorad055adb2015-03-02 15:03:51 -0800769 */
770 private void onBluetoothGattServiceUp() {
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800771 if (DBG) {
772 Slog.d(TAG, "BluetoothGatt Service is Up");
773 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700774 try {
775 mBluetoothLock.readLock().lock();
Marie Janssenfa630682016-12-15 13:51:30 -0800776 if (mBluetooth == null) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800777 if (DBG) {
778 Slog.w(TAG, "onBluetoothServiceUp: mBluetooth is null!");
779 }
Marie Janssenfa630682016-12-15 13:51:30 -0800780 return;
781 }
782 int st = mBluetooth.getState();
783 if (st != BluetoothAdapter.STATE_BLE_ON) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800784 if (DBG) {
785 Slog.v(TAG, "onBluetoothServiceUp: state isn't BLE_ON: "
786 + BluetoothAdapter.nameForState(st));
787 }
Marie Janssenfa630682016-12-15 13:51:30 -0800788 return;
789 }
790 if (isBluetoothPersistedStateOnBluetooth() || !isBleAppPresent()) {
791 // This triggers transition to STATE_ON
Nitin Arorad055adb2015-03-02 15:03:51 -0800792 mBluetooth.onLeServiceUp();
Nitin Arorad055adb2015-03-02 15:03:51 -0800793 persistBluetoothSetting(BLUETOOTH_ON_BLUETOOTH);
Nitin Arorad055adb2015-03-02 15:03:51 -0800794 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700795 } catch (RemoteException e) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800796 Slog.e(TAG, "Unable to call onServiceUp", e);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700797 } finally {
798 mBluetoothLock.readLock().unlock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800799 }
800 }
801
802 /**
803 * Inform BluetoothAdapter instances that BREDR part is down
804 * and turn off all service and stack if no LE app needs it
805 */
806 private void sendBrEdrDownCallback() {
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800807 if (DBG) {
808 Slog.d(TAG, "Calling sendBrEdrDownCallback callbacks");
809 }
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700810
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700811 if (mBluetooth == null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700812 Slog.w(TAG, "Bluetooth handle is null");
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700813 return;
814 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800815
Martin Brabhamc2b06222017-02-27 16:55:07 -0800816 if (isBleAppPresent()) {
817 // Need to stay at BLE ON. Disconnect all Gatt connections
818 try {
819 mBluetoothGatt.unregAll();
820 } catch (RemoteException e) {
821 Slog.e(TAG, "Unable to disconnect all apps.", e);
822 }
823 } else {
Nitin Arorad055adb2015-03-02 15:03:51 -0800824 try {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700825 mBluetoothLock.readLock().lock();
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800826 if (mBluetooth != null) {
827 mBluetooth.onBrEdrDown();
828 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700829 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700830 Slog.e(TAG, "Call to onBrEdrDown() failed.", e);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700831 } finally {
832 mBluetoothLock.readLock().unlock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800833 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800834 }
Martin Brabhamc2b06222017-02-27 16:55:07 -0800835
Nitin Arorad055adb2015-03-02 15:03:51 -0800836 }
837
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800838 public boolean enableNoAutoConnect(String packageName) {
Lenka Trochtova63d5e4a72016-12-02 12:19:39 +0100839 if (isBluetoothDisallowed()) {
840 if (DBG) {
841 Slog.d(TAG, "enableNoAutoConnect(): not enabling - bluetooth disallowed");
842 }
843 return false;
844 }
845
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700846 mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800847 "Need BLUETOOTH ADMIN permission");
Zhihai Xu40874a02012-10-08 17:57:03 -0700848
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700849 if (DBG) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800850 Slog.d(TAG, "enableNoAutoConnect(): mBluetooth =" + mBluetooth + " mBinding = "
851 + mBinding);
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700852 }
Martijn Coenen8385c5a2012-11-29 10:14:16 -0800853 int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
854
855 if (callingAppId != Process.NFC_UID) {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700856 throw new SecurityException("no permission to enable Bluetooth quietly");
857 }
Martijn Coenen8385c5a2012-11-29 10:14:16 -0800858
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800859 synchronized (mReceiver) {
Zhihai Xu401202b2012-12-03 11:36:21 -0800860 mQuietEnableExternal = true;
861 mEnableExternal = true;
Jack He8caab152018-03-02 13:08:36 -0800862 sendEnableMsg(true,
863 BluetoothProtoEnums.ENABLE_DISABLE_REASON_APPLICATION_REQUEST, packageName);
Zhihai Xu401202b2012-12-03 11:36:21 -0800864 }
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700865 return true;
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700866 }
Ajay Panicker4bb48302016-03-31 14:14:27 -0700867
Svetoslav Ganovac69be52016-06-29 17:31:44 -0700868 public boolean enable(String packageName) throws RemoteException {
869 final int callingUid = Binder.getCallingUid();
870 final boolean callerSystem = UserHandle.getAppId(callingUid) == Process.SYSTEM_UID;
871
Lenka Trochtova63d5e4a72016-12-02 12:19:39 +0100872 if (isBluetoothDisallowed()) {
873 if (DBG) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800874 Slog.d(TAG, "enable(): not enabling - bluetooth disallowed");
Lenka Trochtova63d5e4a72016-12-02 12:19:39 +0100875 }
876 return false;
877 }
878
Svetoslav Ganovac69be52016-06-29 17:31:44 -0700879 if (!callerSystem) {
880 if (!checkIfCallerIsForegroundUser()) {
881 Slog.w(TAG, "enable(): not allowed for non-active and non system user");
882 return false;
883 }
884
885 mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
886 "Need BLUETOOTH ADMIN permission");
887
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800888 if (!isEnabled() && mPermissionReviewRequired && startConsentUiIfNeeded(packageName,
889 callingUid, BluetoothAdapter.ACTION_REQUEST_ENABLE)) {
Svetoslav Ganovac69be52016-06-29 17:31:44 -0700890 return false;
891 }
fredcf2458862012-04-16 15:18:27 -0700892 }
893
Zhihai Xu401202b2012-12-03 11:36:21 -0800894 if (DBG) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800895 Slog.d(TAG, "enable(" + packageName + "): mBluetooth =" + mBluetooth + " mBinding = "
896 + mBinding + " mState = " + BluetoothAdapter.nameForState(mState));
Sanket Agarwal090bf552016-04-21 14:10:55 -0700897 }
Zhihai Xu401202b2012-12-03 11:36:21 -0800898
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800899 synchronized (mReceiver) {
Zhihai Xu401202b2012-12-03 11:36:21 -0800900 mQuietEnableExternal = false;
901 mEnableExternal = true;
902 // waive WRITE_SECURE_SETTINGS permission check
Jack He8caab152018-03-02 13:08:36 -0800903 sendEnableMsg(false,
904 BluetoothProtoEnums.ENABLE_DISABLE_REASON_APPLICATION_REQUEST, packageName);
Zhihai Xu401202b2012-12-03 11:36:21 -0800905 }
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800906 if (DBG) {
907 Slog.d(TAG, "enable returning");
908 }
Zhihai Xu401202b2012-12-03 11:36:21 -0800909 return true;
fredc0f420372012-04-12 00:02:00 -0700910 }
911
Svetoslav Ganovac69be52016-06-29 17:31:44 -0700912 public boolean disable(String packageName, boolean persist) throws RemoteException {
913 final int callingUid = Binder.getCallingUid();
914 final boolean callerSystem = UserHandle.getAppId(callingUid) == Process.SYSTEM_UID;
Zhihai Xu40874a02012-10-08 17:57:03 -0700915
Svetoslav Ganovac69be52016-06-29 17:31:44 -0700916 if (!callerSystem) {
917 if (!checkIfCallerIsForegroundUser()) {
918 Slog.w(TAG, "disable(): not allowed for non-active and non system user");
919 return false;
920 }
921
922 mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
923 "Need BLUETOOTH ADMIN permission");
924
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800925 if (isEnabled() && mPermissionReviewRequired && startConsentUiIfNeeded(packageName,
926 callingUid, BluetoothAdapter.ACTION_REQUEST_DISABLE)) {
Svetoslav Ganovac69be52016-06-29 17:31:44 -0700927 return false;
928 }
Zhihai Xu40874a02012-10-08 17:57:03 -0700929 }
930
fredcf2458862012-04-16 15:18:27 -0700931 if (DBG) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800932 Slog.d(TAG, "disable(): mBluetooth = " + mBluetooth + " mBinding = " + mBinding);
Matthew Xiecdce0b92012-07-12 19:06:15 -0700933 }
fredcf2458862012-04-16 15:18:27 -0700934
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800935 synchronized (mReceiver) {
Zhihai Xu401202b2012-12-03 11:36:21 -0800936 if (persist) {
Zhihai Xu401202b2012-12-03 11:36:21 -0800937 persistBluetoothSetting(BLUETOOTH_OFF);
Zhihai Xu401202b2012-12-03 11:36:21 -0800938 }
939 mEnableExternal = false;
Jack He8caab152018-03-02 13:08:36 -0800940 sendDisableMsg(BluetoothProtoEnums.ENABLE_DISABLE_REASON_APPLICATION_REQUEST,
941 packageName);
Zhihai Xu401202b2012-12-03 11:36:21 -0800942 }
fredc0f420372012-04-12 00:02:00 -0700943 return true;
944 }
945
baishengf62d8692018-01-25 18:07:24 +0800946 private boolean startConsentUiIfNeeded(String packageName,
947 int callingUid, String intentAction) throws RemoteException {
948 if (checkBluetoothPermissionWhenPermissionReviewRequired()) {
949 return false;
950 }
Svetoslav Ganovac69be52016-06-29 17:31:44 -0700951 try {
952 // Validate the package only if we are going to use it
953 ApplicationInfo applicationInfo = mContext.getPackageManager()
954 .getApplicationInfoAsUser(packageName,
955 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
956 UserHandle.getUserId(callingUid));
957 if (applicationInfo.uid != callingUid) {
baishengf62d8692018-01-25 18:07:24 +0800958 throw new SecurityException("Package " + packageName
959 + " not in uid " + callingUid);
Svetoslav Ganovac69be52016-06-29 17:31:44 -0700960 }
961
Ivan Podogovd2d32b12016-12-05 16:46:52 +0000962 Intent intent = new Intent(intentAction);
Ivan Podogov1ab87252017-01-03 12:02:18 +0000963 intent.putExtra(Intent.EXTRA_PACKAGE_NAME, packageName);
Myles Watsonb5cd11a2017-11-27 16:42:11 -0800964 intent.setFlags(
965 Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
Ivan Podogov1ab87252017-01-03 12:02:18 +0000966 try {
967 mContext.startActivity(intent);
968 } catch (ActivityNotFoundException e) {
969 // Shouldn't happen
970 Slog.e(TAG, "Intent to handle action " + intentAction + " missing");
971 return false;
Svetoslav Ganovac69be52016-06-29 17:31:44 -0700972 }
Ivan Podogov1ab87252017-01-03 12:02:18 +0000973 return true;
Svetoslav Ganovac69be52016-06-29 17:31:44 -0700974 } catch (PackageManager.NameNotFoundException e) {
975 throw new RemoteException(e.getMessage());
976 }
Svetoslav Ganovac69be52016-06-29 17:31:44 -0700977 }
978
baishengf62d8692018-01-25 18:07:24 +0800979 /**
980 * Check if the caller must still pass permission check or if the caller is exempted
981 * from the consent UI via the MANAGE_BLUETOOTH_WHEN_PERMISSION_REVIEW_REQUIRED check.
982 *
983 * Commands from some callers may be exempted from triggering the consent UI when
984 * enabling bluetooth. This exemption is checked via the
985 * MANAGE_BLUETOOTH_WHEN_PERMISSION_REVIEW_REQUIRED and allows calls to skip
986 * the consent UI where it may otherwise be required.
987 *
988 * @hide
989 */
990 private boolean checkBluetoothPermissionWhenPermissionReviewRequired() {
991 if (!mPermissionReviewRequired) {
992 return false;
993 }
994 int result = mContext.checkCallingPermission(
995 android.Manifest.permission.MANAGE_BLUETOOTH_WHEN_PERMISSION_REVIEW_REQUIRED);
996 return result == PackageManager.PERMISSION_GRANTED;
997 }
998
fredc649fe492012-04-19 01:07:18 -0700999 public void unbindAndFinish() {
fredcf2458862012-04-16 15:18:27 -07001000 if (DBG) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001001 Slog.d(TAG, "unbindAndFinish(): " + mBluetooth + " mBinding = " + mBinding
1002 + " mUnbinding = " + mUnbinding);
fredcf2458862012-04-16 15:18:27 -07001003 }
1004
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001005 try {
1006 mBluetoothLock.writeLock().lock();
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001007 if (mUnbinding) {
1008 return;
1009 }
fredc0f420372012-04-12 00:02:00 -07001010 mUnbinding = true;
Pavlin Radoslavove47ec142016-06-01 22:25:18 -07001011 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
Pavlin Radoslavov74f60c02016-09-21 17:28:11 -07001012 mHandler.removeMessages(MESSAGE_BIND_PROFILE_SERVICE);
Zhihai Xu40874a02012-10-08 17:57:03 -07001013 if (mBluetooth != null) {
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001014 //Unregister callback object
1015 try {
1016 mBluetooth.unregisterCallback(mBluetoothCallback);
1017 } catch (RemoteException re) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001018 Slog.e(TAG, "Unable to unregister BluetoothCallback", re);
fredcbf072a72012-05-09 16:52:50 -07001019 }
Marie Janssen9db28eb2016-01-12 16:05:15 -08001020 mBluetoothBinder = null;
fredcd6883532012-04-25 17:46:13 -07001021 mBluetooth = null;
fredc0f420372012-04-12 00:02:00 -07001022 mContext.unbindService(mConnection);
fredcd6883532012-04-25 17:46:13 -07001023 mUnbinding = false;
Zhihai Xu40874a02012-10-08 17:57:03 -07001024 mBinding = false;
fredcf2458862012-04-16 15:18:27 -07001025 } else {
Marie Janssencb21ad72016-12-13 10:51:02 -08001026 mUnbinding = false;
fredc0f420372012-04-12 00:02:00 -07001027 }
Nitin Arorad055adb2015-03-02 15:03:51 -08001028 mBluetoothGatt = null;
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001029 } finally {
1030 mBluetoothLock.writeLock().unlock();
fredc0f420372012-04-12 00:02:00 -07001031 }
1032 }
1033
Matthew Xieddf7e472013-03-01 18:41:02 -08001034 public IBluetoothGatt getBluetoothGatt() {
1035 // sync protection
1036 return mBluetoothGatt;
1037 }
1038
Benjamin Franze8b98922014-11-12 15:57:54 +00001039 @Override
1040 public boolean bindBluetoothProfileService(int bluetoothProfile,
1041 IBluetoothProfileServiceConnection proxy) {
1042 if (!mEnable) {
1043 if (DBG) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001044 Slog.d(TAG, "Trying to bind to profile: " + bluetoothProfile
1045 + ", while Bluetooth was disabled");
Benjamin Franze8b98922014-11-12 15:57:54 +00001046 }
1047 return false;
1048 }
1049 synchronized (mProfileServices) {
1050 ProfileServiceConnections psc = mProfileServices.get(new Integer(bluetoothProfile));
1051 if (psc == null) {
1052 if (DBG) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001053 Slog.d(TAG, "Creating new ProfileServiceConnections object for" + " profile: "
1054 + bluetoothProfile);
Benjamin Franze8b98922014-11-12 15:57:54 +00001055 }
Benjamin Franz5b614592014-12-09 18:58:45 +00001056
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001057 if (bluetoothProfile != BluetoothProfile.HEADSET) {
1058 return false;
1059 }
Benjamin Franz5b614592014-12-09 18:58:45 +00001060
1061 Intent intent = new Intent(IBluetoothHeadset.class.getName());
Benjamin Franze8b98922014-11-12 15:57:54 +00001062 psc = new ProfileServiceConnections(intent);
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001063 if (!psc.bindService()) {
1064 return false;
1065 }
Benjamin Franz5b614592014-12-09 18:58:45 +00001066
Benjamin Franze8b98922014-11-12 15:57:54 +00001067 mProfileServices.put(new Integer(bluetoothProfile), psc);
Benjamin Franze8b98922014-11-12 15:57:54 +00001068 }
1069 }
1070
1071 // Introducing a delay to give the client app time to prepare
1072 Message addProxyMsg = mHandler.obtainMessage(MESSAGE_ADD_PROXY_DELAYED);
1073 addProxyMsg.arg1 = bluetoothProfile;
1074 addProxyMsg.obj = proxy;
1075 mHandler.sendMessageDelayed(addProxyMsg, ADD_PROXY_DELAY_MS);
1076 return true;
1077 }
1078
1079 @Override
1080 public void unbindBluetoothProfileService(int bluetoothProfile,
1081 IBluetoothProfileServiceConnection proxy) {
1082 synchronized (mProfileServices) {
1083 ProfileServiceConnections psc = mProfileServices.get(new Integer(bluetoothProfile));
1084 if (psc == null) {
1085 return;
1086 }
1087 psc.removeProxy(proxy);
1088 }
1089 }
1090
1091 private void unbindAllBluetoothProfileServices() {
1092 synchronized (mProfileServices) {
1093 for (Integer i : mProfileServices.keySet()) {
1094 ProfileServiceConnections psc = mProfileServices.get(i);
Benjamin Franz5b614592014-12-09 18:58:45 +00001095 try {
1096 mContext.unbindService(psc);
1097 } catch (IllegalArgumentException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001098 Slog.e(TAG, "Unable to unbind service with intent: " + psc.mIntent, e);
Benjamin Franz5b614592014-12-09 18:58:45 +00001099 }
Benjamin Franze8b98922014-11-12 15:57:54 +00001100 psc.removeAllProxies();
1101 }
1102 mProfileServices.clear();
1103 }
1104 }
1105
1106 /**
Miao Chou658bf2f2015-06-26 17:14:35 -07001107 * Send enable message and set adapter name and address. Called when the boot phase becomes
1108 * PHASE_SYSTEM_SERVICES_READY.
1109 */
1110 public void handleOnBootPhase() {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001111 if (DBG) {
1112 Slog.d(TAG, "Bluetooth boot completed");
1113 }
Lenka Trochtova63d5e4a72016-12-02 12:19:39 +01001114 UserManagerInternal userManagerInternal =
1115 LocalServices.getService(UserManagerInternal.class);
1116 userManagerInternal.addUserRestrictionsListener(mUserRestrictionsListener);
Lenka Trochtovac6f0e232017-01-17 10:35:49 +01001117 final boolean isBluetoothDisallowed = isBluetoothDisallowed();
Lenka Trochtovac6f0e232017-01-17 10:35:49 +01001118 if (isBluetoothDisallowed) {
Lenka Trochtova63d5e4a72016-12-02 12:19:39 +01001119 return;
1120 }
Miao Chou658bf2f2015-06-26 17:14:35 -07001121 if (mEnableExternal && isBluetoothPersistedStateOnBluetooth()) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001122 if (DBG) {
1123 Slog.d(TAG, "Auto-enabling Bluetooth.");
1124 }
Jack He8caab152018-03-02 13:08:36 -08001125 sendEnableMsg(mQuietEnableExternal,
1126 BluetoothProtoEnums.ENABLE_DISABLE_REASON_SYSTEM_BOOT,
1127 mContext.getPackageName());
Ajay Panickerbf796d82016-03-11 13:47:20 -08001128 } else if (!isNameAndAddressSet()) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001129 if (DBG) {
1130 Slog.d(TAG, "Getting adapter name and address");
1131 }
Ajay Panicker4bb48302016-03-31 14:14:27 -07001132 Message getMsg = mHandler.obtainMessage(MESSAGE_GET_NAME_AND_ADDRESS);
1133 mHandler.sendMessage(getMsg);
Miao Chou658bf2f2015-06-26 17:14:35 -07001134 }
Miao Chou658bf2f2015-06-26 17:14:35 -07001135 }
1136
1137 /**
1138 * Called when switching to a different foreground user.
1139 */
1140 public void handleOnSwitchUser(int userHandle) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001141 if (DBG) {
1142 Slog.d(TAG, "User " + userHandle + " switched");
1143 }
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001144 mHandler.obtainMessage(MESSAGE_USER_SWITCHED, userHandle, 0).sendToTarget();
1145 }
1146
1147 /**
1148 * Called when user is unlocked.
1149 */
1150 public void handleOnUnlockUser(int userHandle) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001151 if (DBG) {
1152 Slog.d(TAG, "User " + userHandle + " unlocked");
1153 }
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001154 mHandler.obtainMessage(MESSAGE_USER_UNLOCKED, userHandle, 0).sendToTarget();
Miao Chou658bf2f2015-06-26 17:14:35 -07001155 }
1156
1157 /**
Benjamin Franze8b98922014-11-12 15:57:54 +00001158 * This class manages the clients connected to a given ProfileService
1159 * and maintains the connection with that service.
1160 */
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001161 private final class ProfileServiceConnections
1162 implements ServiceConnection, IBinder.DeathRecipient {
Benjamin Franze8b98922014-11-12 15:57:54 +00001163 final RemoteCallbackList<IBluetoothProfileServiceConnection> mProxies =
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001164 new RemoteCallbackList<IBluetoothProfileServiceConnection>();
Benjamin Franze8b98922014-11-12 15:57:54 +00001165 IBinder mService;
1166 ComponentName mClassName;
1167 Intent mIntent;
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001168 boolean mInvokingProxyCallbacks = false;
Benjamin Franze8b98922014-11-12 15:57:54 +00001169
1170 ProfileServiceConnections(Intent intent) {
1171 mService = null;
1172 mClassName = null;
1173 mIntent = intent;
1174 }
1175
Benjamin Franz5b614592014-12-09 18:58:45 +00001176 private boolean bindService() {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001177 if (mIntent != null && mService == null && doBind(mIntent, this, 0,
1178 UserHandle.CURRENT_OR_SELF)) {
Benjamin Franze8b98922014-11-12 15:57:54 +00001179 Message msg = mHandler.obtainMessage(MESSAGE_BIND_PROFILE_SERVICE);
1180 msg.obj = this;
1181 mHandler.sendMessageDelayed(msg, TIMEOUT_BIND_MS);
Benjamin Franz5b614592014-12-09 18:58:45 +00001182 return true;
Benjamin Franze8b98922014-11-12 15:57:54 +00001183 }
Jeff Sharkey67609c72016-03-05 14:29:13 -07001184 Slog.w(TAG, "Unable to bind with intent: " + mIntent);
Benjamin Franz5b614592014-12-09 18:58:45 +00001185 return false;
Benjamin Franze8b98922014-11-12 15:57:54 +00001186 }
1187
1188 private void addProxy(IBluetoothProfileServiceConnection proxy) {
1189 mProxies.register(proxy);
1190 if (mService != null) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001191 try {
Benjamin Franze8b98922014-11-12 15:57:54 +00001192 proxy.onServiceConnected(mClassName, mService);
1193 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001194 Slog.e(TAG, "Unable to connect to proxy", e);
Benjamin Franze8b98922014-11-12 15:57:54 +00001195 }
1196 } else {
1197 if (!mHandler.hasMessages(MESSAGE_BIND_PROFILE_SERVICE, this)) {
1198 Message msg = mHandler.obtainMessage(MESSAGE_BIND_PROFILE_SERVICE);
1199 msg.obj = this;
1200 mHandler.sendMessage(msg);
1201 }
1202 }
1203 }
1204
1205 private void removeProxy(IBluetoothProfileServiceConnection proxy) {
1206 if (proxy != null) {
1207 if (mProxies.unregister(proxy)) {
1208 try {
1209 proxy.onServiceDisconnected(mClassName);
1210 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001211 Slog.e(TAG, "Unable to disconnect proxy", e);
Benjamin Franze8b98922014-11-12 15:57:54 +00001212 }
1213 }
1214 } else {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001215 Slog.w(TAG, "Trying to remove a null proxy");
Benjamin Franze8b98922014-11-12 15:57:54 +00001216 }
1217 }
1218
1219 private void removeAllProxies() {
1220 onServiceDisconnected(mClassName);
1221 mProxies.kill();
1222 }
1223
1224 @Override
1225 public void onServiceConnected(ComponentName className, IBinder service) {
1226 // remove timeout message
1227 mHandler.removeMessages(MESSAGE_BIND_PROFILE_SERVICE, this);
1228 mService = service;
1229 mClassName = className;
1230 try {
1231 mService.linkToDeath(this, 0);
1232 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001233 Slog.e(TAG, "Unable to linkToDeath", e);
Benjamin Franze8b98922014-11-12 15:57:54 +00001234 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001235
1236 if (mInvokingProxyCallbacks) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001237 Slog.e(TAG, "Proxy callbacks already in progress.");
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001238 return;
Benjamin Franze8b98922014-11-12 15:57:54 +00001239 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001240 mInvokingProxyCallbacks = true;
1241
1242 final int n = mProxies.beginBroadcast();
1243 try {
1244 for (int i = 0; i < n; i++) {
1245 try {
1246 mProxies.getBroadcastItem(i).onServiceConnected(className, service);
1247 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001248 Slog.e(TAG, "Unable to connect to proxy", e);
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001249 }
1250 }
1251 } finally {
1252 mProxies.finishBroadcast();
1253 mInvokingProxyCallbacks = false;
1254 }
Benjamin Franze8b98922014-11-12 15:57:54 +00001255 }
1256
1257 @Override
1258 public void onServiceDisconnected(ComponentName className) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001259 if (mService == null) {
1260 return;
1261 }
Benjamin Franze8b98922014-11-12 15:57:54 +00001262 mService.unlinkToDeath(this, 0);
1263 mService = null;
1264 mClassName = null;
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001265
1266 if (mInvokingProxyCallbacks) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001267 Slog.e(TAG, "Proxy callbacks already in progress.");
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001268 return;
Benjamin Franze8b98922014-11-12 15:57:54 +00001269 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001270 mInvokingProxyCallbacks = true;
1271
1272 final int n = mProxies.beginBroadcast();
1273 try {
1274 for (int i = 0; i < n; i++) {
1275 try {
1276 mProxies.getBroadcastItem(i).onServiceDisconnected(className);
1277 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001278 Slog.e(TAG, "Unable to disconnect from proxy", e);
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001279 }
1280 }
1281 } finally {
1282 mProxies.finishBroadcast();
1283 mInvokingProxyCallbacks = false;
1284 }
Benjamin Franze8b98922014-11-12 15:57:54 +00001285 }
1286
1287 @Override
1288 public void binderDied() {
1289 if (DBG) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001290 Slog.w(TAG, "Profile service for profile: " + mClassName + " died.");
Benjamin Franze8b98922014-11-12 15:57:54 +00001291 }
1292 onServiceDisconnected(mClassName);
1293 // Trigger rebind
1294 Message msg = mHandler.obtainMessage(MESSAGE_BIND_PROFILE_SERVICE);
1295 msg.obj = this;
1296 mHandler.sendMessageDelayed(msg, TIMEOUT_BIND_MS);
1297 }
1298 }
1299
fredcbf072a72012-05-09 16:52:50 -07001300 private void sendBluetoothStateCallback(boolean isUp) {
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001301 try {
1302 int n = mStateChangeCallbacks.beginBroadcast();
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001303 if (DBG) {
1304 Slog.d(TAG, "Broadcasting onBluetoothStateChange(" + isUp + ") to " + n
1305 + " receivers.");
1306 }
1307 for (int i = 0; i < n; i++) {
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001308 try {
1309 mStateChangeCallbacks.getBroadcastItem(i).onBluetoothStateChange(isUp);
1310 } catch (RemoteException e) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001311 Slog.e(TAG, "Unable to call onBluetoothStateChange() on callback #" + i, e);
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001312 }
fredcbf072a72012-05-09 16:52:50 -07001313 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001314 } finally {
1315 mStateChangeCallbacks.finishBroadcast();
fredcbf072a72012-05-09 16:52:50 -07001316 }
fredcbf072a72012-05-09 16:52:50 -07001317 }
1318
1319 /**
Zhihai Xu40874a02012-10-08 17:57:03 -07001320 * Inform BluetoothAdapter instances that Adapter service is up
1321 */
1322 private void sendBluetoothServiceUpCallback() {
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001323 try {
1324 int n = mCallbacks.beginBroadcast();
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001325 Slog.d(TAG, "Broadcasting onBluetoothServiceUp() to " + n + " receivers.");
1326 for (int i = 0; i < n; i++) {
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001327 try {
1328 mCallbacks.getBroadcastItem(i).onBluetoothServiceUp(mBluetooth);
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001329 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001330 Slog.e(TAG, "Unable to call onBluetoothServiceUp() on callback #" + i, e);
Zhihai Xu40874a02012-10-08 17:57:03 -07001331 }
1332 }
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001333 } finally {
1334 mCallbacks.finishBroadcast();
Zhihai Xu40874a02012-10-08 17:57:03 -07001335 }
1336 }
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001337
Zhihai Xu40874a02012-10-08 17:57:03 -07001338 /**
fredcbf072a72012-05-09 16:52:50 -07001339 * Inform BluetoothAdapter instances that Adapter service is down
1340 */
1341 private void sendBluetoothServiceDownCallback() {
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001342 try {
1343 int n = mCallbacks.beginBroadcast();
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001344 Slog.d(TAG, "Broadcasting onBluetoothServiceDown() to " + n + " receivers.");
1345 for (int i = 0; i < n; i++) {
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001346 try {
1347 mCallbacks.getBroadcastItem(i).onBluetoothServiceDown();
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001348 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001349 Slog.e(TAG, "Unable to call onBluetoothServiceDown() on callback #" + i, e);
fredcd6883532012-04-25 17:46:13 -07001350 }
1351 }
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001352 } finally {
1353 mCallbacks.finishBroadcast();
fredcd6883532012-04-25 17:46:13 -07001354 }
1355 }
Svet Ganov408abf72015-05-12 19:13:36 -07001356
fredc0f420372012-04-12 00:02:00 -07001357 public String getAddress() {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001358 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");
Zhihai Xu40874a02012-10-08 17:57:03 -07001359
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001360 if ((Binder.getCallingUid() != Process.SYSTEM_UID) && (!checkIfCallerIsForegroundUser())) {
1361 Slog.w(TAG, "getAddress(): not allowed for non-active and non system user");
Zhihai Xu6eb76522012-11-29 15:41:04 -08001362 return null;
Zhihai Xu40874a02012-10-08 17:57:03 -07001363 }
1364
Svet Ganov408abf72015-05-12 19:13:36 -07001365 if (mContext.checkCallingOrSelfPermission(Manifest.permission.LOCAL_MAC_ADDRESS)
1366 != PackageManager.PERMISSION_GRANTED) {
1367 return BluetoothAdapter.DEFAULT_MAC_ADDRESS;
1368 }
1369
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001370 try {
1371 mBluetoothLock.readLock().lock();
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001372 if (mBluetooth != null) {
1373 return mBluetooth.getAddress();
1374 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001375 } catch (RemoteException e) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001376 Slog.e(TAG,
1377 "getAddress(): Unable to retrieve address remotely. Returning cached address",
1378 e);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001379 } finally {
1380 mBluetoothLock.readLock().unlock();
fredc116d1d462012-04-20 14:47:08 -07001381 }
Ajay Panickerbf796d82016-03-11 13:47:20 -08001382
Matthew Xiecdce0b92012-07-12 19:06:15 -07001383 // mAddress is accessed from outside.
1384 // It is alright without a lock. Here, bluetooth is off, no other thread is
1385 // changing mAddress
fredc0f420372012-04-12 00:02:00 -07001386 return mAddress;
1387 }
fredc649fe492012-04-19 01:07:18 -07001388
fredc0f420372012-04-12 00:02:00 -07001389 public String getName() {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001390 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission");
Zhihai Xu40874a02012-10-08 17:57:03 -07001391
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001392 if ((Binder.getCallingUid() != Process.SYSTEM_UID) && (!checkIfCallerIsForegroundUser())) {
1393 Slog.w(TAG, "getName(): not allowed for non-active and non system user");
Zhihai Xu6eb76522012-11-29 15:41:04 -08001394 return null;
Zhihai Xu40874a02012-10-08 17:57:03 -07001395 }
1396
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001397 try {
1398 mBluetoothLock.readLock().lock();
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001399 if (mBluetooth != null) {
1400 return mBluetooth.getName();
1401 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001402 } catch (RemoteException e) {
1403 Slog.e(TAG, "getName(): Unable to retrieve name remotely. Returning cached name", e);
1404 } finally {
1405 mBluetoothLock.readLock().unlock();
fredc116d1d462012-04-20 14:47:08 -07001406 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001407
Matthew Xiecdce0b92012-07-12 19:06:15 -07001408 // mName is accessed from outside.
1409 // It alright without a lock. Here, bluetooth is off, no other thread is
1410 // changing mName
fredc0f420372012-04-12 00:02:00 -07001411 return mName;
1412 }
1413
fredc0f420372012-04-12 00:02:00 -07001414 private class BluetoothServiceConnection implements ServiceConnection {
Marie Janssencb21ad72016-12-13 10:51:02 -08001415 public void onServiceConnected(ComponentName componentName, IBinder service) {
1416 String name = componentName.getClassName();
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001417 if (DBG) {
1418 Slog.d(TAG, "BluetoothServiceConnection: " + name);
1419 }
fredc0f420372012-04-12 00:02:00 -07001420 Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_SERVICE_CONNECTED);
Marie Janssencb21ad72016-12-13 10:51:02 -08001421 if (name.equals("com.android.bluetooth.btservice.AdapterService")) {
Matthew Xieddf7e472013-03-01 18:41:02 -08001422 msg.arg1 = SERVICE_IBLUETOOTH;
Marie Janssencb21ad72016-12-13 10:51:02 -08001423 } else if (name.equals("com.android.bluetooth.gatt.GattService")) {
Matthew Xieddf7e472013-03-01 18:41:02 -08001424 msg.arg1 = SERVICE_IBLUETOOTHGATT;
1425 } else {
Marie Janssencb21ad72016-12-13 10:51:02 -08001426 Slog.e(TAG, "Unknown service connected: " + name);
Matthew Xieddf7e472013-03-01 18:41:02 -08001427 return;
1428 }
fredc0f420372012-04-12 00:02:00 -07001429 msg.obj = service;
1430 mHandler.sendMessage(msg);
1431 }
1432
Marie Janssencb21ad72016-12-13 10:51:02 -08001433 public void onServiceDisconnected(ComponentName componentName) {
1434 // Called if we unexpectedly disconnect.
1435 String name = componentName.getClassName();
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001436 if (DBG) {
1437 Slog.d(TAG, "BluetoothServiceConnection, disconnected: " + name);
1438 }
fredc0f420372012-04-12 00:02:00 -07001439 Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED);
Marie Janssencb21ad72016-12-13 10:51:02 -08001440 if (name.equals("com.android.bluetooth.btservice.AdapterService")) {
Matthew Xieddf7e472013-03-01 18:41:02 -08001441 msg.arg1 = SERVICE_IBLUETOOTH;
Marie Janssencb21ad72016-12-13 10:51:02 -08001442 } else if (name.equals("com.android.bluetooth.gatt.GattService")) {
Matthew Xieddf7e472013-03-01 18:41:02 -08001443 msg.arg1 = SERVICE_IBLUETOOTHGATT;
1444 } else {
Marie Janssencb21ad72016-12-13 10:51:02 -08001445 Slog.e(TAG, "Unknown service disconnected: " + name);
Matthew Xieddf7e472013-03-01 18:41:02 -08001446 return;
1447 }
fredc0f420372012-04-12 00:02:00 -07001448 mHandler.sendMessage(msg);
1449 }
1450 }
1451
1452 private BluetoothServiceConnection mConnection = new BluetoothServiceConnection();
1453
Zhihai Xu40874a02012-10-08 17:57:03 -07001454 private class BluetoothHandler extends Handler {
Ajay Panicker4bb48302016-03-31 14:14:27 -07001455 boolean mGetNameAddressOnly = false;
1456
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001457 BluetoothHandler(Looper looper) {
Zhihai Xu40874a02012-10-08 17:57:03 -07001458 super(looper);
1459 }
1460
fredc0f420372012-04-12 00:02:00 -07001461 @Override
1462 public void handleMessage(Message msg) {
fredc0f420372012-04-12 00:02:00 -07001463 switch (msg.what) {
Ajay Panicker4bb48302016-03-31 14:14:27 -07001464 case MESSAGE_GET_NAME_AND_ADDRESS:
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001465 if (DBG) {
1466 Slog.d(TAG, "MESSAGE_GET_NAME_AND_ADDRESS");
1467 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001468 try {
1469 mBluetoothLock.writeLock().lock();
Ajay Panicker4bb48302016-03-31 14:14:27 -07001470 if ((mBluetooth == null) && (!mBinding)) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001471 if (DBG) {
1472 Slog.d(TAG, "Binding to service to get name and address");
1473 }
Ajay Panicker4bb48302016-03-31 14:14:27 -07001474 mGetNameAddressOnly = true;
1475 Message timeoutMsg = mHandler.obtainMessage(MESSAGE_TIMEOUT_BIND);
1476 mHandler.sendMessageDelayed(timeoutMsg, TIMEOUT_BIND_MS);
1477 Intent i = new Intent(IBluetooth.class.getName());
1478 if (!doBind(i, mConnection,
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001479 Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT,
1480 UserHandle.CURRENT)) {
Ajay Panicker4bb48302016-03-31 14:14:27 -07001481 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
1482 } else {
1483 mBinding = true;
1484 }
1485 } else if (mBluetooth != null) {
1486 try {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001487 storeNameAndAddress(mBluetooth.getName(), mBluetooth.getAddress());
Ajay Panicker4bb48302016-03-31 14:14:27 -07001488 } catch (RemoteException re) {
1489 Slog.e(TAG, "Unable to grab names", re);
1490 }
1491 if (mGetNameAddressOnly && !mEnable) {
1492 unbindAndFinish();
1493 }
1494 mGetNameAddressOnly = false;
1495 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001496 } finally {
1497 mBluetoothLock.writeLock().unlock();
Ajay Panicker4bb48302016-03-31 14:14:27 -07001498 }
1499 break;
1500
Matthew Xiecdce0b92012-07-12 19:06:15 -07001501 case MESSAGE_ENABLE:
fredcf2458862012-04-16 15:18:27 -07001502 if (DBG) {
Marie Janssencb21ad72016-12-13 10:51:02 -08001503 Slog.d(TAG, "MESSAGE_ENABLE(" + msg.arg1 + "): mBluetooth = " + mBluetooth);
fredc649fe492012-04-19 01:07:18 -07001504 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001505 mHandler.removeMessages(MESSAGE_RESTART_BLUETOOTH_SERVICE);
1506 mEnable = true;
Calvin Ona0b91d72016-06-15 17:58:23 -07001507
1508 // Use service interface to get the exact state
1509 try {
1510 mBluetoothLock.readLock().lock();
1511 if (mBluetooth != null) {
1512 int state = mBluetooth.getState();
1513 if (state == BluetoothAdapter.STATE_BLE_ON) {
Marie Janssene0bfa2e2016-12-20 11:21:12 -08001514 Slog.w(TAG, "BT Enable in BLE_ON State, going to ON");
Calvin Ona0b91d72016-06-15 17:58:23 -07001515 mBluetooth.onLeServiceUp();
Marie Janssene0bfa2e2016-12-20 11:21:12 -08001516 persistBluetoothSetting(BLUETOOTH_ON_BLUETOOTH);
Calvin Ona0b91d72016-06-15 17:58:23 -07001517 break;
1518 }
1519 }
1520 } catch (RemoteException e) {
1521 Slog.e(TAG, "", e);
1522 } finally {
1523 mBluetoothLock.readLock().unlock();
1524 }
1525
1526 mQuietEnable = (msg.arg1 == 1);
Pavlin Radoslavove47ec142016-06-01 22:25:18 -07001527 if (mBluetooth == null) {
Calvin Ona0b91d72016-06-15 17:58:23 -07001528 handleEnable(mQuietEnable);
Pavlin Radoslavove47ec142016-06-01 22:25:18 -07001529 } else {
1530 //
1531 // We need to wait until transitioned to STATE_OFF and
1532 // the previous Bluetooth process has exited. The
1533 // waiting period has three components:
1534 // (a) Wait until the local state is STATE_OFF. This
1535 // is accomplished by "waitForOnOff(false, true)".
1536 // (b) Wait until the STATE_OFF state is updated to
1537 // all components.
1538 // (c) Wait until the Bluetooth process exits, and
1539 // ActivityManager detects it.
1540 // The waiting for (b) and (c) is accomplished by
1541 // delaying the MESSAGE_RESTART_BLUETOOTH_SERVICE
1542 // message. On slower devices, that delay needs to be
1543 // on the order of (2 * SERVICE_RESTART_TIME_MS).
1544 //
1545 waitForOnOff(false, true);
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001546 Message restartMsg =
1547 mHandler.obtainMessage(MESSAGE_RESTART_BLUETOOTH_SERVICE);
1548 mHandler.sendMessageDelayed(restartMsg, 2 * SERVICE_RESTART_TIME_MS);
Pavlin Radoslavove47ec142016-06-01 22:25:18 -07001549 }
fredc649fe492012-04-19 01:07:18 -07001550 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001551
fredc0f420372012-04-12 00:02:00 -07001552 case MESSAGE_DISABLE:
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001553 if (DBG) {
1554 Slog.d(TAG, "MESSAGE_DISABLE: mBluetooth = " + mBluetooth);
1555 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001556 mHandler.removeMessages(MESSAGE_RESTART_BLUETOOTH_SERVICE);
1557 if (mEnable && mBluetooth != null) {
1558 waitForOnOff(true, false);
1559 mEnable = false;
Zhihai Xu401202b2012-12-03 11:36:21 -08001560 handleDisable();
Zhihai Xu40874a02012-10-08 17:57:03 -07001561 waitForOnOff(false, false);
1562 } else {
1563 mEnable = false;
Zhihai Xu401202b2012-12-03 11:36:21 -08001564 handleDisable();
Zhihai Xu40874a02012-10-08 17:57:03 -07001565 }
fredc0f420372012-04-12 00:02:00 -07001566 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001567
Stanley Tng873b5702017-05-01 21:27:31 -07001568 case MESSAGE_RESTORE_USER_SETTING:
Jack He8caab152018-03-02 13:08:36 -08001569 if ((msg.arg1 == RESTORE_SETTING_TO_OFF) && mEnable) {
1570 if (DBG) {
1571 Slog.d(TAG, "Restore Bluetooth state to disabled");
Stanley Tng873b5702017-05-01 21:27:31 -07001572 }
Jack He8caab152018-03-02 13:08:36 -08001573 persistBluetoothSetting(BLUETOOTH_OFF);
1574 mEnableExternal = false;
1575 sendDisableMsg(
1576 BluetoothProtoEnums.ENABLE_DISABLE_REASON_RESTORE_USER_SETTING,
1577 mContext.getPackageName());
1578 } else if ((msg.arg1 == RESTORE_SETTING_TO_ON) && !mEnable) {
1579 if (DBG) {
1580 Slog.d(TAG, "Restore Bluetooth state to enabled");
1581 }
1582 mQuietEnableExternal = false;
1583 mEnableExternal = true;
1584 // waive WRITE_SECURE_SETTINGS permission check
1585 sendEnableMsg(false,
1586 BluetoothProtoEnums.ENABLE_DISABLE_REASON_RESTORE_USER_SETTING,
1587 mContext.getPackageName());
Stanley Tng873b5702017-05-01 21:27:31 -07001588 }
1589 break;
1590
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001591 case MESSAGE_REGISTER_ADAPTER: {
fredc0f420372012-04-12 00:02:00 -07001592 IBluetoothManagerCallback callback = (IBluetoothManagerCallback) msg.obj;
Marie Janssencb21ad72016-12-13 10:51:02 -08001593 mCallbacks.register(callback);
fredc0f420372012-04-12 00:02:00 -07001594 break;
Marie Janssencb21ad72016-12-13 10:51:02 -08001595 }
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001596 case MESSAGE_UNREGISTER_ADAPTER: {
fredc0f420372012-04-12 00:02:00 -07001597 IBluetoothManagerCallback callback = (IBluetoothManagerCallback) msg.obj;
Marie Janssencb21ad72016-12-13 10:51:02 -08001598 mCallbacks.unregister(callback);
fredc0f420372012-04-12 00:02:00 -07001599 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001600 }
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001601 case MESSAGE_REGISTER_STATE_CHANGE_CALLBACK: {
1602 IBluetoothStateChangeCallback callback =
1603 (IBluetoothStateChangeCallback) msg.obj;
Marie Janssencb21ad72016-12-13 10:51:02 -08001604 mStateChangeCallbacks.register(callback);
fredc0f420372012-04-12 00:02:00 -07001605 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001606 }
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001607 case MESSAGE_UNREGISTER_STATE_CHANGE_CALLBACK: {
1608 IBluetoothStateChangeCallback callback =
1609 (IBluetoothStateChangeCallback) msg.obj;
Marie Janssencb21ad72016-12-13 10:51:02 -08001610 mStateChangeCallbacks.unregister(callback);
fredc0f420372012-04-12 00:02:00 -07001611 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001612 }
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001613 case MESSAGE_ADD_PROXY_DELAYED: {
Jack He8caab152018-03-02 13:08:36 -08001614 ProfileServiceConnections psc = mProfileServices.get(msg.arg1);
Benjamin Franze8b98922014-11-12 15:57:54 +00001615 if (psc == null) {
1616 break;
1617 }
1618 IBluetoothProfileServiceConnection proxy =
1619 (IBluetoothProfileServiceConnection) msg.obj;
1620 psc.addProxy(proxy);
1621 break;
1622 }
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001623 case MESSAGE_BIND_PROFILE_SERVICE: {
Benjamin Franze8b98922014-11-12 15:57:54 +00001624 ProfileServiceConnections psc = (ProfileServiceConnections) msg.obj;
1625 removeMessages(MESSAGE_BIND_PROFILE_SERVICE, msg.obj);
1626 if (psc == null) {
1627 break;
1628 }
1629 psc.bindService();
1630 break;
1631 }
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001632 case MESSAGE_BLUETOOTH_SERVICE_CONNECTED: {
1633 if (DBG) {
1634 Slog.d(TAG, "MESSAGE_BLUETOOTH_SERVICE_CONNECTED: " + msg.arg1);
1635 }
fredc0f420372012-04-12 00:02:00 -07001636
1637 IBinder service = (IBinder) msg.obj;
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001638 try {
1639 mBluetoothLock.writeLock().lock();
Matthew Xieddf7e472013-03-01 18:41:02 -08001640 if (msg.arg1 == SERVICE_IBLUETOOTHGATT) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001641 mBluetoothGatt =
1642 IBluetoothGatt.Stub.asInterface(Binder.allowBlocking(service));
Nitin Arorad055adb2015-03-02 15:03:51 -08001643 onBluetoothGattServiceUp();
Matthew Xieddf7e472013-03-01 18:41:02 -08001644 break;
1645 } // else must be SERVICE_IBLUETOOTH
1646
1647 //Remove timeout
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001648 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
Matthew Xieddf7e472013-03-01 18:41:02 -08001649
fredc0f420372012-04-12 00:02:00 -07001650 mBinding = false;
Marie Janssen9db28eb2016-01-12 16:05:15 -08001651 mBluetoothBinder = service;
Jeff Sharkey0a17db12016-11-04 11:23:46 -06001652 mBluetooth = IBluetooth.Stub.asInterface(Binder.allowBlocking(service));
fredc0f420372012-04-12 00:02:00 -07001653
Ajay Panicker4bb48302016-03-31 14:14:27 -07001654 if (!isNameAndAddressSet()) {
1655 Message getMsg = mHandler.obtainMessage(MESSAGE_GET_NAME_AND_ADDRESS);
1656 mHandler.sendMessage(getMsg);
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001657 if (mGetNameAddressOnly) {
1658 return;
1659 }
Ajay Panicker4bb48302016-03-31 14:14:27 -07001660 }
1661
Matthew Xiecdce0b92012-07-12 19:06:15 -07001662 //Register callback object
fredcbf072a72012-05-09 16:52:50 -07001663 try {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001664 mBluetooth.registerCallback(mBluetoothCallback);
1665 } catch (RemoteException re) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001666 Slog.e(TAG, "Unable to register BluetoothCallback", re);
fredcbf072a72012-05-09 16:52:50 -07001667 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001668 //Inform BluetoothAdapter instances that service is up
Zhihai Xu40874a02012-10-08 17:57:03 -07001669 sendBluetoothServiceUpCallback();
1670
Matthew Xiecdce0b92012-07-12 19:06:15 -07001671 //Do enable request
1672 try {
Jack Hea6e031c2017-12-08 12:21:37 -08001673 if (!mQuietEnable) {
Marie Janssencb21ad72016-12-13 10:51:02 -08001674 if (!mBluetooth.enable()) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001675 Slog.e(TAG, "IBluetooth.enable() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001676 }
Marie Janssencb21ad72016-12-13 10:51:02 -08001677 } else {
1678 if (!mBluetooth.enableNoAutoConnect()) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001679 Slog.e(TAG, "IBluetooth.enableNoAutoConnect() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001680 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001681 }
1682 } catch (RemoteException e) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001683 Slog.e(TAG, "Unable to call enable()", e);
Matthew Xiecdce0b92012-07-12 19:06:15 -07001684 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001685 } finally {
1686 mBluetoothLock.writeLock().unlock();
Freda8c6df02012-07-11 10:25:23 -07001687 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001688
1689 if (!mEnable) {
1690 waitForOnOff(true, false);
Zhihai Xu401202b2012-12-03 11:36:21 -08001691 handleDisable();
Zhihai Xu40874a02012-10-08 17:57:03 -07001692 waitForOnOff(false, false);
1693 }
fredc649fe492012-04-19 01:07:18 -07001694 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001695 }
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001696 case MESSAGE_BLUETOOTH_STATE_CHANGE: {
fredcbf072a72012-05-09 16:52:50 -07001697 int prevState = msg.arg1;
1698 int newState = msg.arg2;
Marie Janssencb21ad72016-12-13 10:51:02 -08001699 if (DBG) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001700 Slog.d(TAG,
1701 "MESSAGE_BLUETOOTH_STATE_CHANGE: " + BluetoothAdapter.nameForState(
1702 prevState) + " > " + BluetoothAdapter.nameForState(
1703 newState));
Marie Janssencb21ad72016-12-13 10:51:02 -08001704 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001705 mState = newState;
1706 bluetoothStateChangeHandler(prevState, newState);
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001707 // handle error state transition case from TURNING_ON to OFF
1708 // unbind and rebind bluetooth service and enable bluetooth
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001709 if ((prevState == BluetoothAdapter.STATE_BLE_TURNING_ON) && (newState
1710 == BluetoothAdapter.STATE_OFF) && (mBluetooth != null) && mEnable) {
Marie Janssen2977c3e2016-11-09 12:01:24 -08001711 recoverBluetoothServiceFromError(false);
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001712 }
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001713 if ((prevState == BluetoothAdapter.STATE_TURNING_ON) && (newState
1714 == BluetoothAdapter.STATE_BLE_ON) && (mBluetooth != null) && mEnable) {
Marie Janssen2977c3e2016-11-09 12:01:24 -08001715 recoverBluetoothServiceFromError(true);
Nitin Arorad055adb2015-03-02 15:03:51 -08001716 }
Calvin Ona0b91d72016-06-15 17:58:23 -07001717 // If we tried to enable BT while BT was in the process of shutting down,
1718 // wait for the BT process to fully tear down and then force a restart
1719 // here. This is a bit of a hack (b/29363429).
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001720 if ((prevState == BluetoothAdapter.STATE_BLE_TURNING_OFF) && (newState
1721 == BluetoothAdapter.STATE_OFF)) {
Calvin Ona0b91d72016-06-15 17:58:23 -07001722 if (mEnable) {
1723 Slog.d(TAG, "Entering STATE_OFF but mEnabled is true; restarting.");
1724 waitForOnOff(false, true);
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001725 Message restartMsg =
1726 mHandler.obtainMessage(MESSAGE_RESTART_BLUETOOTH_SERVICE);
Calvin Ona0b91d72016-06-15 17:58:23 -07001727 mHandler.sendMessageDelayed(restartMsg, 2 * SERVICE_RESTART_TIME_MS);
1728 }
1729 }
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001730 if (newState == BluetoothAdapter.STATE_ON
1731 || newState == BluetoothAdapter.STATE_BLE_ON) {
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001732 // bluetooth is working, reset the counter
1733 if (mErrorRecoveryRetryCounter != 0) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001734 Slog.w(TAG, "bluetooth is recovered from error");
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001735 mErrorRecoveryRetryCounter = 0;
1736 }
1737 }
fredc649fe492012-04-19 01:07:18 -07001738 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001739 }
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001740 case MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED: {
Marie Janssencb21ad72016-12-13 10:51:02 -08001741 Slog.e(TAG, "MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED(" + msg.arg1 + ")");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001742 try {
1743 mBluetoothLock.writeLock().lock();
Matthew Xieddf7e472013-03-01 18:41:02 -08001744 if (msg.arg1 == SERVICE_IBLUETOOTH) {
1745 // if service is unbinded already, do nothing and return
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001746 if (mBluetooth == null) {
1747 break;
1748 }
Matthew Xieddf7e472013-03-01 18:41:02 -08001749 mBluetooth = null;
1750 } else if (msg.arg1 == SERVICE_IBLUETOOTHGATT) {
1751 mBluetoothGatt = null;
1752 break;
1753 } else {
Marie Janssencb21ad72016-12-13 10:51:02 -08001754 Slog.e(TAG, "Unknown argument for service disconnect!");
Matthew Xieddf7e472013-03-01 18:41:02 -08001755 break;
1756 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001757 } finally {
1758 mBluetoothLock.writeLock().unlock();
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301759 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001760
Marie Janssene54b4222017-03-16 18:10:59 -07001761 // log the unexpected crash
1762 addCrashLog();
Jack He8caab152018-03-02 13:08:36 -08001763 addActiveLog(BluetoothProtoEnums.ENABLE_DISABLE_REASON_CRASH,
1764 mContext.getPackageName(), false);
Zhihai Xu40874a02012-10-08 17:57:03 -07001765 if (mEnable) {
1766 mEnable = false;
1767 // Send a Bluetooth Restart message
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001768 Message restartMsg =
1769 mHandler.obtainMessage(MESSAGE_RESTART_BLUETOOTH_SERVICE);
1770 mHandler.sendMessageDelayed(restartMsg, SERVICE_RESTART_TIME_MS);
Zhihai Xu40874a02012-10-08 17:57:03 -07001771 }
1772
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001773 sendBluetoothServiceDownCallback();
Zhihai Xu40874a02012-10-08 17:57:03 -07001774
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001775 // Send BT state broadcast to update
1776 // the BT icon correctly
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001777 if ((mState == BluetoothAdapter.STATE_TURNING_ON) || (mState
1778 == BluetoothAdapter.STATE_ON)) {
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001779 bluetoothStateChangeHandler(BluetoothAdapter.STATE_ON,
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001780 BluetoothAdapter.STATE_TURNING_OFF);
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001781 mState = BluetoothAdapter.STATE_TURNING_OFF;
Zhihai Xu40874a02012-10-08 17:57:03 -07001782 }
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001783 if (mState == BluetoothAdapter.STATE_TURNING_OFF) {
1784 bluetoothStateChangeHandler(BluetoothAdapter.STATE_TURNING_OFF,
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001785 BluetoothAdapter.STATE_OFF);
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001786 }
1787
1788 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
1789 mState = BluetoothAdapter.STATE_OFF;
fredc649fe492012-04-19 01:07:18 -07001790 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001791 }
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001792 case MESSAGE_RESTART_BLUETOOTH_SERVICE: {
Marie Janssencb21ad72016-12-13 10:51:02 -08001793 Slog.d(TAG, "MESSAGE_RESTART_BLUETOOTH_SERVICE");
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301794 /* Enable without persisting the setting as
1795 it doesnt change when IBluetooth
1796 service restarts */
Zhihai Xu40874a02012-10-08 17:57:03 -07001797 mEnable = true;
Jack He8caab152018-03-02 13:08:36 -08001798 addActiveLog(BluetoothProtoEnums.ENABLE_DISABLE_REASON_RESTARTED,
1799 mContext.getPackageName(), true);
Zhihai Xu401202b2012-12-03 11:36:21 -08001800 handleEnable(mQuietEnable);
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301801 break;
1802 }
Marie Janssencb21ad72016-12-13 10:51:02 -08001803 case MESSAGE_TIMEOUT_BIND: {
1804 Slog.e(TAG, "MESSAGE_TIMEOUT_BIND");
1805 mBluetoothLock.writeLock().lock();
1806 mBinding = false;
1807 mBluetoothLock.writeLock().unlock();
1808 break;
1809 }
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001810 case MESSAGE_TIMEOUT_UNBIND: {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001811 Slog.e(TAG, "MESSAGE_TIMEOUT_UNBIND");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001812 mBluetoothLock.writeLock().lock();
1813 mUnbinding = false;
1814 mBluetoothLock.writeLock().unlock();
fredc649fe492012-04-19 01:07:18 -07001815 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001816 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001817
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001818 case MESSAGE_USER_SWITCHED: {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001819 if (DBG) {
1820 Slog.d(TAG, "MESSAGE_USER_SWITCHED");
1821 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001822 mHandler.removeMessages(MESSAGE_USER_SWITCHED);
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001823
Zhihai Xu40874a02012-10-08 17:57:03 -07001824 /* disable and enable BT when detect a user switch */
Ram Periathiruvadi88256d12017-05-03 19:11:20 -07001825 if (mBluetooth != null && isEnabled()) {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001826 try {
1827 mBluetoothLock.readLock().lock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001828 if (mBluetooth != null) {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001829 mBluetooth.unregisterCallback(mBluetoothCallback);
Zhihai Xu40874a02012-10-08 17:57:03 -07001830 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001831 } catch (RemoteException re) {
1832 Slog.e(TAG, "Unable to unregister", re);
1833 } finally {
1834 mBluetoothLock.readLock().unlock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001835 }
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001836
1837 if (mState == BluetoothAdapter.STATE_TURNING_OFF) {
1838 // MESSAGE_USER_SWITCHED happened right after MESSAGE_ENABLE
1839 bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_OFF);
1840 mState = BluetoothAdapter.STATE_OFF;
1841 }
1842 if (mState == BluetoothAdapter.STATE_OFF) {
1843 bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_TURNING_ON);
1844 mState = BluetoothAdapter.STATE_TURNING_ON;
1845 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001846
1847 waitForOnOff(true, false);
1848
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001849 if (mState == BluetoothAdapter.STATE_TURNING_ON) {
1850 bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_ON);
1851 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001852
Benjamin Franze8b98922014-11-12 15:57:54 +00001853 unbindAllBluetoothProfileServices();
Zhihai Xu40874a02012-10-08 17:57:03 -07001854 // disable
Jack He8caab152018-03-02 13:08:36 -08001855 addActiveLog(BluetoothProtoEnums.ENABLE_DISABLE_REASON_USER_SWITCH,
1856 mContext.getPackageName(), false);
Zhihai Xu401202b2012-12-03 11:36:21 -08001857 handleDisable();
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001858 // Pbap service need receive STATE_TURNING_OFF intent to close
1859 bluetoothStateChangeHandler(BluetoothAdapter.STATE_ON,
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001860 BluetoothAdapter.STATE_TURNING_OFF);
Zhihai Xu40874a02012-10-08 17:57:03 -07001861
Pavlin Radoslavov41401112016-06-27 15:25:18 -07001862 boolean didDisableTimeout = !waitForOnOff(false, true);
Zhihai Xu40874a02012-10-08 17:57:03 -07001863
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001864 bluetoothStateChangeHandler(BluetoothAdapter.STATE_TURNING_OFF,
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001865 BluetoothAdapter.STATE_OFF);
Zhihai Xu40874a02012-10-08 17:57:03 -07001866 sendBluetoothServiceDownCallback();
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001867
Pavlin Radoslavove957a8a2016-05-24 15:28:41 -07001868 try {
1869 mBluetoothLock.writeLock().lock();
1870 if (mBluetooth != null) {
1871 mBluetooth = null;
1872 // Unbind
1873 mContext.unbindService(mConnection);
1874 }
1875 mBluetoothGatt = null;
1876 } finally {
1877 mBluetoothLock.writeLock().unlock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001878 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001879
Pavlin Radoslavov41401112016-06-27 15:25:18 -07001880 //
1881 // If disabling Bluetooth times out, wait for an
1882 // additional amount of time to ensure the process is
1883 // shut down completely before attempting to restart.
1884 //
1885 if (didDisableTimeout) {
1886 SystemClock.sleep(3000);
1887 } else {
1888 SystemClock.sleep(100);
1889 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001890
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001891 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
1892 mState = BluetoothAdapter.STATE_OFF;
Zhihai Xu40874a02012-10-08 17:57:03 -07001893 // enable
Jack He8caab152018-03-02 13:08:36 -08001894 addActiveLog(BluetoothProtoEnums.ENABLE_DISABLE_REASON_USER_SWITCH,
1895 mContext.getPackageName(), true);
Ram Periathiruvadi88256d12017-05-03 19:11:20 -07001896 // mEnable flag could have been reset on disableBLE. Reenable it.
1897 mEnable = true;
Zhihai Xu401202b2012-12-03 11:36:21 -08001898 handleEnable(mQuietEnable);
John Spurlock8a985d22014-02-25 09:40:05 -05001899 } else if (mBinding || mBluetooth != null) {
Zhihai Xu40874a02012-10-08 17:57:03 -07001900 Message userMsg = mHandler.obtainMessage(MESSAGE_USER_SWITCHED);
1901 userMsg.arg2 = 1 + msg.arg2;
Marie Janssencb21ad72016-12-13 10:51:02 -08001902 // if user is switched when service is binding retry after a delay
Zhihai Xu40874a02012-10-08 17:57:03 -07001903 mHandler.sendMessageDelayed(userMsg, USER_SWITCHED_TIME_MS);
1904 if (DBG) {
Marie Janssencb21ad72016-12-13 10:51:02 -08001905 Slog.d(TAG, "Retry MESSAGE_USER_SWITCHED " + userMsg.arg2);
Zhihai Xu40874a02012-10-08 17:57:03 -07001906 }
John Spurlock8a985d22014-02-25 09:40:05 -05001907 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001908 break;
1909 }
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001910 case MESSAGE_USER_UNLOCKED: {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001911 if (DBG) {
1912 Slog.d(TAG, "MESSAGE_USER_UNLOCKED");
1913 }
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001914 mHandler.removeMessages(MESSAGE_USER_SWITCHED);
1915
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001916 if (mEnable && !mBinding && (mBluetooth == null)) {
1917 // We should be connected, but we gave up for some
1918 // reason; maybe the Bluetooth service wasn't encryption
1919 // aware, so try binding again.
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001920 if (DBG) {
1921 Slog.d(TAG, "Enabled but not bound; retrying after unlock");
1922 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001923 handleEnable(mQuietEnable);
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001924 }
1925 }
fredc0f420372012-04-12 00:02:00 -07001926 }
1927 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001928 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001929
Zhihai Xu401202b2012-12-03 11:36:21 -08001930 private void handleEnable(boolean quietMode) {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001931 mQuietEnable = quietMode;
1932
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001933 try {
1934 mBluetoothLock.writeLock().lock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001935 if ((mBluetooth == null) && (!mBinding)) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001936 //Start bind timeout and bind
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001937 Message timeoutMsg = mHandler.obtainMessage(MESSAGE_TIMEOUT_BIND);
1938 mHandler.sendMessageDelayed(timeoutMsg, TIMEOUT_BIND_MS);
Matthew Xiecdce0b92012-07-12 19:06:15 -07001939 Intent i = new Intent(IBluetooth.class.getName());
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001940 if (!doBind(i, mConnection, Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT,
Dianne Hackbornce09f5a2014-10-10 15:03:13 -07001941 UserHandle.CURRENT)) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001942 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
Zhihai Xu40874a02012-10-08 17:57:03 -07001943 } else {
1944 mBinding = true;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001945 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001946 } else if (mBluetooth != null) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001947 //Enable bluetooth
1948 try {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001949 if (!mQuietEnable) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001950 if (!mBluetooth.enable()) {
1951 Slog.e(TAG, "IBluetooth.enable() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001952 }
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001953 } else {
1954 if (!mBluetooth.enableNoAutoConnect()) {
1955 Slog.e(TAG, "IBluetooth.enableNoAutoConnect() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001956 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001957 }
1958 } catch (RemoteException e) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001959 Slog.e(TAG, "Unable to call enable()", e);
Matthew Xiecdce0b92012-07-12 19:06:15 -07001960 }
1961 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001962 } finally {
1963 mBluetoothLock.writeLock().unlock();
Matthew Xiecdce0b92012-07-12 19:06:15 -07001964 }
1965 }
1966
Dianne Hackborn221ea892013-08-04 16:50:16 -07001967 boolean doBind(Intent intent, ServiceConnection conn, int flags, UserHandle user) {
1968 ComponentName comp = intent.resolveSystemService(mContext.getPackageManager(), 0);
1969 intent.setComponent(comp);
1970 if (comp == null || !mContext.bindServiceAsUser(intent, conn, flags, user)) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001971 Slog.e(TAG, "Fail to bind to: " + intent);
Dianne Hackborn221ea892013-08-04 16:50:16 -07001972 return false;
1973 }
1974 return true;
1975 }
1976
Zhihai Xu401202b2012-12-03 11:36:21 -08001977 private void handleDisable() {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001978 try {
1979 mBluetoothLock.readLock().lock();
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001980 if (mBluetooth != null) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001981 if (DBG) {
1982 Slog.d(TAG, "Sending off request.");
1983 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001984 if (!mBluetooth.disable()) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001985 Slog.e(TAG, "IBluetooth.disable() returned false");
Matthew Xiecdce0b92012-07-12 19:06:15 -07001986 }
1987 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001988 } catch (RemoteException e) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08001989 Slog.e(TAG, "Unable to call disable()", e);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001990 } finally {
1991 mBluetoothLock.readLock().unlock();
Matthew Xiecdce0b92012-07-12 19:06:15 -07001992 }
1993 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001994
1995 private boolean checkIfCallerIsForegroundUser() {
1996 int foregroundUser;
1997 int callingUser = UserHandle.getCallingUserId();
Martijn Coenen8385c5a2012-11-29 10:14:16 -08001998 int callingUid = Binder.getCallingUid();
Zhihai Xu40874a02012-10-08 17:57:03 -07001999 long callingIdentity = Binder.clearCallingIdentity();
Benjamin Franze8b98922014-11-12 15:57:54 +00002000 UserManager um = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
2001 UserInfo ui = um.getProfileParent(callingUser);
2002 int parentUser = (ui != null) ? ui.id : UserHandle.USER_NULL;
Martijn Coenen8385c5a2012-11-29 10:14:16 -08002003 int callingAppId = UserHandle.getAppId(callingUid);
Zhihai Xu40874a02012-10-08 17:57:03 -07002004 boolean valid = false;
2005 try {
2006 foregroundUser = ActivityManager.getCurrentUser();
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002007 valid = (callingUser == foregroundUser) || parentUser == foregroundUser
2008 || callingAppId == Process.NFC_UID || callingAppId == mSystemUiUid;
Marie Janssencb21ad72016-12-13 10:51:02 -08002009 if (DBG && !valid) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002010 Slog.d(TAG, "checkIfCallerIsForegroundUser: valid=" + valid + " callingUser="
2011 + callingUser + " parentUser=" + parentUser + " foregroundUser="
2012 + foregroundUser);
Zhihai Xu40874a02012-10-08 17:57:03 -07002013 }
2014 } finally {
2015 Binder.restoreCallingIdentity(callingIdentity);
2016 }
2017 return valid;
2018 }
2019
Nitin Arorad055adb2015-03-02 15:03:51 -08002020 private void sendBleStateChanged(int prevState, int newState) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002021 if (DBG) {
2022 Slog.d(TAG,
2023 "Sending BLE State Change: " + BluetoothAdapter.nameForState(prevState) + " > "
2024 + BluetoothAdapter.nameForState(newState));
2025 }
Nitin Arorad055adb2015-03-02 15:03:51 -08002026 // Send broadcast message to everyone else
2027 Intent intent = new Intent(BluetoothAdapter.ACTION_BLE_STATE_CHANGED);
2028 intent.putExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE, prevState);
2029 intent.putExtra(BluetoothAdapter.EXTRA_STATE, newState);
2030 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
2031 mContext.sendBroadcastAsUser(intent, UserHandle.ALL, BLUETOOTH_PERM);
2032 }
2033
Zhihai Xu40874a02012-10-08 17:57:03 -07002034 private void bluetoothStateChangeHandler(int prevState, int newState) {
Nitin Arorad055adb2015-03-02 15:03:51 -08002035 boolean isStandardBroadcast = true;
Marie Janssencb21ad72016-12-13 10:51:02 -08002036 if (prevState == newState) { // No change. Nothing to do.
2037 return;
2038 }
2039 // Notify all proxy objects first of adapter state change
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002040 if (newState == BluetoothAdapter.STATE_BLE_ON || newState == BluetoothAdapter.STATE_OFF) {
Marie Janssencb21ad72016-12-13 10:51:02 -08002041 boolean intermediate_off = (prevState == BluetoothAdapter.STATE_TURNING_OFF
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002042 && newState == BluetoothAdapter.STATE_BLE_ON);
Zhihai Xu40874a02012-10-08 17:57:03 -07002043
Marie Janssencb21ad72016-12-13 10:51:02 -08002044 if (newState == BluetoothAdapter.STATE_OFF) {
2045 // If Bluetooth is off, send service down event to proxy objects, and unbind
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002046 if (DBG) {
2047 Slog.d(TAG, "Bluetooth is complete send Service Down");
2048 }
Marie Janssencb21ad72016-12-13 10:51:02 -08002049 sendBluetoothServiceDownCallback();
2050 unbindAndFinish();
Nitin Arorad055adb2015-03-02 15:03:51 -08002051 sendBleStateChanged(prevState, newState);
Marie Janssencb21ad72016-12-13 10:51:02 -08002052 // Don't broadcast as it has already been broadcast before
Nitin Arorad055adb2015-03-02 15:03:51 -08002053 isStandardBroadcast = false;
2054
Marie Janssencb21ad72016-12-13 10:51:02 -08002055 } else if (!intermediate_off) {
2056 // connect to GattService
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002057 if (DBG) {
2058 Slog.d(TAG, "Bluetooth is in LE only mode");
2059 }
Marie Janssencb21ad72016-12-13 10:51:02 -08002060 if (mBluetoothGatt != null) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002061 if (DBG) {
2062 Slog.d(TAG, "Calling BluetoothGattServiceUp");
2063 }
Marie Janssencb21ad72016-12-13 10:51:02 -08002064 onBluetoothGattServiceUp();
2065 } else {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002066 if (DBG) {
2067 Slog.d(TAG, "Binding Bluetooth GATT service");
2068 }
2069 if (mContext.getPackageManager()
2070 .hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
Marie Janssencb21ad72016-12-13 10:51:02 -08002071 Intent i = new Intent(IBluetoothGatt.class.getName());
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002072 doBind(i, mConnection, Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT,
2073 UserHandle.CURRENT);
Marie Janssencb21ad72016-12-13 10:51:02 -08002074 }
Nitin Arorad055adb2015-03-02 15:03:51 -08002075 }
Marie Janssencb21ad72016-12-13 10:51:02 -08002076 sendBleStateChanged(prevState, newState);
2077 //Don't broadcase this as std intent
2078 isStandardBroadcast = false;
2079
2080 } else if (intermediate_off) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002081 if (DBG) {
2082 Slog.d(TAG, "Intermediate off, back to LE only mode");
2083 }
Marie Janssencb21ad72016-12-13 10:51:02 -08002084 // For LE only mode, broadcast as is
2085 sendBleStateChanged(prevState, newState);
2086 sendBluetoothStateCallback(false); // BT is OFF for general users
2087 // Broadcast as STATE_OFF
2088 newState = BluetoothAdapter.STATE_OFF;
2089 sendBrEdrDownCallback();
Nitin Arorad055adb2015-03-02 15:03:51 -08002090 }
Marie Janssencb21ad72016-12-13 10:51:02 -08002091 } else if (newState == BluetoothAdapter.STATE_ON) {
2092 boolean isUp = (newState == BluetoothAdapter.STATE_ON);
2093 sendBluetoothStateCallback(isUp);
2094 sendBleStateChanged(prevState, newState);
2095
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002096 } else if (newState == BluetoothAdapter.STATE_BLE_TURNING_ON
2097 || newState == BluetoothAdapter.STATE_BLE_TURNING_OFF) {
Marie Janssencb21ad72016-12-13 10:51:02 -08002098 sendBleStateChanged(prevState, newState);
2099 isStandardBroadcast = false;
2100
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002101 } else if (newState == BluetoothAdapter.STATE_TURNING_ON
2102 || newState == BluetoothAdapter.STATE_TURNING_OFF) {
Marie Janssencb21ad72016-12-13 10:51:02 -08002103 sendBleStateChanged(prevState, newState);
2104 }
2105
2106 if (isStandardBroadcast) {
2107 if (prevState == BluetoothAdapter.STATE_BLE_ON) {
2108 // Show prevState of BLE_ON as OFF to standard users
2109 prevState = BluetoothAdapter.STATE_OFF;
2110 }
2111 Intent intent = new Intent(BluetoothAdapter.ACTION_STATE_CHANGED);
2112 intent.putExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE, prevState);
2113 intent.putExtra(BluetoothAdapter.EXTRA_STATE, newState);
2114 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
2115 mContext.sendBroadcastAsUser(intent, UserHandle.ALL, BLUETOOTH_PERM);
Zhihai Xu40874a02012-10-08 17:57:03 -07002116 }
2117 }
2118
2119 /**
2120 * if on is true, wait for state become ON
2121 * if off is true, wait for state become OFF
2122 * if both on and off are false, wait for state not ON
2123 */
2124 private boolean waitForOnOff(boolean on, boolean off) {
2125 int i = 0;
2126 while (i < 10) {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07002127 try {
2128 mBluetoothLock.readLock().lock();
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002129 if (mBluetooth == null) {
2130 break;
2131 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07002132 if (on) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002133 if (mBluetooth.getState() == BluetoothAdapter.STATE_ON) {
2134 return true;
2135 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07002136 } else if (off) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002137 if (mBluetooth.getState() == BluetoothAdapter.STATE_OFF) {
2138 return true;
2139 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07002140 } else {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002141 if (mBluetooth.getState() != BluetoothAdapter.STATE_ON) {
2142 return true;
2143 }
Zhihai Xu40874a02012-10-08 17:57:03 -07002144 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07002145 } catch (RemoteException e) {
2146 Slog.e(TAG, "getState()", e);
2147 break;
2148 } finally {
2149 mBluetoothLock.readLock().unlock();
Zhihai Xu40874a02012-10-08 17:57:03 -07002150 }
2151 if (on || off) {
2152 SystemClock.sleep(300);
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07002153 } else {
Zhihai Xu40874a02012-10-08 17:57:03 -07002154 SystemClock.sleep(50);
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07002155 }
Zhihai Xu40874a02012-10-08 17:57:03 -07002156 i++;
2157 }
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002158 Slog.e(TAG, "waitForOnOff time out");
Zhihai Xu40874a02012-10-08 17:57:03 -07002159 return false;
2160 }
Zhihai Xu681ae7f2012-11-12 15:14:18 -08002161
Jack He8caab152018-03-02 13:08:36 -08002162 private void sendDisableMsg(int reason, String packageName) {
Zhihai Xu401202b2012-12-03 11:36:21 -08002163 mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_DISABLE));
Jack He8caab152018-03-02 13:08:36 -08002164 addActiveLog(reason, packageName, false);
Zhihai Xu401202b2012-12-03 11:36:21 -08002165 }
2166
Jack He8caab152018-03-02 13:08:36 -08002167 private void sendEnableMsg(boolean quietMode, int reason, String packageName) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002168 mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_ENABLE, quietMode ? 1 : 0, 0));
Jack He8caab152018-03-02 13:08:36 -08002169 addActiveLog(reason, packageName, true);
Marie Janssen12a35012017-06-26 07:21:03 -07002170 mLastEnabledTime = SystemClock.elapsedRealtime();
Marie Janssen59804562016-12-28 14:13:21 -08002171 }
2172
Jack He8caab152018-03-02 13:08:36 -08002173 private void addActiveLog(int reason, String packageName, boolean enable) {
Marie Janssen59804562016-12-28 14:13:21 -08002174 synchronized (mActiveLogs) {
Marie Janssene54b4222017-03-16 18:10:59 -07002175 if (mActiveLogs.size() > ACTIVE_LOG_MAX_SIZE) {
Marie Janssen59804562016-12-28 14:13:21 -08002176 mActiveLogs.remove();
2177 }
Jack He8caab152018-03-02 13:08:36 -08002178 mActiveLogs.add(
2179 new ActiveLog(reason, packageName, enable, System.currentTimeMillis()));
Marie Janssen59804562016-12-28 14:13:21 -08002180 }
Zhihai Xu401202b2012-12-03 11:36:21 -08002181 }
2182
Marie Janssene54b4222017-03-16 18:10:59 -07002183 private void addCrashLog() {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002184 synchronized (mCrashTimestamps) {
2185 if (mCrashTimestamps.size() == CRASH_LOG_MAX_SIZE) {
2186 mCrashTimestamps.removeFirst();
2187 }
2188 mCrashTimestamps.add(System.currentTimeMillis());
2189 mCrashes++;
2190 }
Marie Janssene54b4222017-03-16 18:10:59 -07002191 }
2192
Marie Janssen2977c3e2016-11-09 12:01:24 -08002193 private void recoverBluetoothServiceFromError(boolean clearBle) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002194 Slog.e(TAG, "recoverBluetoothServiceFromError");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07002195 try {
2196 mBluetoothLock.readLock().lock();
Zhihai Xudd9d17d2013-01-08 17:05:58 -08002197 if (mBluetooth != null) {
2198 //Unregister callback object
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07002199 mBluetooth.unregisterCallback(mBluetoothCallback);
Zhihai Xudd9d17d2013-01-08 17:05:58 -08002200 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07002201 } catch (RemoteException re) {
2202 Slog.e(TAG, "Unable to unregister", re);
2203 } finally {
2204 mBluetoothLock.readLock().unlock();
Zhihai Xudd9d17d2013-01-08 17:05:58 -08002205 }
2206
2207 SystemClock.sleep(500);
2208
2209 // disable
Jack He8caab152018-03-02 13:08:36 -08002210 addActiveLog(BluetoothProtoEnums.ENABLE_DISABLE_REASON_START_ERROR,
2211 mContext.getPackageName(), false);
Zhihai Xudd9d17d2013-01-08 17:05:58 -08002212 handleDisable();
2213
2214 waitForOnOff(false, true);
2215
2216 sendBluetoothServiceDownCallback();
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07002217
Pavlin Radoslavove957a8a2016-05-24 15:28:41 -07002218 try {
2219 mBluetoothLock.writeLock().lock();
2220 if (mBluetooth != null) {
2221 mBluetooth = null;
2222 // Unbind
2223 mContext.unbindService(mConnection);
2224 }
2225 mBluetoothGatt = null;
2226 } finally {
2227 mBluetoothLock.writeLock().unlock();
Zhihai Xudd9d17d2013-01-08 17:05:58 -08002228 }
2229
2230 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
2231 mState = BluetoothAdapter.STATE_OFF;
2232
Marie Janssen2977c3e2016-11-09 12:01:24 -08002233 if (clearBle) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002234 clearBleApps();
Marie Janssen2977c3e2016-11-09 12:01:24 -08002235 }
2236
Zhihai Xudd9d17d2013-01-08 17:05:58 -08002237 mEnable = false;
2238
2239 if (mErrorRecoveryRetryCounter++ < MAX_ERROR_RESTART_RETRIES) {
2240 // Send a Bluetooth Restart message to reenable bluetooth
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002241 Message restartMsg = mHandler.obtainMessage(MESSAGE_RESTART_BLUETOOTH_SERVICE);
Zhihai Xudd9d17d2013-01-08 17:05:58 -08002242 mHandler.sendMessageDelayed(restartMsg, ERROR_RESTART_TIME_MS);
2243 } else {
2244 // todo: notify user to power down and power up phone to make bluetooth work.
2245 }
2246 }
Mike Lockwood726d4de2014-10-28 14:06:28 -07002247
Lenka Trochtova63d5e4a72016-12-02 12:19:39 +01002248 private boolean isBluetoothDisallowed() {
2249 long callingIdentity = Binder.clearCallingIdentity();
2250 try {
2251 return mContext.getSystemService(UserManager.class)
2252 .hasUserRestriction(UserManager.DISALLOW_BLUETOOTH, UserHandle.SYSTEM);
2253 } finally {
2254 Binder.restoreCallingIdentity(callingIdentity);
2255 }
2256 }
2257
Lenka Trochtovac6f0e232017-01-17 10:35:49 +01002258 /**
2259 * Disables BluetoothOppLauncherActivity component, so the Bluetooth sharing option is not
Pavel Grafov4f4f6f82017-03-28 13:44:04 +01002260 * offered to the user if Bluetooth or sharing is disallowed. Puts the component to its default
2261 * state if Bluetooth is not disallowed.
Lenka Trochtovac6f0e232017-01-17 10:35:49 +01002262 *
Pavel Grafov4f4f6f82017-03-28 13:44:04 +01002263 * @param userId user to disable bluetooth sharing for.
2264 * @param bluetoothSharingDisallowed whether bluetooth sharing is disallowed.
Lenka Trochtovac6f0e232017-01-17 10:35:49 +01002265 */
Pavel Grafov4f4f6f82017-03-28 13:44:04 +01002266 private void updateOppLauncherComponentState(int userId, boolean bluetoothSharingDisallowed) {
Lenka Trochtovac6f0e232017-01-17 10:35:49 +01002267 final ComponentName oppLauncherComponent = new ComponentName("com.android.bluetooth",
2268 "com.android.bluetooth.opp.BluetoothOppLauncherActivity");
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002269 final int newState =
2270 bluetoothSharingDisallowed ? PackageManager.COMPONENT_ENABLED_STATE_DISABLED
2271 : PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
Lenka Trochtovac6f0e232017-01-17 10:35:49 +01002272 try {
Pavel Grafov4f4f6f82017-03-28 13:44:04 +01002273 final IPackageManager imp = AppGlobals.getPackageManager();
Myles Watson6291fae2017-06-29 03:12:02 -07002274 imp.setComponentEnabledSetting(oppLauncherComponent, newState,
2275 PackageManager.DONT_KILL_APP, userId);
Lenka Trochtovac6f0e232017-01-17 10:35:49 +01002276 } catch (Exception e) {
2277 // The component was not found, do nothing.
2278 }
2279 }
2280
Mike Lockwood726d4de2014-10-28 14:06:28 -07002281 @Override
Pavlin Radoslavov6e8faff2016-02-23 11:54:37 -08002282 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002283 if (!DumpUtils.checkDumpPermission(mContext, TAG, writer)) {
2284 return;
2285 }
Pavlin Radoslavov6e8faff2016-02-23 11:54:37 -08002286 String errorMsg = null;
Marie Janssen59804562016-12-28 14:13:21 -08002287
2288 boolean protoOut = (args.length > 0) && args[0].startsWith("--proto");
2289
2290 if (!protoOut) {
2291 writer.println("Bluetooth Status");
2292 writer.println(" enabled: " + isEnabled());
2293 writer.println(" state: " + BluetoothAdapter.nameForState(mState));
2294 writer.println(" address: " + mAddress);
2295 writer.println(" name: " + mName);
2296 if (mEnable) {
Marie Janssen12a35012017-06-26 07:21:03 -07002297 long onDuration = SystemClock.elapsedRealtime() - mLastEnabledTime;
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002298 String onDurationString = String.format(Locale.US, "%02d:%02d:%02d.%03d",
2299 (int) (onDuration / (1000 * 60 * 60)),
2300 (int) ((onDuration / (1000 * 60)) % 60), (int) ((onDuration / 1000) % 60),
2301 (int) (onDuration % 1000));
Andre Eisenbache66e1682017-04-10 13:49:13 -07002302 writer.println(" time since enabled: " + onDurationString);
Marie Janssen59804562016-12-28 14:13:21 -08002303 }
2304
Marie Janssena95924d2017-01-18 09:37:52 -08002305 if (mActiveLogs.size() == 0) {
Andre Eisenbache66e1682017-04-10 13:49:13 -07002306 writer.println("\nBluetooth never enabled!");
Marie Janssena95924d2017-01-18 09:37:52 -08002307 } else {
Andre Eisenbache66e1682017-04-10 13:49:13 -07002308 writer.println("\nEnable log:");
Marie Janssena95924d2017-01-18 09:37:52 -08002309 for (ActiveLog log : mActiveLogs) {
2310 writer.println(" " + log);
2311 }
Marie Janssen59804562016-12-28 14:13:21 -08002312 }
2313
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002314 writer.println(
2315 "\nBluetooth crashed " + mCrashes + " time" + (mCrashes == 1 ? "" : "s"));
2316 if (mCrashes == CRASH_LOG_MAX_SIZE) {
2317 writer.println("(last " + CRASH_LOG_MAX_SIZE + ")");
2318 }
Marie Janssene54b4222017-03-16 18:10:59 -07002319 for (Long time : mCrashTimestamps) {
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002320 writer.println(" " + timeToLog(time));
Marie Janssene54b4222017-03-16 18:10:59 -07002321 }
2322
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002323 writer.println("\n" + mBleApps.size() + " BLE app" + (mBleApps.size() == 1 ? "" : "s")
2324 + "registered");
Marie Janssen59804562016-12-28 14:13:21 -08002325 for (ClientDeathRecipient app : mBleApps.values()) {
Marie Janssena95924d2017-01-18 09:37:52 -08002326 writer.println(" " + app.getPackageName());
Marie Janssen59804562016-12-28 14:13:21 -08002327 }
2328
Marie Janssena95924d2017-01-18 09:37:52 -08002329 writer.println("");
Marie Janssen59804562016-12-28 14:13:21 -08002330 writer.flush();
Marie Janssenf5ec5382017-01-03 11:37:38 -08002331 if (args.length == 0) {
Marie Janssena95924d2017-01-18 09:37:52 -08002332 // Add arg to produce output
2333 args = new String[1];
2334 args[0] = "--print";
Marie Janssenf5ec5382017-01-03 11:37:38 -08002335 }
Marie Janssen59804562016-12-28 14:13:21 -08002336 }
2337
Pavlin Radoslavov6e8faff2016-02-23 11:54:37 -08002338 if (mBluetoothBinder == null) {
2339 errorMsg = "Bluetooth Service not connected";
2340 } else {
2341 try {
2342 mBluetoothBinder.dump(fd, args);
2343 } catch (RemoteException re) {
Marie Janssen59804562016-12-28 14:13:21 -08002344 errorMsg = "RemoteException while dumping Bluetooth Service";
Pavlin Radoslavov6e8faff2016-02-23 11:54:37 -08002345 }
Mike Lockwood726d4de2014-10-28 14:06:28 -07002346 }
Pavlin Radoslavov6e8faff2016-02-23 11:54:37 -08002347 if (errorMsg != null) {
2348 // Silently return if we are extracting metrics in Protobuf format
Myles Watsonb5cd11a2017-11-27 16:42:11 -08002349 if (protoOut) {
2350 return;
2351 }
Pavlin Radoslavov6e8faff2016-02-23 11:54:37 -08002352 writer.println(errorMsg);
2353 }
Mike Lockwood726d4de2014-10-28 14:06:28 -07002354 }
Jack He8caab152018-03-02 13:08:36 -08002355
2356 private static String getEnableDisableReasonString(int reason) {
2357 switch (reason) {
2358 case BluetoothProtoEnums.ENABLE_DISABLE_REASON_APPLICATION_REQUEST:
2359 return "APPLICATION_REQUEST";
2360 case BluetoothProtoEnums.ENABLE_DISABLE_REASON_AIRPLANE_MODE:
2361 return "AIRPLANE_MODE";
2362 case BluetoothProtoEnums.ENABLE_DISABLE_REASON_DISALLOWED:
2363 return "DISALLOWED";
2364 case BluetoothProtoEnums.ENABLE_DISABLE_REASON_RESTARTED:
2365 return "RESTARTED";
2366 case BluetoothProtoEnums.ENABLE_DISABLE_REASON_START_ERROR:
2367 return "START_ERROR";
2368 case BluetoothProtoEnums.ENABLE_DISABLE_REASON_SYSTEM_BOOT:
2369 return "SYSTEM_BOOT";
2370 case BluetoothProtoEnums.ENABLE_DISABLE_REASON_CRASH:
2371 return "CRASH";
2372 case BluetoothProtoEnums.ENABLE_DISABLE_REASON_USER_SWITCH:
2373 return "USER_SWITCH";
2374 case BluetoothProtoEnums.ENABLE_DISABLE_REASON_RESTORE_USER_SETTING:
2375 return "RESTORE_USER_SETTING";
2376 case BluetoothProtoEnums.ENABLE_DISABLE_REASON_UNSPECIFIED:
2377 default: return "UNKNOWN[" + reason + "]";
2378 }
2379 }
fredc0f420372012-04-12 00:02:00 -07002380}