blob: 6c4895c91f27bffec5ff4b2d9429599977c57990 [file] [log] [blame]
fredc0f420372012-04-12 00:02:00 -07001/*
Zhihai Xufa0fd392012-10-23 17:31:56 -07002 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
fredc0f420372012-04-12 00:02:00 -070015 */
16
17package com.android.server;
18
Svet Ganov408abf72015-05-12 19:13:36 -070019import android.Manifest;
Zhihai Xu40874a02012-10-08 17:57:03 -070020import android.app.ActivityManager;
fredc0f420372012-04-12 00:02:00 -070021import android.bluetooth.BluetoothAdapter;
Benjamin Franze8b98922014-11-12 15:57:54 +000022import android.bluetooth.BluetoothProfile;
fredc0f420372012-04-12 00:02:00 -070023import android.bluetooth.IBluetooth;
fredcbf072a72012-05-09 16:52:50 -070024import android.bluetooth.IBluetoothCallback;
Wei Wange4a744b2015-06-11 17:50:29 -070025import android.bluetooth.IBluetoothGatt;
Benjamin Franze8b98922014-11-12 15:57:54 +000026import android.bluetooth.IBluetoothHeadset;
fredc0f420372012-04-12 00:02:00 -070027import android.bluetooth.IBluetoothManager;
28import android.bluetooth.IBluetoothManagerCallback;
Benjamin Franze8b98922014-11-12 15:57:54 +000029import android.bluetooth.IBluetoothProfileServiceConnection;
fredc0f420372012-04-12 00:02:00 -070030import android.bluetooth.IBluetoothStateChangeCallback;
Svet Ganov77df6f32016-08-17 11:46:34 -070031import android.content.ActivityNotFoundException;
fredc0f420372012-04-12 00:02:00 -070032import android.content.BroadcastReceiver;
33import android.content.ComponentName;
34import android.content.ContentResolver;
35import android.content.Context;
36import android.content.Intent;
37import android.content.IntentFilter;
38import android.content.ServiceConnection;
Svetoslav Ganovac69be52016-06-29 17:31:44 -070039import android.content.pm.ApplicationInfo;
Matthew Xie32ab77b2013-05-08 19:26:57 -070040import android.content.pm.PackageManager;
Benjamin Franze8b98922014-11-12 15:57:54 +000041import android.content.pm.UserInfo;
Wei Wange4a744b2015-06-11 17:50:29 -070042import android.database.ContentObserver;
Zhihai Xu40874a02012-10-08 17:57:03 -070043import android.os.Binder;
Svetoslav Ganovac69be52016-06-29 17:31:44 -070044import android.os.Build;
Lenka Trochtova63d5e4a72016-12-02 12:19:39 +010045import android.os.Bundle;
fredc0f420372012-04-12 00:02:00 -070046import android.os.Handler;
fredc0f420372012-04-12 00:02:00 -070047import android.os.IBinder;
Zhihai Xu40874a02012-10-08 17:57:03 -070048import android.os.Looper;
fredc0f420372012-04-12 00:02:00 -070049import android.os.Message;
Zhihai Xu40874a02012-10-08 17:57:03 -070050import android.os.Process;
fredcd6883532012-04-25 17:46:13 -070051import android.os.RemoteCallbackList;
fredc0f420372012-04-12 00:02:00 -070052import android.os.RemoteException;
Lenka Trochtovac6f0e232017-01-17 10:35:49 +010053import android.os.ServiceManager;
Zhihai Xu40874a02012-10-08 17:57:03 -070054import android.os.SystemClock;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070055import android.os.UserHandle;
Benjamin Franze8b98922014-11-12 15:57:54 +000056import android.os.UserManager;
Lenka Trochtova63d5e4a72016-12-02 12:19:39 +010057import android.os.UserManagerInternal;
58import android.os.UserManagerInternal.UserRestrictionsListener;
fredc0f420372012-04-12 00:02:00 -070059import android.provider.Settings;
Wei Wang67d84162015-04-26 17:04:29 -070060import android.provider.Settings.SettingNotFoundException;
Jeff Sharkey67609c72016-03-05 14:29:13 -070061import android.util.Slog;
Mike Lockwood726d4de2014-10-28 14:06:28 -070062
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060063import com.android.internal.util.DumpUtils;
Lenka Trochtovac6f0e232017-01-17 10:35:49 +010064import com.android.server.pm.PackageManagerService;
65
Mike Lockwood726d4de2014-10-28 14:06:28 -070066import java.io.FileDescriptor;
67import java.io.PrintWriter;
Marie Janssen2977c3e2016-11-09 12:01:24 -080068import java.util.concurrent.ConcurrentHashMap;
Marie Janssen59804562016-12-28 14:13:21 -080069import java.util.concurrent.locks.ReentrantReadWriteLock;
Benjamin Franze8b98922014-11-12 15:57:54 +000070import java.util.HashMap;
Marie Janssen59804562016-12-28 14:13:21 -080071import java.util.LinkedList;
Benjamin Franze8b98922014-11-12 15:57:54 +000072import java.util.Map;
Miao Chou658bf2f2015-06-26 17:14:35 -070073
Marie Janssen59804562016-12-28 14:13:21 -080074
fredc0f420372012-04-12 00:02:00 -070075class BluetoothManagerService extends IBluetoothManager.Stub {
76 private static final String TAG = "BluetoothManagerService";
Pavlin Radoslavov41401112016-06-27 15:25:18 -070077 private static final boolean DBG = true;
fredc0f420372012-04-12 00:02:00 -070078
fredc0f420372012-04-12 00:02:00 -070079 private static final String BLUETOOTH_ADMIN_PERM = android.Manifest.permission.BLUETOOTH_ADMIN;
80 private static final String BLUETOOTH_PERM = android.Manifest.permission.BLUETOOTH;
Marie Janssene54b4222017-03-16 18:10:59 -070081
Zhihai Xud31c3222012-10-31 16:08:57 -070082 private static final String SECURE_SETTINGS_BLUETOOTH_ADDR_VALID="bluetooth_addr_valid";
fredc0f420372012-04-12 00:02:00 -070083 private static final String SECURE_SETTINGS_BLUETOOTH_ADDRESS="bluetooth_address";
84 private static final String SECURE_SETTINGS_BLUETOOTH_NAME="bluetooth_name";
Marie Janssene54b4222017-03-16 18:10:59 -070085
86 private static final int ACTIVE_LOG_MAX_SIZE = 20;
87 private static final int CRASH_LOG_MAX_SIZE = 100;
Ajay Panicker467bc042017-02-22 12:23:15 -080088 private static final String REASON_AIRPLANE_MODE = "airplane mode";
Marie Janssene54b4222017-03-16 18:10:59 -070089 private static final String REASON_RESTARTED = "automatic restart";
90 private static final String REASON_START_CRASH = "turn-on crash";
Ajay Panicker467bc042017-02-22 12:23:15 -080091 private static final String REASON_SYSTEM_BOOT = "system boot";
Marie Janssene54b4222017-03-16 18:10:59 -070092 private static final String REASON_UNEXPECTED = "unexpected crash";
93 private static final String REASON_USER_SWITCH = "user switch";
94
fredc0f420372012-04-12 00:02:00 -070095 private static final int TIMEOUT_BIND_MS = 3000; //Maximum msec to wait for a bind
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +053096 //Maximum msec to wait for service restart
97 private static final int SERVICE_RESTART_TIME_MS = 200;
Zhihai Xudd9d17d2013-01-08 17:05:58 -080098 //Maximum msec to wait for restart due to error
99 private static final int ERROR_RESTART_TIME_MS = 3000;
Zhihai Xu40874a02012-10-08 17:57:03 -0700100 //Maximum msec to delay MESSAGE_USER_SWITCHED
101 private static final int USER_SWITCHED_TIME_MS = 200;
Benjamin Franze8b98922014-11-12 15:57:54 +0000102 // Delay for the addProxy function in msec
103 private static final int ADD_PROXY_DELAY_MS = 100;
fredc0f420372012-04-12 00:02:00 -0700104
105 private static final int MESSAGE_ENABLE = 1;
106 private static final int MESSAGE_DISABLE = 2;
fredc649fe492012-04-19 01:07:18 -0700107 private static final int MESSAGE_REGISTER_ADAPTER = 20;
108 private static final int MESSAGE_UNREGISTER_ADAPTER = 21;
109 private static final int MESSAGE_REGISTER_STATE_CHANGE_CALLBACK = 30;
110 private static final int MESSAGE_UNREGISTER_STATE_CHANGE_CALLBACK = 31;
111 private static final int MESSAGE_BLUETOOTH_SERVICE_CONNECTED = 40;
112 private static final int MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED = 41;
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +0530113 private static final int MESSAGE_RESTART_BLUETOOTH_SERVICE = 42;
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -0700114 private static final int MESSAGE_BLUETOOTH_STATE_CHANGE = 60;
115 private static final int MESSAGE_TIMEOUT_BIND = 100;
116 private static final int MESSAGE_TIMEOUT_UNBIND = 101;
Ajay Panicker4bb48302016-03-31 14:14:27 -0700117 private static final int MESSAGE_GET_NAME_AND_ADDRESS = 200;
Zhihai Xu40874a02012-10-08 17:57:03 -0700118 private static final int MESSAGE_USER_SWITCHED = 300;
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -0700119 private static final int MESSAGE_USER_UNLOCKED = 301;
Benjamin Franze8b98922014-11-12 15:57:54 +0000120 private static final int MESSAGE_ADD_PROXY_DELAYED = 400;
121 private static final int MESSAGE_BIND_PROFILE_SERVICE = 401;
Marie Janssencb21ad72016-12-13 10:51:02 -0800122
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -0700123 private static final int MAX_SAVE_RETRIES = 3;
124 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
127 private static final int BLUETOOTH_OFF=0;
128 // Bluetooth persisted setting is on
129 // and Airplane mode won't affect Bluetooth state at start up
130 private static final int BLUETOOTH_ON_BLUETOOTH=1;
131 // Bluetooth persisted setting is on
132 // but Airplane mode will affect Bluetooth state at start up
133 // and Airplane mode will have higher priority.
134 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;
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700151 private final ReentrantReadWriteLock mBluetoothLock =
152 new ReentrantReadWriteLock();
fredc649fe492012-04-19 01:07:18 -0700153 private boolean mBinding;
154 private boolean mUnbinding;
Marie Janssen59804562016-12-28 14:13:21 -0800155
Zhihai Xu401202b2012-12-03 11:36:21 -0800156 // used inside handler thread
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700157 private boolean mQuietEnable = false;
Marie Janssen59804562016-12-28 14:13:21 -0800158 private boolean mEnable;
159
Marie Janssene54b4222017-03-16 18:10:59 -0700160 private CharSequence timeToLog(long timestamp) {
161 return android.text.format.DateFormat.format("MM-dd HH:mm:ss", timestamp);
162 }
163
Marie Janssen59804562016-12-28 14:13:21 -0800164 /**
165 * Used for tracking apps that enabled / disabled Bluetooth.
166 */
167 private class ActiveLog {
168 private String mPackageName;
169 private boolean mEnable;
170 private long mTimestamp;
171
172 public ActiveLog(String packageName, boolean enable, long timestamp) {
173 mPackageName = packageName;
174 mEnable = enable;
175 mTimestamp = timestamp;
176 }
177
178 public long getTime() {
179 return mTimestamp;
180 }
181
182 public String toString() {
Marie Janssene54b4222017-03-16 18:10:59 -0700183 return timeToLog(mTimestamp) + (mEnable ? " Enabled " : " Disabled ") + " by "
184 + mPackageName;
Marie Janssen59804562016-12-28 14:13:21 -0800185 }
186
187 }
188
189 private LinkedList<ActiveLog> mActiveLogs;
Marie Janssene54b4222017-03-16 18:10:59 -0700190 private LinkedList<Long> mCrashTimestamps;
191 private int mCrashes;
Marie Janssen59804562016-12-28 14:13:21 -0800192
193 // configuration from external IBinder call which is used to
Zhihai Xu401202b2012-12-03 11:36:21 -0800194 // synchronize with broadcast receiver.
195 private boolean mQuietEnableExternal;
Zhihai Xu401202b2012-12-03 11:36:21 -0800196 private boolean mEnableExternal;
Marie Janssen59804562016-12-28 14:13:21 -0800197
198 // Map of apps registered to keep BLE scanning on.
199 private Map<IBinder, ClientDeathRecipient> mBleApps = new ConcurrentHashMap<IBinder, ClientDeathRecipient>();
200
Zhihai Xu40874a02012-10-08 17:57:03 -0700201 private int mState;
Zhihai Xu40874a02012-10-08 17:57:03 -0700202 private final BluetoothHandler mHandler;
Zhihai Xudd9d17d2013-01-08 17:05:58 -0800203 private int mErrorRecoveryRetryCounter;
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200204 private final int mSystemUiUid;
fredc0f420372012-04-12 00:02:00 -0700205
Benjamin Franze8b98922014-11-12 15:57:54 +0000206 // Save a ProfileServiceConnections object for each of the bound
207 // bluetooth profile services
208 private final Map <Integer, ProfileServiceConnections> mProfileServices =
209 new HashMap <Integer, ProfileServiceConnections>();
210
Svetoslav Ganovac69be52016-06-29 17:31:44 -0700211 private final boolean mPermissionReviewRequired;
212
Marie Janssen59804562016-12-28 14:13:21 -0800213 private final IBluetoothCallback mBluetoothCallback = new IBluetoothCallback.Stub() {
fredcbf072a72012-05-09 16:52:50 -0700214 @Override
215 public void onBluetoothStateChange(int prevState, int newState) throws RemoteException {
216 Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_STATE_CHANGE,prevState,newState);
217 mHandler.sendMessage(msg);
218 }
219 };
220
Lenka Trochtova63d5e4a72016-12-02 12:19:39 +0100221 private final UserRestrictionsListener mUserRestrictionsListener =
222 new UserRestrictionsListener() {
223 @Override
224 public void onUserRestrictionsChanged(int userId, Bundle newRestrictions,
225 Bundle prevRestrictions) {
Lenka Trochtovac6f0e232017-01-17 10:35:49 +0100226 if (!newRestrictions.containsKey(UserManager.DISALLOW_BLUETOOTH)
227 && !prevRestrictions.containsKey(UserManager.DISALLOW_BLUETOOTH)) {
228 // The relevant restriction has not changed - do nothing.
229 return;
230 }
Lenka Trochtova63d5e4a72016-12-02 12:19:39 +0100231 final boolean bluetoothDisallowed =
232 newRestrictions.getBoolean(UserManager.DISALLOW_BLUETOOTH);
233 if ((mEnable || mEnableExternal) && bluetoothDisallowed) {
234 try {
235 disable(null, true);
236 } catch (RemoteException e) {
237 Slog.w(TAG, "Exception when disabling Bluetooth from UserRestrictionsListener",
238 e);
239 }
240 }
Lenka Trochtovac6f0e232017-01-17 10:35:49 +0100241 updateOppLauncherComponentState(bluetoothDisallowed);
Lenka Trochtova63d5e4a72016-12-02 12:19:39 +0100242 }
243 };
244
Ajay Panicker467bc042017-02-22 12:23:15 -0800245 private final ContentObserver mAirplaneModeObserver = new ContentObserver(null) {
246 @Override
247 public void onChange(boolean unused) {
248 synchronized(this) {
249 if (isBluetoothPersistedStateOn()) {
250 if (isAirplaneModeOn()) {
251 persistBluetoothSetting(BLUETOOTH_ON_AIRPLANE);
252 } else {
253 persistBluetoothSetting(BLUETOOTH_ON_BLUETOOTH);
254 }
255 }
256
257 int st = BluetoothAdapter.STATE_OFF;
258 try {
259 mBluetoothLock.readLock().lock();
260 if (mBluetooth != null) {
261 st = mBluetooth.getState();
262 }
263 } catch (RemoteException e) {
264 Slog.e(TAG, "Unable to call getState", e);
265 return;
266 } finally {
267 mBluetoothLock.readLock().unlock();
268 }
269
270 Slog.d(TAG, "Airplane Mode change - current state: " +
271 BluetoothAdapter.nameForState(st));
272
273 if (isAirplaneModeOn()) {
274 // Clear registered LE apps to force shut-off
275 clearBleApps();
276
277 // If state is BLE_ON make sure we trigger disableBLE
278 if (st == BluetoothAdapter.STATE_BLE_ON) {
279 try {
280 mBluetoothLock.readLock().lock();
281 if (mBluetooth != null) {
282 mBluetooth.onBrEdrDown();
283 mEnable = false;
284 mEnableExternal = false;
285 }
286 } catch (RemoteException e) {
287 Slog.e(TAG,"Unable to call onBrEdrDown", e);
288 } finally {
289 mBluetoothLock.readLock().unlock();
290 }
291 } else if (st == BluetoothAdapter.STATE_ON){
292 sendDisableMsg(REASON_AIRPLANE_MODE);
293 }
294 } else if (mEnableExternal) {
295 sendEnableMsg(mQuietEnableExternal, REASON_AIRPLANE_MODE);
296 }
297 }
298 }
299 };
300
fredcbf072a72012-05-09 16:52:50 -0700301 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
fredc0f420372012-04-12 00:02:00 -0700302 @Override
303 public void onReceive(Context context, Intent intent) {
304 String action = intent.getAction();
fredcbf072a72012-05-09 16:52:50 -0700305 if (BluetoothAdapter.ACTION_LOCAL_NAME_CHANGED.equals(action)) {
fredc0f420372012-04-12 00:02:00 -0700306 String newName = intent.getStringExtra(BluetoothAdapter.EXTRA_LOCAL_NAME);
Jeff Sharkey67609c72016-03-05 14:29:13 -0700307 if (DBG) Slog.d(TAG, "Bluetooth Adapter name changed to " + newName);
fredc0f420372012-04-12 00:02:00 -0700308 if (newName != null) {
309 storeNameAndAddress(newName, null);
310 }
311 }
312 }
313 };
314
315 BluetoothManagerService(Context context) {
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700316 mHandler = new BluetoothHandler(IoThread.get().getLooper());
Zhihai Xu40874a02012-10-08 17:57:03 -0700317
fredc0f420372012-04-12 00:02:00 -0700318 mContext = context;
Svetoslav Ganovac69be52016-06-29 17:31:44 -0700319
Svet Ganov77df6f32016-08-17 11:46:34 -0700320 mPermissionReviewRequired = context.getResources().getBoolean(
Svetoslav Ganovac69be52016-06-29 17:31:44 -0700321 com.android.internal.R.bool.config_permissionReviewRequired);
322
Marie Janssen59804562016-12-28 14:13:21 -0800323 mActiveLogs = new LinkedList<ActiveLog>();
Marie Janssene54b4222017-03-16 18:10:59 -0700324 mCrashTimestamps = new LinkedList<Long>();
325 mCrashes = 0;
fredc0f420372012-04-12 00:02:00 -0700326 mBluetooth = null;
Marie Janssen9db28eb2016-01-12 16:05:15 -0800327 mBluetoothBinder = null;
Nitin Arorad055adb2015-03-02 15:03:51 -0800328 mBluetoothGatt = null;
fredc0f420372012-04-12 00:02:00 -0700329 mBinding = false;
330 mUnbinding = false;
Zhihai Xu40874a02012-10-08 17:57:03 -0700331 mEnable = false;
332 mState = BluetoothAdapter.STATE_OFF;
Zhihai Xu401202b2012-12-03 11:36:21 -0800333 mQuietEnableExternal = false;
334 mEnableExternal = false;
fredc0f420372012-04-12 00:02:00 -0700335 mAddress = null;
336 mName = null;
Zhihai Xudd9d17d2013-01-08 17:05:58 -0800337 mErrorRecoveryRetryCounter = 0;
fredc0f420372012-04-12 00:02:00 -0700338 mContentResolver = context.getContentResolver();
Wei Wange4a744b2015-06-11 17:50:29 -0700339 // Observe BLE scan only mode settings change.
340 registerForBleScanModeChange();
fredcd6883532012-04-25 17:46:13 -0700341 mCallbacks = new RemoteCallbackList<IBluetoothManagerCallback>();
342 mStateChangeCallbacks = new RemoteCallbackList<IBluetoothStateChangeCallback>();
Miao Chou658bf2f2015-06-26 17:14:35 -0700343 IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_LOCAL_NAME_CHANGED);
Dianne Hackbornd83a0962014-05-02 16:28:33 -0700344 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
Matthew Xie6fde3092012-07-11 17:10:07 -0700345 mContext.registerReceiver(mReceiver, filter);
fredc0f420372012-04-12 00:02:00 -0700346 loadStoredNameAndAddress();
Zhihai Xu401202b2012-12-03 11:36:21 -0800347 if (isBluetoothPersistedStateOn()) {
Marie Janssen9fa24912016-10-18 10:04:24 -0700348 if (DBG) Slog.d(TAG, "Startup: Bluetooth persisted state is ON.");
Zhihai Xu401202b2012-12-03 11:36:21 -0800349 mEnableExternal = true;
fredc0f420372012-04-12 00:02:00 -0700350 }
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200351
Ajay Panicker467bc042017-02-22 12:23:15 -0800352 String airplaneModeRadios = Settings.Global.getString(mContentResolver,
353 Settings.Global.AIRPLANE_MODE_RADIOS);
354 if (airplaneModeRadios == null ||
355 airplaneModeRadios.contains(Settings.Global.RADIO_BLUETOOTH)) {
356 mContentResolver.registerContentObserver(
357 Settings.Global.getUriFor(Settings.Global.AIRPLANE_MODE_ON),
358 true, mAirplaneModeObserver);
359 }
360
Marie Janssen59804562016-12-28 14:13:21 -0800361 int systemUiUid = -1;
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200362 try {
Marie Janssen59804562016-12-28 14:13:21 -0800363 systemUiUid = mContext.getPackageManager().getPackageUidAsUser("com.android.systemui",
Jeff Sharkeyc5967e92016-01-07 18:50:29 -0700364 PackageManager.MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM);
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200365 } catch (PackageManager.NameNotFoundException e) {
Joe LaPennaacddf2b2015-09-04 12:52:42 -0700366 // Some platforms, such as wearables do not have a system ui.
Jeff Sharkey67609c72016-03-05 14:29:13 -0700367 Slog.w(TAG, "Unable to resolve SystemUI's UID.", e);
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200368 }
Marie Janssen59804562016-12-28 14:13:21 -0800369 mSystemUiUid = systemUiUid;
fredc0f420372012-04-12 00:02:00 -0700370 }
371
fredc649fe492012-04-19 01:07:18 -0700372 /**
373 * Returns true if airplane mode is currently on
374 */
375 private final boolean isAirplaneModeOn() {
Christopher Tatec09cdce2012-09-10 16:50:14 -0700376 return Settings.Global.getInt(mContext.getContentResolver(),
377 Settings.Global.AIRPLANE_MODE_ON, 0) == 1;
fredc649fe492012-04-19 01:07:18 -0700378 }
379
380 /**
381 * Returns true if the Bluetooth saved state is "on"
382 */
383 private final boolean isBluetoothPersistedStateOn() {
Marie Janssen9fa24912016-10-18 10:04:24 -0700384 int state = Settings.Global.getInt(mContentResolver,
385 Settings.Global.BLUETOOTH_ON, -1);
386 if (DBG) Slog.d(TAG, "Bluetooth persisted state: " + state);
387 return state != BLUETOOTH_OFF;
Zhihai Xu401202b2012-12-03 11:36:21 -0800388 }
389
390 /**
391 * Returns true if the Bluetooth saved state is BLUETOOTH_ON_BLUETOOTH
392 */
393 private final boolean isBluetoothPersistedStateOnBluetooth() {
394 return Settings.Global.getInt(mContentResolver,
Andre Eisenbach8c184312016-09-06 18:03:10 -0700395 Settings.Global.BLUETOOTH_ON, BLUETOOTH_ON_BLUETOOTH) == BLUETOOTH_ON_BLUETOOTH;
fredc649fe492012-04-19 01:07:18 -0700396 }
397
398 /**
399 * Save the Bluetooth on/off state
fredc649fe492012-04-19 01:07:18 -0700400 */
Zhihai Xu401202b2012-12-03 11:36:21 -0800401 private void persistBluetoothSetting(int value) {
Marie Janssen9fa24912016-10-18 10:04:24 -0700402 if (DBG) Slog.d(TAG, "Persisting Bluetooth Setting: " + value);
Marie Janssenfa630682016-12-15 13:51:30 -0800403 // waive WRITE_SECURE_SETTINGS permission check
404 long callingIdentity = Binder.clearCallingIdentity();
Jeff Brownbf6f6f92012-09-25 15:03:20 -0700405 Settings.Global.putInt(mContext.getContentResolver(),
406 Settings.Global.BLUETOOTH_ON,
Zhihai Xu401202b2012-12-03 11:36:21 -0800407 value);
Marie Janssenfa630682016-12-15 13:51:30 -0800408 Binder.restoreCallingIdentity(callingIdentity);
fredc649fe492012-04-19 01:07:18 -0700409 }
410
411 /**
412 * Returns true if the Bluetooth Adapter's name and address is
413 * locally cached
414 * @return
415 */
fredc0f420372012-04-12 00:02:00 -0700416 private boolean isNameAndAddressSet() {
417 return mName !=null && mAddress!= null && mName.length()>0 && mAddress.length()>0;
418 }
419
fredc649fe492012-04-19 01:07:18 -0700420 /**
421 * Retrieve the Bluetooth Adapter's name and address and save it in
422 * in the local cache
423 */
fredc0f420372012-04-12 00:02:00 -0700424 private void loadStoredNameAndAddress() {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700425 if (DBG) Slog.d(TAG, "Loading stored name and address");
Zhihai Xud31c3222012-10-31 16:08:57 -0700426 if (mContext.getResources().getBoolean
427 (com.android.internal.R.bool.config_bluetooth_address_validation) &&
428 Settings.Secure.getInt(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDR_VALID, 0) == 0) {
429 // if the valid flag is not set, don't load the address and name
Jeff Sharkey67609c72016-03-05 14:29:13 -0700430 if (DBG) Slog.d(TAG, "invalid bluetooth name and address stored");
Zhihai Xud31c3222012-10-31 16:08:57 -0700431 return;
432 }
fredc0f420372012-04-12 00:02:00 -0700433 mName = Settings.Secure.getString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_NAME);
434 mAddress = Settings.Secure.getString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDRESS);
Jeff Sharkey67609c72016-03-05 14:29:13 -0700435 if (DBG) Slog.d(TAG, "Stored bluetooth Name=" + mName + ",Address=" + mAddress);
fredc0f420372012-04-12 00:02:00 -0700436 }
437
fredc649fe492012-04-19 01:07:18 -0700438 /**
439 * Save the Bluetooth name and address in the persistent store.
440 * Only non-null values will be saved.
441 * @param name
442 * @param address
443 */
fredc0f420372012-04-12 00:02:00 -0700444 private void storeNameAndAddress(String name, String address) {
445 if (name != null) {
446 Settings.Secure.putString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_NAME, name);
fredc0f420372012-04-12 00:02:00 -0700447 mName = name;
Jeff Sharkey67609c72016-03-05 14:29:13 -0700448 if (DBG) Slog.d(TAG,"Stored Bluetooth name: " +
fredc649fe492012-04-19 01:07:18 -0700449 Settings.Secure.getString(mContentResolver,SECURE_SETTINGS_BLUETOOTH_NAME));
fredc0f420372012-04-12 00:02:00 -0700450 }
451
452 if (address != null) {
453 Settings.Secure.putString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDRESS, address);
fredc0f420372012-04-12 00:02:00 -0700454 mAddress=address;
Jeff Sharkey67609c72016-03-05 14:29:13 -0700455 if (DBG) Slog.d(TAG,"Stored Bluetoothaddress: " +
fredc649fe492012-04-19 01:07:18 -0700456 Settings.Secure.getString(mContentResolver,SECURE_SETTINGS_BLUETOOTH_ADDRESS));
fredc0f420372012-04-12 00:02:00 -0700457 }
Zhihai Xud31c3222012-10-31 16:08:57 -0700458
459 if ((name != null) && (address != null)) {
460 Settings.Secure.putInt(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDR_VALID, 1);
461 }
fredc0f420372012-04-12 00:02:00 -0700462 }
463
464 public IBluetooth registerAdapter(IBluetoothManagerCallback callback){
Natalie Silvanovich55db6462014-05-01 16:12:23 -0700465 if (callback == null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700466 Slog.w(TAG, "Callback is null in registerAdapter");
Natalie Silvanovich55db6462014-05-01 16:12:23 -0700467 return null;
468 }
fredc0f420372012-04-12 00:02:00 -0700469 Message msg = mHandler.obtainMessage(MESSAGE_REGISTER_ADAPTER);
470 msg.obj = callback;
471 mHandler.sendMessage(msg);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700472
473 return mBluetooth;
fredc0f420372012-04-12 00:02:00 -0700474 }
475
476 public void unregisterAdapter(IBluetoothManagerCallback callback) {
Natalie Silvanovich55db6462014-05-01 16:12:23 -0700477 if (callback == null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700478 Slog.w(TAG, "Callback is null in unregisterAdapter");
Natalie Silvanovich55db6462014-05-01 16:12:23 -0700479 return;
480 }
fredc0f420372012-04-12 00:02:00 -0700481 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
482 "Need BLUETOOTH permission");
483 Message msg = mHandler.obtainMessage(MESSAGE_UNREGISTER_ADAPTER);
484 msg.obj = callback;
485 mHandler.sendMessage(msg);
486 }
487
488 public void registerStateChangeCallback(IBluetoothStateChangeCallback callback) {
489 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
490 "Need BLUETOOTH permission");
Marie Janssencb21ad72016-12-13 10:51:02 -0800491 if (callback == null) {
492 Slog.w(TAG, "registerStateChangeCallback: Callback is null!");
493 return;
494 }
fredc0f420372012-04-12 00:02:00 -0700495 Message msg = mHandler.obtainMessage(MESSAGE_REGISTER_STATE_CHANGE_CALLBACK);
496 msg.obj = callback;
497 mHandler.sendMessage(msg);
498 }
499
500 public void unregisterStateChangeCallback(IBluetoothStateChangeCallback callback) {
501 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
502 "Need BLUETOOTH permission");
Marie Janssencb21ad72016-12-13 10:51:02 -0800503 if (callback == null) {
504 Slog.w(TAG, "unregisterStateChangeCallback: Callback is null!");
505 return;
506 }
fredc0f420372012-04-12 00:02:00 -0700507 Message msg = mHandler.obtainMessage(MESSAGE_UNREGISTER_STATE_CHANGE_CALLBACK);
508 msg.obj = callback;
509 mHandler.sendMessage(msg);
510 }
511
512 public boolean isEnabled() {
Zhihai Xu6eb76522012-11-29 15:41:04 -0800513 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
514 (!checkIfCallerIsForegroundUser())) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700515 Slog.w(TAG,"isEnabled(): not allowed for non-active and non system user");
Zhihai Xu40874a02012-10-08 17:57:03 -0700516 return false;
517 }
518
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700519 try {
520 mBluetoothLock.readLock().lock();
521 if (mBluetooth != null) return mBluetooth.isEnabled();
522 } catch (RemoteException e) {
523 Slog.e(TAG, "isEnabled()", e);
524 } finally {
525 mBluetoothLock.readLock().unlock();
fredc0f420372012-04-12 00:02:00 -0700526 }
527 return false;
528 }
529
Christine Hallstrom995c90a2016-05-25 15:49:08 -0700530 public int getState() {
531 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
532 (!checkIfCallerIsForegroundUser())) {
Marie Janssencb21ad72016-12-13 10:51:02 -0800533 Slog.w(TAG, "getState(): report OFF for non-active and non system user");
Christine Hallstrom995c90a2016-05-25 15:49:08 -0700534 return BluetoothAdapter.STATE_OFF;
535 }
536
537 try {
538 mBluetoothLock.readLock().lock();
539 if (mBluetooth != null) return mBluetooth.getState();
540 } catch (RemoteException e) {
541 Slog.e(TAG, "getState()", e);
542 } finally {
543 mBluetoothLock.readLock().unlock();
544 }
545 return BluetoothAdapter.STATE_OFF;
546 }
547
Nitin Arorad055adb2015-03-02 15:03:51 -0800548 class ClientDeathRecipient implements IBinder.DeathRecipient {
Marie Janssen59804562016-12-28 14:13:21 -0800549 private String mPackageName;
550
551 public ClientDeathRecipient(String packageName) {
552 mPackageName = packageName;
553 }
554
Nitin Arorad055adb2015-03-02 15:03:51 -0800555 public void binderDied() {
Marie Janssen59804562016-12-28 14:13:21 -0800556 if (DBG) Slog.d(TAG, "Binder is dead - unregister " + mPackageName);
Marie Janssen2977c3e2016-11-09 12:01:24 -0800557 if (isBleAppPresent()) {
558 // Nothing to do, another app is here.
559 return;
560 }
561 if (DBG) Slog.d(TAG, "Disabling LE only mode after application crash");
562 try {
563 mBluetoothLock.readLock().lock();
564 if (mBluetooth != null &&
565 mBluetooth.getState() == BluetoothAdapter.STATE_BLE_ON) {
566 mEnable = false;
567 mBluetooth.onBrEdrDown();
Nitin Arorad055adb2015-03-02 15:03:51 -0800568 }
Marie Janssen2977c3e2016-11-09 12:01:24 -0800569 } catch (RemoteException e) {
570 Slog.e(TAG,"Unable to call onBrEdrDown", e);
571 } finally {
572 mBluetoothLock.readLock().unlock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800573 }
574 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800575
Marie Janssen59804562016-12-28 14:13:21 -0800576 public String getPackageName() {
577 return mPackageName;
578 }
579 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800580
Wei Wang67d84162015-04-26 17:04:29 -0700581 @Override
582 public boolean isBleScanAlwaysAvailable() {
Marie Janssena80d7452016-10-25 10:47:51 -0700583 if (isAirplaneModeOn() && !mEnable) {
584 return false;
585 }
Wei Wang67d84162015-04-26 17:04:29 -0700586 try {
587 return (Settings.Global.getInt(mContentResolver,
588 Settings.Global.BLE_SCAN_ALWAYS_AVAILABLE)) != 0;
589 } catch (SettingNotFoundException e) {
590 }
591 return false;
592 }
593
Wei Wange4a744b2015-06-11 17:50:29 -0700594 // Monitor change of BLE scan only mode settings.
595 private void registerForBleScanModeChange() {
596 ContentObserver contentObserver = new ContentObserver(null) {
597 @Override
598 public void onChange(boolean selfChange) {
Marie Janssen2977c3e2016-11-09 12:01:24 -0800599 if (isBleScanAlwaysAvailable()) {
600 // Nothing to do
601 return;
602 }
603 // BLE scan is not available.
604 disableBleScanMode();
605 clearBleApps();
606 try {
607 mBluetoothLock.readLock().lock();
608 if (mBluetooth != null) mBluetooth.onBrEdrDown();
609 } catch (RemoteException e) {
610 Slog.e(TAG, "error when disabling bluetooth", e);
611 } finally {
612 mBluetoothLock.readLock().unlock();
Wei Wange4a744b2015-06-11 17:50:29 -0700613 }
614 }
615 };
616
617 mContentResolver.registerContentObserver(
618 Settings.Global.getUriFor(Settings.Global.BLE_SCAN_ALWAYS_AVAILABLE),
619 false, contentObserver);
620 }
621
622 // Disable ble scan only mode.
623 private void disableBleScanMode() {
624 try {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700625 mBluetoothLock.writeLock().lock();
Wei Wange4a744b2015-06-11 17:50:29 -0700626 if (mBluetooth != null && (mBluetooth.getState() != BluetoothAdapter.STATE_ON)) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700627 if (DBG) Slog.d(TAG, "Reseting the mEnable flag for clean disable");
Wei Wange4a744b2015-06-11 17:50:29 -0700628 mEnable = false;
629 }
630 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700631 Slog.e(TAG, "getState()", e);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700632 } finally {
633 mBluetoothLock.writeLock().unlock();
Wei Wange4a744b2015-06-11 17:50:29 -0700634 }
635 }
636
Marie Janssen59804562016-12-28 14:13:21 -0800637 public int updateBleAppCount(IBinder token, boolean enable, String packageName) {
638 ClientDeathRecipient r = mBleApps.get(token);
639 if (r == null && enable) {
640 ClientDeathRecipient deathRec = new ClientDeathRecipient(packageName);
641 try {
642 token.linkToDeath(deathRec, 0);
643 } catch (RemoteException ex) {
644 throw new IllegalArgumentException("BLE app (" + packageName + ") already dead!");
Nitin Arorad055adb2015-03-02 15:03:51 -0800645 }
Marie Janssen59804562016-12-28 14:13:21 -0800646 mBleApps.put(token, deathRec);
647 if (DBG) Slog.d(TAG, "Registered for death of " + packageName);
648 } else if (!enable && r != null) {
649 // Unregister death recipient as the app goes away.
650 token.unlinkToDeath(r, 0);
651 mBleApps.remove(token);
652 if (DBG) Slog.d(TAG, "Unregistered for death of " + packageName);
Nitin Arorad055adb2015-03-02 15:03:51 -0800653 }
Marie Janssen2977c3e2016-11-09 12:01:24 -0800654 int appCount = mBleApps.size();
655 if (DBG) Slog.d(TAG, appCount + " registered Ble Apps");
656 if (appCount == 0 && mEnable) {
Wei Wange4a744b2015-06-11 17:50:29 -0700657 disableBleScanMode();
Nitin Arorad055adb2015-03-02 15:03:51 -0800658 }
Martin Brabhamc2b06222017-02-27 16:55:07 -0800659 if (appCount == 0 && !mEnableExternal) {
660 sendBrEdrDownCallback();
661 }
Marie Janssen2977c3e2016-11-09 12:01:24 -0800662 return appCount;
Nitin Arorad055adb2015-03-02 15:03:51 -0800663 }
664
Wei Wange4a744b2015-06-11 17:50:29 -0700665 // Clear all apps using BLE scan only mode.
666 private void clearBleApps() {
Marie Janssen2977c3e2016-11-09 12:01:24 -0800667 mBleApps.clear();
Wei Wange4a744b2015-06-11 17:50:29 -0700668 }
669
Marie Janssen59804562016-12-28 14:13:21 -0800670 /** @hide */
Nitin Arorad055adb2015-03-02 15:03:51 -0800671 public boolean isBleAppPresent() {
Marie Janssen2977c3e2016-11-09 12:01:24 -0800672 if (DBG) Slog.d(TAG, "isBleAppPresent() count: " + mBleApps.size());
673 return mBleApps.size() > 0;
Nitin Arorad055adb2015-03-02 15:03:51 -0800674 }
675
676 /**
Marie Janssenfa630682016-12-15 13:51:30 -0800677 * Action taken when GattService is turned on
Nitin Arorad055adb2015-03-02 15:03:51 -0800678 */
679 private void onBluetoothGattServiceUp() {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700680 if (DBG) Slog.d(TAG,"BluetoothGatt Service is Up");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700681 try {
682 mBluetoothLock.readLock().lock();
Marie Janssenfa630682016-12-15 13:51:30 -0800683 if (mBluetooth == null) {
684 if (DBG) Slog.w(TAG, "onBluetoothServiceUp: mBluetooth is null!");
685 return;
686 }
687 int st = mBluetooth.getState();
688 if (st != BluetoothAdapter.STATE_BLE_ON) {
689 if (DBG) Slog.v(TAG, "onBluetoothServiceUp: state isn't BLE_ON: " +
690 BluetoothAdapter.nameForState(st));
691 return;
692 }
693 if (isBluetoothPersistedStateOnBluetooth() || !isBleAppPresent()) {
694 // This triggers transition to STATE_ON
Nitin Arorad055adb2015-03-02 15:03:51 -0800695 mBluetooth.onLeServiceUp();
Nitin Arorad055adb2015-03-02 15:03:51 -0800696 persistBluetoothSetting(BLUETOOTH_ON_BLUETOOTH);
Nitin Arorad055adb2015-03-02 15:03:51 -0800697 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700698 } catch (RemoteException e) {
699 Slog.e(TAG,"Unable to call onServiceUp", e);
700 } finally {
701 mBluetoothLock.readLock().unlock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800702 }
703 }
704
705 /**
706 * Inform BluetoothAdapter instances that BREDR part is down
707 * and turn off all service and stack if no LE app needs it
708 */
709 private void sendBrEdrDownCallback() {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700710 if (DBG) Slog.d(TAG,"Calling sendBrEdrDownCallback callbacks");
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700711
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700712 if (mBluetooth == null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700713 Slog.w(TAG, "Bluetooth handle is null");
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700714 return;
715 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800716
Martin Brabhamc2b06222017-02-27 16:55:07 -0800717 if (isBleAppPresent()) {
718 // Need to stay at BLE ON. Disconnect all Gatt connections
719 try {
720 mBluetoothGatt.unregAll();
721 } catch (RemoteException e) {
722 Slog.e(TAG, "Unable to disconnect all apps.", e);
723 }
724 } else {
Nitin Arorad055adb2015-03-02 15:03:51 -0800725 try {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700726 mBluetoothLock.readLock().lock();
727 if (mBluetooth != null) mBluetooth.onBrEdrDown();
728 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700729 Slog.e(TAG, "Call to onBrEdrDown() failed.", e);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700730 } finally {
731 mBluetoothLock.readLock().unlock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800732 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800733 }
Martin Brabhamc2b06222017-02-27 16:55:07 -0800734
Nitin Arorad055adb2015-03-02 15:03:51 -0800735 }
736
Marie Janssen59804562016-12-28 14:13:21 -0800737 public boolean enableNoAutoConnect(String packageName)
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700738 {
Lenka Trochtova63d5e4a72016-12-02 12:19:39 +0100739 if (isBluetoothDisallowed()) {
740 if (DBG) {
741 Slog.d(TAG, "enableNoAutoConnect(): not enabling - bluetooth disallowed");
742 }
743 return false;
744 }
745
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700746 mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
747 "Need BLUETOOTH ADMIN permission");
Zhihai Xu40874a02012-10-08 17:57:03 -0700748
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700749 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700750 Slog.d(TAG,"enableNoAutoConnect(): mBluetooth =" + mBluetooth +
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700751 " mBinding = " + mBinding);
752 }
Martijn Coenen8385c5a2012-11-29 10:14:16 -0800753 int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
754
755 if (callingAppId != Process.NFC_UID) {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700756 throw new SecurityException("no permission to enable Bluetooth quietly");
757 }
Martijn Coenen8385c5a2012-11-29 10:14:16 -0800758
Zhihai Xu401202b2012-12-03 11:36:21 -0800759 synchronized(mReceiver) {
760 mQuietEnableExternal = true;
761 mEnableExternal = true;
Marie Janssen59804562016-12-28 14:13:21 -0800762 sendEnableMsg(true, packageName);
Zhihai Xu401202b2012-12-03 11:36:21 -0800763 }
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700764 return true;
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700765 }
Ajay Panicker4bb48302016-03-31 14:14:27 -0700766
Svetoslav Ganovac69be52016-06-29 17:31:44 -0700767 public boolean enable(String packageName) throws RemoteException {
768 final int callingUid = Binder.getCallingUid();
769 final boolean callerSystem = UserHandle.getAppId(callingUid) == Process.SYSTEM_UID;
770
Lenka Trochtova63d5e4a72016-12-02 12:19:39 +0100771 if (isBluetoothDisallowed()) {
772 if (DBG) {
773 Slog.d(TAG,"enable(): not enabling - bluetooth disallowed");
774 }
775 return false;
776 }
777
Svetoslav Ganovac69be52016-06-29 17:31:44 -0700778 if (!callerSystem) {
779 if (!checkIfCallerIsForegroundUser()) {
780 Slog.w(TAG, "enable(): not allowed for non-active and non system user");
781 return false;
782 }
783
784 mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
785 "Need BLUETOOTH ADMIN permission");
786
787 if (!isEnabled() && mPermissionReviewRequired
788 && startConsentUiIfNeeded(packageName, callingUid,
789 BluetoothAdapter.ACTION_REQUEST_ENABLE)) {
790 return false;
791 }
fredcf2458862012-04-16 15:18:27 -0700792 }
793
Zhihai Xu401202b2012-12-03 11:36:21 -0800794 if (DBG) {
Marie Janssen59804562016-12-28 14:13:21 -0800795 Slog.d(TAG,"enable(" + packageName + "): mBluetooth =" + mBluetooth +
Marie Janssencb21ad72016-12-13 10:51:02 -0800796 " mBinding = " + mBinding + " mState = " +
797 BluetoothAdapter.nameForState(mState));
Sanket Agarwal090bf552016-04-21 14:10:55 -0700798 }
Zhihai Xu401202b2012-12-03 11:36:21 -0800799
800 synchronized(mReceiver) {
801 mQuietEnableExternal = false;
802 mEnableExternal = true;
803 // waive WRITE_SECURE_SETTINGS permission check
Marie Janssen59804562016-12-28 14:13:21 -0800804 sendEnableMsg(false, packageName);
Zhihai Xu401202b2012-12-03 11:36:21 -0800805 }
Jeff Sharkey67609c72016-03-05 14:29:13 -0700806 if (DBG) Slog.d(TAG, "enable returning");
Zhihai Xu401202b2012-12-03 11:36:21 -0800807 return true;
fredc0f420372012-04-12 00:02:00 -0700808 }
809
Svetoslav Ganovac69be52016-06-29 17:31:44 -0700810 public boolean disable(String packageName, boolean persist) throws RemoteException {
811 final int callingUid = Binder.getCallingUid();
812 final boolean callerSystem = UserHandle.getAppId(callingUid) == Process.SYSTEM_UID;
Zhihai Xu40874a02012-10-08 17:57:03 -0700813
Svetoslav Ganovac69be52016-06-29 17:31:44 -0700814 if (!callerSystem) {
815 if (!checkIfCallerIsForegroundUser()) {
816 Slog.w(TAG, "disable(): not allowed for non-active and non system user");
817 return false;
818 }
819
820 mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
821 "Need BLUETOOTH ADMIN permission");
822
823 if (isEnabled() && mPermissionReviewRequired
824 && startConsentUiIfNeeded(packageName, callingUid,
825 BluetoothAdapter.ACTION_REQUEST_DISABLE)) {
826 return false;
827 }
Zhihai Xu40874a02012-10-08 17:57:03 -0700828 }
829
fredcf2458862012-04-16 15:18:27 -0700830 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700831 Slog.d(TAG,"disable(): mBluetooth = " + mBluetooth +
Matthew Xiecdce0b92012-07-12 19:06:15 -0700832 " mBinding = " + mBinding);
833 }
fredcf2458862012-04-16 15:18:27 -0700834
Zhihai Xu401202b2012-12-03 11:36:21 -0800835 synchronized(mReceiver) {
836 if (persist) {
Zhihai Xu401202b2012-12-03 11:36:21 -0800837 persistBluetoothSetting(BLUETOOTH_OFF);
Zhihai Xu401202b2012-12-03 11:36:21 -0800838 }
839 mEnableExternal = false;
Marie Janssen59804562016-12-28 14:13:21 -0800840 sendDisableMsg(packageName);
Zhihai Xu401202b2012-12-03 11:36:21 -0800841 }
fredc0f420372012-04-12 00:02:00 -0700842 return true;
843 }
844
Svetoslav Ganovac69be52016-06-29 17:31:44 -0700845 private boolean startConsentUiIfNeeded(String packageName,
846 int callingUid, String intentAction) throws RemoteException {
847 try {
848 // Validate the package only if we are going to use it
849 ApplicationInfo applicationInfo = mContext.getPackageManager()
850 .getApplicationInfoAsUser(packageName,
851 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
852 UserHandle.getUserId(callingUid));
853 if (applicationInfo.uid != callingUid) {
854 throw new SecurityException("Package " + callingUid
855 + " not in uid " + callingUid);
856 }
857
Ivan Podogovd2d32b12016-12-05 16:46:52 +0000858 Intent intent = new Intent(intentAction);
Ivan Podogov1ab87252017-01-03 12:02:18 +0000859 intent.putExtra(Intent.EXTRA_PACKAGE_NAME, packageName);
860 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
861 | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
862 try {
863 mContext.startActivity(intent);
864 } catch (ActivityNotFoundException e) {
865 // Shouldn't happen
866 Slog.e(TAG, "Intent to handle action " + intentAction + " missing");
867 return false;
Svetoslav Ganovac69be52016-06-29 17:31:44 -0700868 }
Ivan Podogov1ab87252017-01-03 12:02:18 +0000869 return true;
Svetoslav Ganovac69be52016-06-29 17:31:44 -0700870 } catch (PackageManager.NameNotFoundException e) {
871 throw new RemoteException(e.getMessage());
872 }
Svetoslav Ganovac69be52016-06-29 17:31:44 -0700873 }
874
fredc649fe492012-04-19 01:07:18 -0700875 public void unbindAndFinish() {
fredcf2458862012-04-16 15:18:27 -0700876 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700877 Slog.d(TAG,"unbindAndFinish(): " + mBluetooth +
Marie Janssencb21ad72016-12-13 10:51:02 -0800878 " mBinding = " + mBinding + " mUnbinding = " + mUnbinding);
fredcf2458862012-04-16 15:18:27 -0700879 }
880
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700881 try {
882 mBluetoothLock.writeLock().lock();
fredc0f420372012-04-12 00:02:00 -0700883 if (mUnbinding) return;
884 mUnbinding = true;
Pavlin Radoslavove47ec142016-06-01 22:25:18 -0700885 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
Pavlin Radoslavov74f60c02016-09-21 17:28:11 -0700886 mHandler.removeMessages(MESSAGE_BIND_PROFILE_SERVICE);
Zhihai Xu40874a02012-10-08 17:57:03 -0700887 if (mBluetooth != null) {
Andre Eisenbach305fdab2015-11-11 21:43:26 -0800888 //Unregister callback object
889 try {
890 mBluetooth.unregisterCallback(mBluetoothCallback);
891 } catch (RemoteException re) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700892 Slog.e(TAG, "Unable to unregister BluetoothCallback",re);
fredcbf072a72012-05-09 16:52:50 -0700893 }
Marie Janssen9db28eb2016-01-12 16:05:15 -0800894 mBluetoothBinder = null;
fredcd6883532012-04-25 17:46:13 -0700895 mBluetooth = null;
fredc0f420372012-04-12 00:02:00 -0700896 mContext.unbindService(mConnection);
fredcd6883532012-04-25 17:46:13 -0700897 mUnbinding = false;
Zhihai Xu40874a02012-10-08 17:57:03 -0700898 mBinding = false;
fredcf2458862012-04-16 15:18:27 -0700899 } else {
Marie Janssencb21ad72016-12-13 10:51:02 -0800900 mUnbinding = false;
fredc0f420372012-04-12 00:02:00 -0700901 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800902 mBluetoothGatt = null;
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700903 } finally {
904 mBluetoothLock.writeLock().unlock();
fredc0f420372012-04-12 00:02:00 -0700905 }
906 }
907
Matthew Xieddf7e472013-03-01 18:41:02 -0800908 public IBluetoothGatt getBluetoothGatt() {
909 // sync protection
910 return mBluetoothGatt;
911 }
912
Benjamin Franze8b98922014-11-12 15:57:54 +0000913 @Override
914 public boolean bindBluetoothProfileService(int bluetoothProfile,
915 IBluetoothProfileServiceConnection proxy) {
916 if (!mEnable) {
917 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700918 Slog.d(TAG, "Trying to bind to profile: " + bluetoothProfile +
Benjamin Franze8b98922014-11-12 15:57:54 +0000919 ", while Bluetooth was disabled");
920 }
921 return false;
922 }
923 synchronized (mProfileServices) {
924 ProfileServiceConnections psc = mProfileServices.get(new Integer(bluetoothProfile));
925 if (psc == null) {
926 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700927 Slog.d(TAG, "Creating new ProfileServiceConnections object for"
Benjamin Franze8b98922014-11-12 15:57:54 +0000928 + " profile: " + bluetoothProfile);
929 }
Benjamin Franz5b614592014-12-09 18:58:45 +0000930
931 if (bluetoothProfile != BluetoothProfile.HEADSET) return false;
932
933 Intent intent = new Intent(IBluetoothHeadset.class.getName());
Benjamin Franze8b98922014-11-12 15:57:54 +0000934 psc = new ProfileServiceConnections(intent);
Benjamin Franz5b614592014-12-09 18:58:45 +0000935 if (!psc.bindService()) return false;
936
Benjamin Franze8b98922014-11-12 15:57:54 +0000937 mProfileServices.put(new Integer(bluetoothProfile), psc);
Benjamin Franze8b98922014-11-12 15:57:54 +0000938 }
939 }
940
941 // Introducing a delay to give the client app time to prepare
942 Message addProxyMsg = mHandler.obtainMessage(MESSAGE_ADD_PROXY_DELAYED);
943 addProxyMsg.arg1 = bluetoothProfile;
944 addProxyMsg.obj = proxy;
945 mHandler.sendMessageDelayed(addProxyMsg, ADD_PROXY_DELAY_MS);
946 return true;
947 }
948
949 @Override
950 public void unbindBluetoothProfileService(int bluetoothProfile,
951 IBluetoothProfileServiceConnection proxy) {
952 synchronized (mProfileServices) {
953 ProfileServiceConnections psc = mProfileServices.get(new Integer(bluetoothProfile));
954 if (psc == null) {
955 return;
956 }
957 psc.removeProxy(proxy);
958 }
959 }
960
961 private void unbindAllBluetoothProfileServices() {
962 synchronized (mProfileServices) {
963 for (Integer i : mProfileServices.keySet()) {
964 ProfileServiceConnections psc = mProfileServices.get(i);
Benjamin Franz5b614592014-12-09 18:58:45 +0000965 try {
966 mContext.unbindService(psc);
967 } catch (IllegalArgumentException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700968 Slog.e(TAG, "Unable to unbind service with intent: " + psc.mIntent, e);
Benjamin Franz5b614592014-12-09 18:58:45 +0000969 }
Benjamin Franze8b98922014-11-12 15:57:54 +0000970 psc.removeAllProxies();
971 }
972 mProfileServices.clear();
973 }
974 }
975
976 /**
Miao Chou658bf2f2015-06-26 17:14:35 -0700977 * Send enable message and set adapter name and address. Called when the boot phase becomes
978 * PHASE_SYSTEM_SERVICES_READY.
979 */
980 public void handleOnBootPhase() {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700981 if (DBG) Slog.d(TAG, "Bluetooth boot completed");
Lenka Trochtova63d5e4a72016-12-02 12:19:39 +0100982 UserManagerInternal userManagerInternal =
983 LocalServices.getService(UserManagerInternal.class);
984 userManagerInternal.addUserRestrictionsListener(mUserRestrictionsListener);
Lenka Trochtovac6f0e232017-01-17 10:35:49 +0100985 final boolean isBluetoothDisallowed = isBluetoothDisallowed();
986 PackageManagerService packageManagerService =
987 (PackageManagerService) ServiceManager.getService("package");
988 if (packageManagerService != null && !packageManagerService.isOnlyCoreApps()) {
989 updateOppLauncherComponentState(isBluetoothDisallowed);
990 }
991 if (isBluetoothDisallowed) {
Lenka Trochtova63d5e4a72016-12-02 12:19:39 +0100992 return;
993 }
Miao Chou658bf2f2015-06-26 17:14:35 -0700994 if (mEnableExternal && isBluetoothPersistedStateOnBluetooth()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700995 if (DBG) Slog.d(TAG, "Auto-enabling Bluetooth.");
Ajay Panicker467bc042017-02-22 12:23:15 -0800996 sendEnableMsg(mQuietEnableExternal, REASON_SYSTEM_BOOT);
Ajay Panickerbf796d82016-03-11 13:47:20 -0800997 } else if (!isNameAndAddressSet()) {
998 if (DBG) Slog.d(TAG, "Getting adapter name and address");
Ajay Panicker4bb48302016-03-31 14:14:27 -0700999 Message getMsg = mHandler.obtainMessage(MESSAGE_GET_NAME_AND_ADDRESS);
1000 mHandler.sendMessage(getMsg);
Miao Chou658bf2f2015-06-26 17:14:35 -07001001 }
Miao Chou658bf2f2015-06-26 17:14:35 -07001002 }
1003
1004 /**
1005 * Called when switching to a different foreground user.
1006 */
1007 public void handleOnSwitchUser(int userHandle) {
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001008 if (DBG) Slog.d(TAG, "User " + userHandle + " switched");
1009 mHandler.obtainMessage(MESSAGE_USER_SWITCHED, userHandle, 0).sendToTarget();
1010 }
1011
1012 /**
1013 * Called when user is unlocked.
1014 */
1015 public void handleOnUnlockUser(int userHandle) {
1016 if (DBG) Slog.d(TAG, "User " + userHandle + " unlocked");
1017 mHandler.obtainMessage(MESSAGE_USER_UNLOCKED, userHandle, 0).sendToTarget();
Miao Chou658bf2f2015-06-26 17:14:35 -07001018 }
1019
1020 /**
Benjamin Franze8b98922014-11-12 15:57:54 +00001021 * This class manages the clients connected to a given ProfileService
1022 * and maintains the connection with that service.
1023 */
1024 final private class ProfileServiceConnections implements ServiceConnection,
1025 IBinder.DeathRecipient {
1026 final RemoteCallbackList<IBluetoothProfileServiceConnection> mProxies =
1027 new RemoteCallbackList <IBluetoothProfileServiceConnection>();
1028 IBinder mService;
1029 ComponentName mClassName;
1030 Intent mIntent;
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001031 boolean mInvokingProxyCallbacks = false;
Benjamin Franze8b98922014-11-12 15:57:54 +00001032
1033 ProfileServiceConnections(Intent intent) {
1034 mService = null;
1035 mClassName = null;
1036 mIntent = intent;
1037 }
1038
Benjamin Franz5b614592014-12-09 18:58:45 +00001039 private boolean bindService() {
1040 if (mIntent != null && mService == null &&
1041 doBind(mIntent, this, 0, UserHandle.CURRENT_OR_SELF)) {
Benjamin Franze8b98922014-11-12 15:57:54 +00001042 Message msg = mHandler.obtainMessage(MESSAGE_BIND_PROFILE_SERVICE);
1043 msg.obj = this;
1044 mHandler.sendMessageDelayed(msg, TIMEOUT_BIND_MS);
Benjamin Franz5b614592014-12-09 18:58:45 +00001045 return true;
Benjamin Franze8b98922014-11-12 15:57:54 +00001046 }
Jeff Sharkey67609c72016-03-05 14:29:13 -07001047 Slog.w(TAG, "Unable to bind with intent: " + mIntent);
Benjamin Franz5b614592014-12-09 18:58:45 +00001048 return false;
Benjamin Franze8b98922014-11-12 15:57:54 +00001049 }
1050
1051 private void addProxy(IBluetoothProfileServiceConnection proxy) {
1052 mProxies.register(proxy);
1053 if (mService != null) {
1054 try{
1055 proxy.onServiceConnected(mClassName, mService);
1056 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001057 Slog.e(TAG, "Unable to connect to proxy", e);
Benjamin Franze8b98922014-11-12 15:57:54 +00001058 }
1059 } else {
1060 if (!mHandler.hasMessages(MESSAGE_BIND_PROFILE_SERVICE, this)) {
1061 Message msg = mHandler.obtainMessage(MESSAGE_BIND_PROFILE_SERVICE);
1062 msg.obj = this;
1063 mHandler.sendMessage(msg);
1064 }
1065 }
1066 }
1067
1068 private void removeProxy(IBluetoothProfileServiceConnection proxy) {
1069 if (proxy != null) {
1070 if (mProxies.unregister(proxy)) {
1071 try {
1072 proxy.onServiceDisconnected(mClassName);
1073 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001074 Slog.e(TAG, "Unable to disconnect proxy", e);
Benjamin Franze8b98922014-11-12 15:57:54 +00001075 }
1076 }
1077 } else {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001078 Slog.w(TAG, "Trying to remove a null proxy");
Benjamin Franze8b98922014-11-12 15:57:54 +00001079 }
1080 }
1081
1082 private void removeAllProxies() {
1083 onServiceDisconnected(mClassName);
1084 mProxies.kill();
1085 }
1086
1087 @Override
1088 public void onServiceConnected(ComponentName className, IBinder service) {
1089 // remove timeout message
1090 mHandler.removeMessages(MESSAGE_BIND_PROFILE_SERVICE, this);
1091 mService = service;
1092 mClassName = className;
1093 try {
1094 mService.linkToDeath(this, 0);
1095 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001096 Slog.e(TAG, "Unable to linkToDeath", e);
Benjamin Franze8b98922014-11-12 15:57:54 +00001097 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001098
1099 if (mInvokingProxyCallbacks) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001100 Slog.e(TAG, "Proxy callbacks already in progress.");
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001101 return;
Benjamin Franze8b98922014-11-12 15:57:54 +00001102 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001103 mInvokingProxyCallbacks = true;
1104
1105 final int n = mProxies.beginBroadcast();
1106 try {
1107 for (int i = 0; i < n; i++) {
1108 try {
1109 mProxies.getBroadcastItem(i).onServiceConnected(className, service);
1110 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001111 Slog.e(TAG, "Unable to connect to proxy", e);
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001112 }
1113 }
1114 } finally {
1115 mProxies.finishBroadcast();
1116 mInvokingProxyCallbacks = false;
1117 }
Benjamin Franze8b98922014-11-12 15:57:54 +00001118 }
1119
1120 @Override
1121 public void onServiceDisconnected(ComponentName className) {
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001122 if (mService == null) return;
Benjamin Franze8b98922014-11-12 15:57:54 +00001123 mService.unlinkToDeath(this, 0);
1124 mService = null;
1125 mClassName = null;
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001126
1127 if (mInvokingProxyCallbacks) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001128 Slog.e(TAG, "Proxy callbacks already in progress.");
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001129 return;
Benjamin Franze8b98922014-11-12 15:57:54 +00001130 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001131 mInvokingProxyCallbacks = true;
1132
1133 final int n = mProxies.beginBroadcast();
1134 try {
1135 for (int i = 0; i < n; i++) {
1136 try {
1137 mProxies.getBroadcastItem(i).onServiceDisconnected(className);
1138 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001139 Slog.e(TAG, "Unable to disconnect from proxy", e);
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001140 }
1141 }
1142 } finally {
1143 mProxies.finishBroadcast();
1144 mInvokingProxyCallbacks = false;
1145 }
Benjamin Franze8b98922014-11-12 15:57:54 +00001146 }
1147
1148 @Override
1149 public void binderDied() {
1150 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001151 Slog.w(TAG, "Profile service for profile: " + mClassName
Benjamin Franze8b98922014-11-12 15:57:54 +00001152 + " died.");
1153 }
1154 onServiceDisconnected(mClassName);
1155 // Trigger rebind
1156 Message msg = mHandler.obtainMessage(MESSAGE_BIND_PROFILE_SERVICE);
1157 msg.obj = this;
1158 mHandler.sendMessageDelayed(msg, TIMEOUT_BIND_MS);
1159 }
1160 }
1161
fredcbf072a72012-05-09 16:52:50 -07001162 private void sendBluetoothStateCallback(boolean isUp) {
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001163 try {
1164 int n = mStateChangeCallbacks.beginBroadcast();
Jeff Sharkey67609c72016-03-05 14:29:13 -07001165 if (DBG) Slog.d(TAG,"Broadcasting onBluetoothStateChange("+isUp+") to " + n + " receivers.");
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001166 for (int i=0; i <n;i++) {
1167 try {
1168 mStateChangeCallbacks.getBroadcastItem(i).onBluetoothStateChange(isUp);
1169 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001170 Slog.e(TAG, "Unable to call onBluetoothStateChange() on callback #" + i , e);
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001171 }
fredcbf072a72012-05-09 16:52:50 -07001172 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001173 } finally {
1174 mStateChangeCallbacks.finishBroadcast();
fredcbf072a72012-05-09 16:52:50 -07001175 }
fredcbf072a72012-05-09 16:52:50 -07001176 }
1177
1178 /**
Zhihai Xu40874a02012-10-08 17:57:03 -07001179 * Inform BluetoothAdapter instances that Adapter service is up
1180 */
1181 private void sendBluetoothServiceUpCallback() {
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001182 try {
1183 int n = mCallbacks.beginBroadcast();
Jeff Sharkey67609c72016-03-05 14:29:13 -07001184 Slog.d(TAG,"Broadcasting onBluetoothServiceUp() to " + n + " receivers.");
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001185 for (int i=0; i <n;i++) {
1186 try {
1187 mCallbacks.getBroadcastItem(i).onBluetoothServiceUp(mBluetooth);
1188 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001189 Slog.e(TAG, "Unable to call onBluetoothServiceUp() on callback #" + i, e);
Zhihai Xu40874a02012-10-08 17:57:03 -07001190 }
1191 }
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001192 } finally {
1193 mCallbacks.finishBroadcast();
Zhihai Xu40874a02012-10-08 17:57:03 -07001194 }
1195 }
1196 /**
fredcbf072a72012-05-09 16:52:50 -07001197 * Inform BluetoothAdapter instances that Adapter service is down
1198 */
1199 private void sendBluetoothServiceDownCallback() {
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001200 try {
1201 int n = mCallbacks.beginBroadcast();
Jeff Sharkey67609c72016-03-05 14:29:13 -07001202 Slog.d(TAG,"Broadcasting onBluetoothServiceDown() to " + n + " receivers.");
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001203 for (int i=0; i <n;i++) {
1204 try {
1205 mCallbacks.getBroadcastItem(i).onBluetoothServiceDown();
1206 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001207 Slog.e(TAG, "Unable to call onBluetoothServiceDown() on callback #" + i, e);
fredcd6883532012-04-25 17:46:13 -07001208 }
1209 }
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001210 } finally {
1211 mCallbacks.finishBroadcast();
fredcd6883532012-04-25 17:46:13 -07001212 }
1213 }
Svet Ganov408abf72015-05-12 19:13:36 -07001214
fredc0f420372012-04-12 00:02:00 -07001215 public String getAddress() {
Matthew Xieaf5ddbf2012-12-04 10:47:43 -08001216 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
Svet Ganov408abf72015-05-12 19:13:36 -07001217 "Need BLUETOOTH permission");
Zhihai Xu40874a02012-10-08 17:57:03 -07001218
Zhihai Xu6eb76522012-11-29 15:41:04 -08001219 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
Svet Ganov408abf72015-05-12 19:13:36 -07001220 (!checkIfCallerIsForegroundUser())) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001221 Slog.w(TAG,"getAddress(): not allowed for non-active and non system user");
Zhihai Xu6eb76522012-11-29 15:41:04 -08001222 return null;
Zhihai Xu40874a02012-10-08 17:57:03 -07001223 }
1224
Svet Ganov408abf72015-05-12 19:13:36 -07001225 if (mContext.checkCallingOrSelfPermission(Manifest.permission.LOCAL_MAC_ADDRESS)
1226 != PackageManager.PERMISSION_GRANTED) {
1227 return BluetoothAdapter.DEFAULT_MAC_ADDRESS;
1228 }
1229
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001230 try {
1231 mBluetoothLock.readLock().lock();
1232 if (mBluetooth != null) return mBluetooth.getAddress();
1233 } catch (RemoteException e) {
1234 Slog.e(TAG, "getAddress(): Unable to retrieve address remotely. Returning cached address", e);
1235 } finally {
1236 mBluetoothLock.readLock().unlock();
fredc116d1d462012-04-20 14:47:08 -07001237 }
Ajay Panickerbf796d82016-03-11 13:47:20 -08001238
Matthew Xiecdce0b92012-07-12 19:06:15 -07001239 // mAddress is accessed from outside.
1240 // It is alright without a lock. Here, bluetooth is off, no other thread is
1241 // changing mAddress
fredc0f420372012-04-12 00:02:00 -07001242 return mAddress;
1243 }
fredc649fe492012-04-19 01:07:18 -07001244
fredc0f420372012-04-12 00:02:00 -07001245 public String getName() {
Matthew Xieaf5ddbf2012-12-04 10:47:43 -08001246 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
1247 "Need BLUETOOTH permission");
Zhihai Xu40874a02012-10-08 17:57:03 -07001248
Zhihai Xu6eb76522012-11-29 15:41:04 -08001249 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
1250 (!checkIfCallerIsForegroundUser())) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001251 Slog.w(TAG,"getName(): not allowed for non-active and non system user");
Zhihai Xu6eb76522012-11-29 15:41:04 -08001252 return null;
Zhihai Xu40874a02012-10-08 17:57:03 -07001253 }
1254
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001255 try {
1256 mBluetoothLock.readLock().lock();
1257 if (mBluetooth != null) return mBluetooth.getName();
1258 } catch (RemoteException e) {
1259 Slog.e(TAG, "getName(): Unable to retrieve name remotely. Returning cached name", e);
1260 } finally {
1261 mBluetoothLock.readLock().unlock();
fredc116d1d462012-04-20 14:47:08 -07001262 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001263
Matthew Xiecdce0b92012-07-12 19:06:15 -07001264 // mName is accessed from outside.
1265 // It alright without a lock. Here, bluetooth is off, no other thread is
1266 // changing mName
fredc0f420372012-04-12 00:02:00 -07001267 return mName;
1268 }
1269
fredc0f420372012-04-12 00:02:00 -07001270 private class BluetoothServiceConnection implements ServiceConnection {
Marie Janssencb21ad72016-12-13 10:51:02 -08001271 public void onServiceConnected(ComponentName componentName, IBinder service) {
1272 String name = componentName.getClassName();
1273 if (DBG) Slog.d(TAG, "BluetoothServiceConnection: " + name);
fredc0f420372012-04-12 00:02:00 -07001274 Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_SERVICE_CONNECTED);
Marie Janssencb21ad72016-12-13 10:51:02 -08001275 if (name.equals("com.android.bluetooth.btservice.AdapterService")) {
Matthew Xieddf7e472013-03-01 18:41:02 -08001276 msg.arg1 = SERVICE_IBLUETOOTH;
Marie Janssencb21ad72016-12-13 10:51:02 -08001277 } else if (name.equals("com.android.bluetooth.gatt.GattService")) {
Matthew Xieddf7e472013-03-01 18:41:02 -08001278 msg.arg1 = SERVICE_IBLUETOOTHGATT;
1279 } else {
Marie Janssencb21ad72016-12-13 10:51:02 -08001280 Slog.e(TAG, "Unknown service connected: " + name);
Matthew Xieddf7e472013-03-01 18:41:02 -08001281 return;
1282 }
fredc0f420372012-04-12 00:02:00 -07001283 msg.obj = service;
1284 mHandler.sendMessage(msg);
1285 }
1286
Marie Janssencb21ad72016-12-13 10:51:02 -08001287 public void onServiceDisconnected(ComponentName componentName) {
1288 // Called if we unexpectedly disconnect.
1289 String name = componentName.getClassName();
1290 if (DBG) Slog.d(TAG, "BluetoothServiceConnection, disconnected: " + name);
fredc0f420372012-04-12 00:02:00 -07001291 Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED);
Marie Janssencb21ad72016-12-13 10:51:02 -08001292 if (name.equals("com.android.bluetooth.btservice.AdapterService")) {
Matthew Xieddf7e472013-03-01 18:41:02 -08001293 msg.arg1 = SERVICE_IBLUETOOTH;
Marie Janssencb21ad72016-12-13 10:51:02 -08001294 } else if (name.equals("com.android.bluetooth.gatt.GattService")) {
Matthew Xieddf7e472013-03-01 18:41:02 -08001295 msg.arg1 = SERVICE_IBLUETOOTHGATT;
1296 } else {
Marie Janssencb21ad72016-12-13 10:51:02 -08001297 Slog.e(TAG, "Unknown service disconnected: " + name);
Matthew Xieddf7e472013-03-01 18:41:02 -08001298 return;
1299 }
fredc0f420372012-04-12 00:02:00 -07001300 mHandler.sendMessage(msg);
1301 }
1302 }
1303
1304 private BluetoothServiceConnection mConnection = new BluetoothServiceConnection();
1305
Zhihai Xu40874a02012-10-08 17:57:03 -07001306 private class BluetoothHandler extends Handler {
Ajay Panicker4bb48302016-03-31 14:14:27 -07001307 boolean mGetNameAddressOnly = false;
1308
Zhihai Xu40874a02012-10-08 17:57:03 -07001309 public BluetoothHandler(Looper looper) {
1310 super(looper);
1311 }
1312
fredc0f420372012-04-12 00:02:00 -07001313 @Override
1314 public void handleMessage(Message msg) {
fredc0f420372012-04-12 00:02:00 -07001315 switch (msg.what) {
Ajay Panicker4bb48302016-03-31 14:14:27 -07001316 case MESSAGE_GET_NAME_AND_ADDRESS:
1317 if (DBG) Slog.d(TAG, "MESSAGE_GET_NAME_AND_ADDRESS");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001318 try {
1319 mBluetoothLock.writeLock().lock();
Ajay Panicker4bb48302016-03-31 14:14:27 -07001320 if ((mBluetooth == null) && (!mBinding)) {
1321 if (DBG) Slog.d(TAG, "Binding to service to get name and address");
1322 mGetNameAddressOnly = true;
1323 Message timeoutMsg = mHandler.obtainMessage(MESSAGE_TIMEOUT_BIND);
1324 mHandler.sendMessageDelayed(timeoutMsg, TIMEOUT_BIND_MS);
1325 Intent i = new Intent(IBluetooth.class.getName());
1326 if (!doBind(i, mConnection,
1327 Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT,
1328 UserHandle.CURRENT)) {
1329 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
1330 } else {
1331 mBinding = true;
1332 }
1333 } else if (mBluetooth != null) {
1334 try {
1335 storeNameAndAddress(mBluetooth.getName(),
1336 mBluetooth.getAddress());
1337 } catch (RemoteException re) {
1338 Slog.e(TAG, "Unable to grab names", re);
1339 }
1340 if (mGetNameAddressOnly && !mEnable) {
1341 unbindAndFinish();
1342 }
1343 mGetNameAddressOnly = false;
1344 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001345 } finally {
1346 mBluetoothLock.writeLock().unlock();
Ajay Panicker4bb48302016-03-31 14:14:27 -07001347 }
1348 break;
1349
Matthew Xiecdce0b92012-07-12 19:06:15 -07001350 case MESSAGE_ENABLE:
fredcf2458862012-04-16 15:18:27 -07001351 if (DBG) {
Marie Janssencb21ad72016-12-13 10:51:02 -08001352 Slog.d(TAG, "MESSAGE_ENABLE(" + msg.arg1 + "): mBluetooth = " + mBluetooth);
fredc649fe492012-04-19 01:07:18 -07001353 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001354 mHandler.removeMessages(MESSAGE_RESTART_BLUETOOTH_SERVICE);
1355 mEnable = true;
Calvin Ona0b91d72016-06-15 17:58:23 -07001356
1357 // Use service interface to get the exact state
1358 try {
1359 mBluetoothLock.readLock().lock();
1360 if (mBluetooth != null) {
1361 int state = mBluetooth.getState();
1362 if (state == BluetoothAdapter.STATE_BLE_ON) {
Marie Janssene0bfa2e2016-12-20 11:21:12 -08001363 Slog.w(TAG, "BT Enable in BLE_ON State, going to ON");
Calvin Ona0b91d72016-06-15 17:58:23 -07001364 mBluetooth.onLeServiceUp();
Marie Janssene0bfa2e2016-12-20 11:21:12 -08001365 persistBluetoothSetting(BLUETOOTH_ON_BLUETOOTH);
Calvin Ona0b91d72016-06-15 17:58:23 -07001366 break;
1367 }
1368 }
1369 } catch (RemoteException e) {
1370 Slog.e(TAG, "", e);
1371 } finally {
1372 mBluetoothLock.readLock().unlock();
1373 }
1374
1375 mQuietEnable = (msg.arg1 == 1);
Pavlin Radoslavove47ec142016-06-01 22:25:18 -07001376 if (mBluetooth == null) {
Calvin Ona0b91d72016-06-15 17:58:23 -07001377 handleEnable(mQuietEnable);
Pavlin Radoslavove47ec142016-06-01 22:25:18 -07001378 } else {
1379 //
1380 // We need to wait until transitioned to STATE_OFF and
1381 // the previous Bluetooth process has exited. The
1382 // waiting period has three components:
1383 // (a) Wait until the local state is STATE_OFF. This
1384 // is accomplished by "waitForOnOff(false, true)".
1385 // (b) Wait until the STATE_OFF state is updated to
1386 // all components.
1387 // (c) Wait until the Bluetooth process exits, and
1388 // ActivityManager detects it.
1389 // The waiting for (b) and (c) is accomplished by
1390 // delaying the MESSAGE_RESTART_BLUETOOTH_SERVICE
1391 // message. On slower devices, that delay needs to be
1392 // on the order of (2 * SERVICE_RESTART_TIME_MS).
1393 //
1394 waitForOnOff(false, true);
Pavlin Radoslavove47ec142016-06-01 22:25:18 -07001395 Message restartMsg = mHandler.obtainMessage(
1396 MESSAGE_RESTART_BLUETOOTH_SERVICE);
1397 mHandler.sendMessageDelayed(restartMsg,
1398 2 * SERVICE_RESTART_TIME_MS);
1399 }
fredc649fe492012-04-19 01:07:18 -07001400 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001401
fredc0f420372012-04-12 00:02:00 -07001402 case MESSAGE_DISABLE:
Marie Janssencb21ad72016-12-13 10:51:02 -08001403 if (DBG) Slog.d(TAG, "MESSAGE_DISABLE: mBluetooth = " + mBluetooth);
Zhihai Xu40874a02012-10-08 17:57:03 -07001404 mHandler.removeMessages(MESSAGE_RESTART_BLUETOOTH_SERVICE);
1405 if (mEnable && mBluetooth != null) {
1406 waitForOnOff(true, false);
1407 mEnable = false;
Zhihai Xu401202b2012-12-03 11:36:21 -08001408 handleDisable();
Zhihai Xu40874a02012-10-08 17:57:03 -07001409 waitForOnOff(false, false);
1410 } else {
1411 mEnable = false;
Zhihai Xu401202b2012-12-03 11:36:21 -08001412 handleDisable();
Zhihai Xu40874a02012-10-08 17:57:03 -07001413 }
fredc0f420372012-04-12 00:02:00 -07001414 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001415
fredc0f420372012-04-12 00:02:00 -07001416 case MESSAGE_REGISTER_ADAPTER:
1417 {
1418 IBluetoothManagerCallback callback = (IBluetoothManagerCallback) msg.obj;
Marie Janssencb21ad72016-12-13 10:51:02 -08001419 mCallbacks.register(callback);
fredc0f420372012-04-12 00:02:00 -07001420 break;
Marie Janssencb21ad72016-12-13 10:51:02 -08001421 }
fredc0f420372012-04-12 00:02:00 -07001422 case MESSAGE_UNREGISTER_ADAPTER:
1423 {
1424 IBluetoothManagerCallback callback = (IBluetoothManagerCallback) msg.obj;
Marie Janssencb21ad72016-12-13 10:51:02 -08001425 mCallbacks.unregister(callback);
fredc0f420372012-04-12 00:02:00 -07001426 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001427 }
fredc0f420372012-04-12 00:02:00 -07001428 case MESSAGE_REGISTER_STATE_CHANGE_CALLBACK:
1429 {
1430 IBluetoothStateChangeCallback callback = (IBluetoothStateChangeCallback) msg.obj;
Marie Janssencb21ad72016-12-13 10:51:02 -08001431 mStateChangeCallbacks.register(callback);
fredc0f420372012-04-12 00:02:00 -07001432 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001433 }
fredc0f420372012-04-12 00:02:00 -07001434 case MESSAGE_UNREGISTER_STATE_CHANGE_CALLBACK:
1435 {
1436 IBluetoothStateChangeCallback callback = (IBluetoothStateChangeCallback) msg.obj;
Marie Janssencb21ad72016-12-13 10:51:02 -08001437 mStateChangeCallbacks.unregister(callback);
fredc0f420372012-04-12 00:02:00 -07001438 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001439 }
Benjamin Franze8b98922014-11-12 15:57:54 +00001440 case MESSAGE_ADD_PROXY_DELAYED:
1441 {
1442 ProfileServiceConnections psc = mProfileServices.get(
1443 new Integer(msg.arg1));
1444 if (psc == null) {
1445 break;
1446 }
1447 IBluetoothProfileServiceConnection proxy =
1448 (IBluetoothProfileServiceConnection) msg.obj;
1449 psc.addProxy(proxy);
1450 break;
1451 }
1452 case MESSAGE_BIND_PROFILE_SERVICE:
1453 {
1454 ProfileServiceConnections psc = (ProfileServiceConnections) msg.obj;
1455 removeMessages(MESSAGE_BIND_PROFILE_SERVICE, msg.obj);
1456 if (psc == null) {
1457 break;
1458 }
1459 psc.bindService();
1460 break;
1461 }
fredc0f420372012-04-12 00:02:00 -07001462 case MESSAGE_BLUETOOTH_SERVICE_CONNECTED:
1463 {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001464 if (DBG) Slog.d(TAG,"MESSAGE_BLUETOOTH_SERVICE_CONNECTED: " + msg.arg1);
fredc0f420372012-04-12 00:02:00 -07001465
1466 IBinder service = (IBinder) msg.obj;
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001467 try {
1468 mBluetoothLock.writeLock().lock();
Matthew Xieddf7e472013-03-01 18:41:02 -08001469 if (msg.arg1 == SERVICE_IBLUETOOTHGATT) {
Jeff Sharkey0a17db12016-11-04 11:23:46 -06001470 mBluetoothGatt = IBluetoothGatt.Stub
1471 .asInterface(Binder.allowBlocking(service));
Nitin Arorad055adb2015-03-02 15:03:51 -08001472 onBluetoothGattServiceUp();
Matthew Xieddf7e472013-03-01 18:41:02 -08001473 break;
1474 } // else must be SERVICE_IBLUETOOTH
1475
1476 //Remove timeout
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001477 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
Matthew Xieddf7e472013-03-01 18:41:02 -08001478
fredc0f420372012-04-12 00:02:00 -07001479 mBinding = false;
Marie Janssen9db28eb2016-01-12 16:05:15 -08001480 mBluetoothBinder = service;
Jeff Sharkey0a17db12016-11-04 11:23:46 -06001481 mBluetooth = IBluetooth.Stub.asInterface(Binder.allowBlocking(service));
fredc0f420372012-04-12 00:02:00 -07001482
Ajay Panicker4bb48302016-03-31 14:14:27 -07001483 if (!isNameAndAddressSet()) {
1484 Message getMsg = mHandler.obtainMessage(MESSAGE_GET_NAME_AND_ADDRESS);
1485 mHandler.sendMessage(getMsg);
1486 if (mGetNameAddressOnly) return;
1487 }
1488
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001489 try {
1490 boolean enableHciSnoopLog = (Settings.Secure.getInt(mContentResolver,
1491 Settings.Secure.BLUETOOTH_HCI_LOG, 0) == 1);
1492 if (!mBluetooth.configHciSnoopLog(enableHciSnoopLog)) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001493 Slog.e(TAG,"IBluetooth.configHciSnoopLog return false");
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001494 }
1495 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001496 Slog.e(TAG,"Unable to call configHciSnoopLog", e);
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001497 }
1498
Matthew Xiecdce0b92012-07-12 19:06:15 -07001499 //Register callback object
fredcbf072a72012-05-09 16:52:50 -07001500 try {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001501 mBluetooth.registerCallback(mBluetoothCallback);
1502 } catch (RemoteException re) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001503 Slog.e(TAG, "Unable to register BluetoothCallback",re);
fredcbf072a72012-05-09 16:52:50 -07001504 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001505 //Inform BluetoothAdapter instances that service is up
Zhihai Xu40874a02012-10-08 17:57:03 -07001506 sendBluetoothServiceUpCallback();
1507
Matthew Xiecdce0b92012-07-12 19:06:15 -07001508 //Do enable request
1509 try {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001510 if (mQuietEnable == false) {
Marie Janssencb21ad72016-12-13 10:51:02 -08001511 if (!mBluetooth.enable()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001512 Slog.e(TAG,"IBluetooth.enable() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001513 }
Marie Janssencb21ad72016-12-13 10:51:02 -08001514 } else {
1515 if (!mBluetooth.enableNoAutoConnect()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001516 Slog.e(TAG,"IBluetooth.enableNoAutoConnect() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001517 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001518 }
1519 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001520 Slog.e(TAG,"Unable to call enable()",e);
Matthew Xiecdce0b92012-07-12 19:06:15 -07001521 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001522 } finally {
1523 mBluetoothLock.writeLock().unlock();
Freda8c6df02012-07-11 10:25:23 -07001524 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001525
1526 if (!mEnable) {
1527 waitForOnOff(true, false);
Zhihai Xu401202b2012-12-03 11:36:21 -08001528 handleDisable();
Zhihai Xu40874a02012-10-08 17:57:03 -07001529 waitForOnOff(false, false);
1530 }
fredc649fe492012-04-19 01:07:18 -07001531 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001532 }
fredcbf072a72012-05-09 16:52:50 -07001533 case MESSAGE_BLUETOOTH_STATE_CHANGE:
fredc0f420372012-04-12 00:02:00 -07001534 {
fredcbf072a72012-05-09 16:52:50 -07001535 int prevState = msg.arg1;
1536 int newState = msg.arg2;
Marie Janssencb21ad72016-12-13 10:51:02 -08001537 if (DBG) {
1538 Slog.d(TAG, "MESSAGE_BLUETOOTH_STATE_CHANGE: " + BluetoothAdapter.nameForState(prevState) + " > " +
1539 BluetoothAdapter.nameForState(newState));
1540 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001541 mState = newState;
1542 bluetoothStateChangeHandler(prevState, newState);
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001543 // handle error state transition case from TURNING_ON to OFF
1544 // unbind and rebind bluetooth service and enable bluetooth
Nitin Arorad055adb2015-03-02 15:03:51 -08001545 if ((prevState == BluetoothAdapter.STATE_BLE_TURNING_ON) &&
Calvin Ona0b91d72016-06-15 17:58:23 -07001546 (newState == BluetoothAdapter.STATE_OFF) &&
1547 (mBluetooth != null) && mEnable) {
Marie Janssen2977c3e2016-11-09 12:01:24 -08001548 recoverBluetoothServiceFromError(false);
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001549 }
Nitin Arorad055adb2015-03-02 15:03:51 -08001550 if ((prevState == BluetoothAdapter.STATE_TURNING_ON) &&
Calvin Ona0b91d72016-06-15 17:58:23 -07001551 (newState == BluetoothAdapter.STATE_BLE_ON) &&
1552 (mBluetooth != null) && mEnable) {
Marie Janssen2977c3e2016-11-09 12:01:24 -08001553 recoverBluetoothServiceFromError(true);
Nitin Arorad055adb2015-03-02 15:03:51 -08001554 }
Calvin Ona0b91d72016-06-15 17:58:23 -07001555 // If we tried to enable BT while BT was in the process of shutting down,
1556 // wait for the BT process to fully tear down and then force a restart
1557 // here. This is a bit of a hack (b/29363429).
1558 if ((prevState == BluetoothAdapter.STATE_BLE_TURNING_OFF) &&
1559 (newState == BluetoothAdapter.STATE_OFF)) {
1560 if (mEnable) {
1561 Slog.d(TAG, "Entering STATE_OFF but mEnabled is true; restarting.");
1562 waitForOnOff(false, true);
1563 Message restartMsg = mHandler.obtainMessage(
1564 MESSAGE_RESTART_BLUETOOTH_SERVICE);
1565 mHandler.sendMessageDelayed(restartMsg, 2 * SERVICE_RESTART_TIME_MS);
1566 }
1567 }
Nitin Arorad055adb2015-03-02 15:03:51 -08001568 if (newState == BluetoothAdapter.STATE_ON ||
Calvin Ona0b91d72016-06-15 17:58:23 -07001569 newState == BluetoothAdapter.STATE_BLE_ON) {
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001570 // bluetooth is working, reset the counter
1571 if (mErrorRecoveryRetryCounter != 0) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001572 Slog.w(TAG, "bluetooth is recovered from error");
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001573 mErrorRecoveryRetryCounter = 0;
1574 }
1575 }
fredc649fe492012-04-19 01:07:18 -07001576 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001577 }
fredc0f420372012-04-12 00:02:00 -07001578 case MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED:
1579 {
Marie Janssencb21ad72016-12-13 10:51:02 -08001580 Slog.e(TAG, "MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED(" + msg.arg1 + ")");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001581 try {
1582 mBluetoothLock.writeLock().lock();
Matthew Xieddf7e472013-03-01 18:41:02 -08001583 if (msg.arg1 == SERVICE_IBLUETOOTH) {
1584 // if service is unbinded already, do nothing and return
1585 if (mBluetooth == null) break;
1586 mBluetooth = null;
1587 } else if (msg.arg1 == SERVICE_IBLUETOOTHGATT) {
1588 mBluetoothGatt = null;
1589 break;
1590 } else {
Marie Janssencb21ad72016-12-13 10:51:02 -08001591 Slog.e(TAG, "Unknown argument for service disconnect!");
Matthew Xieddf7e472013-03-01 18:41:02 -08001592 break;
1593 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001594 } finally {
1595 mBluetoothLock.writeLock().unlock();
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301596 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001597
Marie Janssene54b4222017-03-16 18:10:59 -07001598 // log the unexpected crash
1599 addCrashLog();
1600 addActiveLog(REASON_UNEXPECTED, false);
Zhihai Xu40874a02012-10-08 17:57:03 -07001601 if (mEnable) {
1602 mEnable = false;
1603 // Send a Bluetooth Restart message
1604 Message restartMsg = mHandler.obtainMessage(
1605 MESSAGE_RESTART_BLUETOOTH_SERVICE);
1606 mHandler.sendMessageDelayed(restartMsg,
1607 SERVICE_RESTART_TIME_MS);
1608 }
1609
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001610 sendBluetoothServiceDownCallback();
Zhihai Xu40874a02012-10-08 17:57:03 -07001611
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001612 // Send BT state broadcast to update
1613 // the BT icon correctly
1614 if ((mState == BluetoothAdapter.STATE_TURNING_ON) ||
Calvin Ona0b91d72016-06-15 17:58:23 -07001615 (mState == BluetoothAdapter.STATE_ON)) {
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001616 bluetoothStateChangeHandler(BluetoothAdapter.STATE_ON,
1617 BluetoothAdapter.STATE_TURNING_OFF);
1618 mState = BluetoothAdapter.STATE_TURNING_OFF;
Zhihai Xu40874a02012-10-08 17:57:03 -07001619 }
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001620 if (mState == BluetoothAdapter.STATE_TURNING_OFF) {
1621 bluetoothStateChangeHandler(BluetoothAdapter.STATE_TURNING_OFF,
1622 BluetoothAdapter.STATE_OFF);
1623 }
1624
1625 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
1626 mState = BluetoothAdapter.STATE_OFF;
fredc649fe492012-04-19 01:07:18 -07001627 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001628 }
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301629 case MESSAGE_RESTART_BLUETOOTH_SERVICE:
1630 {
Marie Janssencb21ad72016-12-13 10:51:02 -08001631 Slog.d(TAG, "MESSAGE_RESTART_BLUETOOTH_SERVICE");
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301632 /* Enable without persisting the setting as
1633 it doesnt change when IBluetooth
1634 service restarts */
Zhihai Xu40874a02012-10-08 17:57:03 -07001635 mEnable = true;
Marie Janssene54b4222017-03-16 18:10:59 -07001636 addActiveLog(REASON_RESTARTED, true);
Zhihai Xu401202b2012-12-03 11:36:21 -08001637 handleEnable(mQuietEnable);
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301638 break;
1639 }
Marie Janssencb21ad72016-12-13 10:51:02 -08001640 case MESSAGE_TIMEOUT_BIND: {
1641 Slog.e(TAG, "MESSAGE_TIMEOUT_BIND");
1642 mBluetoothLock.writeLock().lock();
1643 mBinding = false;
1644 mBluetoothLock.writeLock().unlock();
1645 break;
1646 }
fredc0f420372012-04-12 00:02:00 -07001647 case MESSAGE_TIMEOUT_UNBIND:
1648 {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001649 Slog.e(TAG, "MESSAGE_TIMEOUT_UNBIND");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001650 mBluetoothLock.writeLock().lock();
1651 mUnbinding = false;
1652 mBluetoothLock.writeLock().unlock();
fredc649fe492012-04-19 01:07:18 -07001653 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001654 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001655
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001656 case MESSAGE_USER_SWITCHED: {
1657 if (DBG) Slog.d(TAG, "MESSAGE_USER_SWITCHED");
Zhihai Xu40874a02012-10-08 17:57:03 -07001658 mHandler.removeMessages(MESSAGE_USER_SWITCHED);
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001659
Zhihai Xu40874a02012-10-08 17:57:03 -07001660 /* disable and enable BT when detect a user switch */
1661 if (mEnable && mBluetooth != null) {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001662 try {
1663 mBluetoothLock.readLock().lock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001664 if (mBluetooth != null) {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001665 mBluetooth.unregisterCallback(mBluetoothCallback);
Zhihai Xu40874a02012-10-08 17:57:03 -07001666 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001667 } catch (RemoteException re) {
1668 Slog.e(TAG, "Unable to unregister", re);
1669 } finally {
1670 mBluetoothLock.readLock().unlock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001671 }
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001672
1673 if (mState == BluetoothAdapter.STATE_TURNING_OFF) {
1674 // MESSAGE_USER_SWITCHED happened right after MESSAGE_ENABLE
1675 bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_OFF);
1676 mState = BluetoothAdapter.STATE_OFF;
1677 }
1678 if (mState == BluetoothAdapter.STATE_OFF) {
1679 bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_TURNING_ON);
1680 mState = BluetoothAdapter.STATE_TURNING_ON;
1681 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001682
1683 waitForOnOff(true, false);
1684
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001685 if (mState == BluetoothAdapter.STATE_TURNING_ON) {
1686 bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_ON);
1687 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001688
Benjamin Franze8b98922014-11-12 15:57:54 +00001689 unbindAllBluetoothProfileServices();
Zhihai Xu40874a02012-10-08 17:57:03 -07001690 // disable
Marie Janssene54b4222017-03-16 18:10:59 -07001691 addActiveLog(REASON_USER_SWITCH, false);
Zhihai Xu401202b2012-12-03 11:36:21 -08001692 handleDisable();
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001693 // Pbap service need receive STATE_TURNING_OFF intent to close
1694 bluetoothStateChangeHandler(BluetoothAdapter.STATE_ON,
1695 BluetoothAdapter.STATE_TURNING_OFF);
Zhihai Xu40874a02012-10-08 17:57:03 -07001696
Pavlin Radoslavov41401112016-06-27 15:25:18 -07001697 boolean didDisableTimeout = !waitForOnOff(false, true);
Zhihai Xu40874a02012-10-08 17:57:03 -07001698
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001699 bluetoothStateChangeHandler(BluetoothAdapter.STATE_TURNING_OFF,
Zhihai Xu40874a02012-10-08 17:57:03 -07001700 BluetoothAdapter.STATE_OFF);
Zhihai Xu40874a02012-10-08 17:57:03 -07001701 sendBluetoothServiceDownCallback();
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001702
Pavlin Radoslavove957a8a2016-05-24 15:28:41 -07001703 try {
1704 mBluetoothLock.writeLock().lock();
1705 if (mBluetooth != null) {
1706 mBluetooth = null;
1707 // Unbind
1708 mContext.unbindService(mConnection);
1709 }
1710 mBluetoothGatt = null;
1711 } finally {
1712 mBluetoothLock.writeLock().unlock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001713 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001714
Pavlin Radoslavov41401112016-06-27 15:25:18 -07001715 //
1716 // If disabling Bluetooth times out, wait for an
1717 // additional amount of time to ensure the process is
1718 // shut down completely before attempting to restart.
1719 //
1720 if (didDisableTimeout) {
1721 SystemClock.sleep(3000);
1722 } else {
1723 SystemClock.sleep(100);
1724 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001725
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001726 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
1727 mState = BluetoothAdapter.STATE_OFF;
Zhihai Xu40874a02012-10-08 17:57:03 -07001728 // enable
Marie Janssene54b4222017-03-16 18:10:59 -07001729 addActiveLog(REASON_USER_SWITCH, true);
Zhihai Xu401202b2012-12-03 11:36:21 -08001730 handleEnable(mQuietEnable);
John Spurlock8a985d22014-02-25 09:40:05 -05001731 } else if (mBinding || mBluetooth != null) {
Zhihai Xu40874a02012-10-08 17:57:03 -07001732 Message userMsg = mHandler.obtainMessage(MESSAGE_USER_SWITCHED);
1733 userMsg.arg2 = 1 + msg.arg2;
Marie Janssencb21ad72016-12-13 10:51:02 -08001734 // if user is switched when service is binding retry after a delay
Zhihai Xu40874a02012-10-08 17:57:03 -07001735 mHandler.sendMessageDelayed(userMsg, USER_SWITCHED_TIME_MS);
1736 if (DBG) {
Marie Janssencb21ad72016-12-13 10:51:02 -08001737 Slog.d(TAG, "Retry MESSAGE_USER_SWITCHED " + userMsg.arg2);
Zhihai Xu40874a02012-10-08 17:57:03 -07001738 }
John Spurlock8a985d22014-02-25 09:40:05 -05001739 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001740 break;
1741 }
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001742 case MESSAGE_USER_UNLOCKED: {
1743 if (DBG) Slog.d(TAG, "MESSAGE_USER_UNLOCKED");
1744 mHandler.removeMessages(MESSAGE_USER_SWITCHED);
1745
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001746 if (mEnable && !mBinding && (mBluetooth == null)) {
1747 // We should be connected, but we gave up for some
1748 // reason; maybe the Bluetooth service wasn't encryption
1749 // aware, so try binding again.
1750 if (DBG) Slog.d(TAG, "Enabled but not bound; retrying after unlock");
1751 handleEnable(mQuietEnable);
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001752 }
1753 }
fredc0f420372012-04-12 00:02:00 -07001754 }
1755 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001756 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001757
Zhihai Xu401202b2012-12-03 11:36:21 -08001758 private void handleEnable(boolean quietMode) {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001759 mQuietEnable = quietMode;
1760
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001761 try {
1762 mBluetoothLock.writeLock().lock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001763 if ((mBluetooth == null) && (!mBinding)) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001764 //Start bind timeout and bind
1765 Message timeoutMsg=mHandler.obtainMessage(MESSAGE_TIMEOUT_BIND);
1766 mHandler.sendMessageDelayed(timeoutMsg,TIMEOUT_BIND_MS);
Matthew Xiecdce0b92012-07-12 19:06:15 -07001767 Intent i = new Intent(IBluetooth.class.getName());
Dianne Hackbornce09f5a2014-10-10 15:03:13 -07001768 if (!doBind(i, mConnection,Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT,
1769 UserHandle.CURRENT)) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001770 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
Zhihai Xu40874a02012-10-08 17:57:03 -07001771 } else {
1772 mBinding = true;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001773 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001774 } else if (mBluetooth != null) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001775 //Enable bluetooth
1776 try {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001777 if (!mQuietEnable) {
1778 if(!mBluetooth.enable()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001779 Slog.e(TAG,"IBluetooth.enable() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001780 }
1781 }
1782 else {
1783 if(!mBluetooth.enableNoAutoConnect()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001784 Slog.e(TAG,"IBluetooth.enableNoAutoConnect() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001785 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001786 }
1787 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001788 Slog.e(TAG,"Unable to call enable()",e);
Matthew Xiecdce0b92012-07-12 19:06:15 -07001789 }
1790 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001791 } finally {
1792 mBluetoothLock.writeLock().unlock();
Matthew Xiecdce0b92012-07-12 19:06:15 -07001793 }
1794 }
1795
Dianne Hackborn221ea892013-08-04 16:50:16 -07001796 boolean doBind(Intent intent, ServiceConnection conn, int flags, UserHandle user) {
1797 ComponentName comp = intent.resolveSystemService(mContext.getPackageManager(), 0);
1798 intent.setComponent(comp);
1799 if (comp == null || !mContext.bindServiceAsUser(intent, conn, flags, user)) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001800 Slog.e(TAG, "Fail to bind to: " + intent);
Dianne Hackborn221ea892013-08-04 16:50:16 -07001801 return false;
1802 }
1803 return true;
1804 }
1805
Zhihai Xu401202b2012-12-03 11:36:21 -08001806 private void handleDisable() {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001807 try {
1808 mBluetoothLock.readLock().lock();
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001809 if (mBluetooth != null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001810 if (DBG) Slog.d(TAG,"Sending off request.");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001811 if (!mBluetooth.disable()) {
1812 Slog.e(TAG,"IBluetooth.disable() returned false");
Matthew Xiecdce0b92012-07-12 19:06:15 -07001813 }
1814 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001815 } catch (RemoteException e) {
1816 Slog.e(TAG,"Unable to call disable()",e);
1817 } finally {
1818 mBluetoothLock.readLock().unlock();
Matthew Xiecdce0b92012-07-12 19:06:15 -07001819 }
1820 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001821
1822 private boolean checkIfCallerIsForegroundUser() {
1823 int foregroundUser;
1824 int callingUser = UserHandle.getCallingUserId();
Martijn Coenen8385c5a2012-11-29 10:14:16 -08001825 int callingUid = Binder.getCallingUid();
Zhihai Xu40874a02012-10-08 17:57:03 -07001826 long callingIdentity = Binder.clearCallingIdentity();
Benjamin Franze8b98922014-11-12 15:57:54 +00001827 UserManager um = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
1828 UserInfo ui = um.getProfileParent(callingUser);
1829 int parentUser = (ui != null) ? ui.id : UserHandle.USER_NULL;
Martijn Coenen8385c5a2012-11-29 10:14:16 -08001830 int callingAppId = UserHandle.getAppId(callingUid);
Zhihai Xu40874a02012-10-08 17:57:03 -07001831 boolean valid = false;
1832 try {
1833 foregroundUser = ActivityManager.getCurrentUser();
Martijn Coenen8385c5a2012-11-29 10:14:16 -08001834 valid = (callingUser == foregroundUser) ||
Benjamin Franze8b98922014-11-12 15:57:54 +00001835 parentUser == foregroundUser ||
Adrian Roosbd9a9a52014-08-18 15:31:57 +02001836 callingAppId == Process.NFC_UID ||
1837 callingAppId == mSystemUiUid;
Marie Janssencb21ad72016-12-13 10:51:02 -08001838 if (DBG && !valid) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001839 Slog.d(TAG, "checkIfCallerIsForegroundUser: valid=" + valid
Zhihai Xu40874a02012-10-08 17:57:03 -07001840 + " callingUser=" + callingUser
Benjamin Franze8b98922014-11-12 15:57:54 +00001841 + " parentUser=" + parentUser
Zhihai Xu40874a02012-10-08 17:57:03 -07001842 + " foregroundUser=" + foregroundUser);
1843 }
1844 } finally {
1845 Binder.restoreCallingIdentity(callingIdentity);
1846 }
1847 return valid;
1848 }
1849
Nitin Arorad055adb2015-03-02 15:03:51 -08001850 private void sendBleStateChanged(int prevState, int newState) {
Marie Janssencb21ad72016-12-13 10:51:02 -08001851 if (DBG) Slog.d(TAG,"Sending BLE State Change: " + BluetoothAdapter.nameForState(prevState) +
1852 " > " + BluetoothAdapter.nameForState(newState));
Nitin Arorad055adb2015-03-02 15:03:51 -08001853 // Send broadcast message to everyone else
1854 Intent intent = new Intent(BluetoothAdapter.ACTION_BLE_STATE_CHANGED);
1855 intent.putExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE, prevState);
1856 intent.putExtra(BluetoothAdapter.EXTRA_STATE, newState);
1857 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1858 mContext.sendBroadcastAsUser(intent, UserHandle.ALL, BLUETOOTH_PERM);
1859 }
1860
Zhihai Xu40874a02012-10-08 17:57:03 -07001861 private void bluetoothStateChangeHandler(int prevState, int newState) {
Nitin Arorad055adb2015-03-02 15:03:51 -08001862 boolean isStandardBroadcast = true;
Marie Janssencb21ad72016-12-13 10:51:02 -08001863 if (prevState == newState) { // No change. Nothing to do.
1864 return;
1865 }
1866 // Notify all proxy objects first of adapter state change
1867 if (newState == BluetoothAdapter.STATE_BLE_ON ||
1868 newState == BluetoothAdapter.STATE_OFF) {
1869 boolean intermediate_off = (prevState == BluetoothAdapter.STATE_TURNING_OFF
1870 && newState == BluetoothAdapter.STATE_BLE_ON);
Zhihai Xu40874a02012-10-08 17:57:03 -07001871
Marie Janssencb21ad72016-12-13 10:51:02 -08001872 if (newState == BluetoothAdapter.STATE_OFF) {
1873 // If Bluetooth is off, send service down event to proxy objects, and unbind
1874 if (DBG) Slog.d(TAG, "Bluetooth is complete send Service Down");
1875 sendBluetoothServiceDownCallback();
1876 unbindAndFinish();
Nitin Arorad055adb2015-03-02 15:03:51 -08001877 sendBleStateChanged(prevState, newState);
Marie Janssencb21ad72016-12-13 10:51:02 -08001878 // Don't broadcast as it has already been broadcast before
Nitin Arorad055adb2015-03-02 15:03:51 -08001879 isStandardBroadcast = false;
1880
Marie Janssencb21ad72016-12-13 10:51:02 -08001881 } else if (!intermediate_off) {
1882 // connect to GattService
1883 if (DBG) Slog.d(TAG, "Bluetooth is in LE only mode");
1884 if (mBluetoothGatt != null) {
1885 if (DBG) Slog.d(TAG, "Calling BluetoothGattServiceUp");
1886 onBluetoothGattServiceUp();
1887 } else {
1888 if (DBG) Slog.d(TAG, "Binding Bluetooth GATT service");
1889 if (mContext.getPackageManager().hasSystemFeature(
1890 PackageManager.FEATURE_BLUETOOTH_LE)) {
1891 Intent i = new Intent(IBluetoothGatt.class.getName());
1892 doBind(i, mConnection, Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT, UserHandle.CURRENT);
1893 }
Nitin Arorad055adb2015-03-02 15:03:51 -08001894 }
Marie Janssencb21ad72016-12-13 10:51:02 -08001895 sendBleStateChanged(prevState, newState);
1896 //Don't broadcase this as std intent
1897 isStandardBroadcast = false;
1898
1899 } else if (intermediate_off) {
1900 if (DBG) Slog.d(TAG, "Intermediate off, back to LE only mode");
1901 // For LE only mode, broadcast as is
1902 sendBleStateChanged(prevState, newState);
1903 sendBluetoothStateCallback(false); // BT is OFF for general users
1904 // Broadcast as STATE_OFF
1905 newState = BluetoothAdapter.STATE_OFF;
1906 sendBrEdrDownCallback();
Nitin Arorad055adb2015-03-02 15:03:51 -08001907 }
Marie Janssencb21ad72016-12-13 10:51:02 -08001908 } else if (newState == BluetoothAdapter.STATE_ON) {
1909 boolean isUp = (newState == BluetoothAdapter.STATE_ON);
1910 sendBluetoothStateCallback(isUp);
1911 sendBleStateChanged(prevState, newState);
1912
1913 } else if (newState == BluetoothAdapter.STATE_BLE_TURNING_ON ||
1914 newState == BluetoothAdapter.STATE_BLE_TURNING_OFF ) {
1915 sendBleStateChanged(prevState, newState);
1916 isStandardBroadcast = false;
1917
1918 } else if (newState == BluetoothAdapter.STATE_TURNING_ON ||
1919 newState == BluetoothAdapter.STATE_TURNING_OFF) {
1920 sendBleStateChanged(prevState, newState);
1921 }
1922
1923 if (isStandardBroadcast) {
1924 if (prevState == BluetoothAdapter.STATE_BLE_ON) {
1925 // Show prevState of BLE_ON as OFF to standard users
1926 prevState = BluetoothAdapter.STATE_OFF;
1927 }
1928 Intent intent = new Intent(BluetoothAdapter.ACTION_STATE_CHANGED);
1929 intent.putExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE, prevState);
1930 intent.putExtra(BluetoothAdapter.EXTRA_STATE, newState);
1931 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1932 mContext.sendBroadcastAsUser(intent, UserHandle.ALL, BLUETOOTH_PERM);
Zhihai Xu40874a02012-10-08 17:57:03 -07001933 }
1934 }
1935
1936 /**
1937 * if on is true, wait for state become ON
1938 * if off is true, wait for state become OFF
1939 * if both on and off are false, wait for state not ON
1940 */
1941 private boolean waitForOnOff(boolean on, boolean off) {
1942 int i = 0;
1943 while (i < 10) {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001944 try {
1945 mBluetoothLock.readLock().lock();
1946 if (mBluetooth == null) break;
1947 if (on) {
1948 if (mBluetooth.getState() == BluetoothAdapter.STATE_ON) return true;
1949 } else if (off) {
1950 if (mBluetooth.getState() == BluetoothAdapter.STATE_OFF) return true;
1951 } else {
1952 if (mBluetooth.getState() != BluetoothAdapter.STATE_ON) return true;
Zhihai Xu40874a02012-10-08 17:57:03 -07001953 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001954 } catch (RemoteException e) {
1955 Slog.e(TAG, "getState()", e);
1956 break;
1957 } finally {
1958 mBluetoothLock.readLock().unlock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001959 }
1960 if (on || off) {
1961 SystemClock.sleep(300);
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07001962 } else {
Zhihai Xu40874a02012-10-08 17:57:03 -07001963 SystemClock.sleep(50);
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07001964 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001965 i++;
1966 }
Jeff Sharkey67609c72016-03-05 14:29:13 -07001967 Slog.e(TAG,"waitForOnOff time out");
Zhihai Xu40874a02012-10-08 17:57:03 -07001968 return false;
1969 }
Zhihai Xu681ae7f2012-11-12 15:14:18 -08001970
Marie Janssen59804562016-12-28 14:13:21 -08001971 private void sendDisableMsg(String packageName) {
Zhihai Xu401202b2012-12-03 11:36:21 -08001972 mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_DISABLE));
Marie Janssen59804562016-12-28 14:13:21 -08001973 addActiveLog(packageName, false);
Zhihai Xu401202b2012-12-03 11:36:21 -08001974 }
1975
Marie Janssen59804562016-12-28 14:13:21 -08001976 private void sendEnableMsg(boolean quietMode, String packageName) {
Zhihai Xu401202b2012-12-03 11:36:21 -08001977 mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_ENABLE,
1978 quietMode ? 1 : 0, 0));
Marie Janssen59804562016-12-28 14:13:21 -08001979 addActiveLog(packageName, true);
1980 }
1981
1982 private void addActiveLog(String packageName, boolean enable) {
1983 synchronized (mActiveLogs) {
Marie Janssene54b4222017-03-16 18:10:59 -07001984 if (mActiveLogs.size() > ACTIVE_LOG_MAX_SIZE) {
Marie Janssen59804562016-12-28 14:13:21 -08001985 mActiveLogs.remove();
1986 }
1987 mActiveLogs.add(new ActiveLog(packageName, enable, System.currentTimeMillis()));
1988 }
Zhihai Xu401202b2012-12-03 11:36:21 -08001989 }
1990
Marie Janssene54b4222017-03-16 18:10:59 -07001991 private void addCrashLog() {
1992 synchronized (mCrashTimestamps) {
1993 if (mCrashTimestamps.size() == CRASH_LOG_MAX_SIZE) mCrashTimestamps.removeFirst();
1994 mCrashTimestamps.add(System.currentTimeMillis());
1995 mCrashes++;
1996 }
1997 }
1998
Marie Janssen2977c3e2016-11-09 12:01:24 -08001999 private void recoverBluetoothServiceFromError(boolean clearBle) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07002000 Slog.e(TAG,"recoverBluetoothServiceFromError");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07002001 try {
2002 mBluetoothLock.readLock().lock();
Zhihai Xudd9d17d2013-01-08 17:05:58 -08002003 if (mBluetooth != null) {
2004 //Unregister callback object
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07002005 mBluetooth.unregisterCallback(mBluetoothCallback);
Zhihai Xudd9d17d2013-01-08 17:05:58 -08002006 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07002007 } catch (RemoteException re) {
2008 Slog.e(TAG, "Unable to unregister", re);
2009 } finally {
2010 mBluetoothLock.readLock().unlock();
Zhihai Xudd9d17d2013-01-08 17:05:58 -08002011 }
2012
2013 SystemClock.sleep(500);
2014
2015 // disable
Marie Janssene54b4222017-03-16 18:10:59 -07002016 addActiveLog(REASON_START_CRASH, false);
Zhihai Xudd9d17d2013-01-08 17:05:58 -08002017 handleDisable();
2018
2019 waitForOnOff(false, true);
2020
2021 sendBluetoothServiceDownCallback();
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07002022
Pavlin Radoslavove957a8a2016-05-24 15:28:41 -07002023 try {
2024 mBluetoothLock.writeLock().lock();
2025 if (mBluetooth != null) {
2026 mBluetooth = null;
2027 // Unbind
2028 mContext.unbindService(mConnection);
2029 }
2030 mBluetoothGatt = null;
2031 } finally {
2032 mBluetoothLock.writeLock().unlock();
Zhihai Xudd9d17d2013-01-08 17:05:58 -08002033 }
2034
2035 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
2036 mState = BluetoothAdapter.STATE_OFF;
2037
Marie Janssen2977c3e2016-11-09 12:01:24 -08002038 if (clearBle) {
2039 clearBleApps();
2040 }
2041
Zhihai Xudd9d17d2013-01-08 17:05:58 -08002042 mEnable = false;
2043
2044 if (mErrorRecoveryRetryCounter++ < MAX_ERROR_RESTART_RETRIES) {
2045 // Send a Bluetooth Restart message to reenable bluetooth
2046 Message restartMsg = mHandler.obtainMessage(
2047 MESSAGE_RESTART_BLUETOOTH_SERVICE);
2048 mHandler.sendMessageDelayed(restartMsg, ERROR_RESTART_TIME_MS);
2049 } else {
2050 // todo: notify user to power down and power up phone to make bluetooth work.
2051 }
2052 }
Mike Lockwood726d4de2014-10-28 14:06:28 -07002053
Lenka Trochtova63d5e4a72016-12-02 12:19:39 +01002054 private boolean isBluetoothDisallowed() {
2055 long callingIdentity = Binder.clearCallingIdentity();
2056 try {
2057 return mContext.getSystemService(UserManager.class)
2058 .hasUserRestriction(UserManager.DISALLOW_BLUETOOTH, UserHandle.SYSTEM);
2059 } finally {
2060 Binder.restoreCallingIdentity(callingIdentity);
2061 }
2062 }
2063
Lenka Trochtovac6f0e232017-01-17 10:35:49 +01002064 /**
2065 * Disables BluetoothOppLauncherActivity component, so the Bluetooth sharing option is not
2066 * offered to the user if Bluetooth is disallowed. Puts the component to its default state if
2067 * Bluetooth is not disallowed.
2068 *
2069 * @param bluetoothDisallowed whether the {@link UserManager.DISALLOW_BLUETOOTH} user
2070 * restriction was set.
2071 */
2072 private void updateOppLauncherComponentState(boolean bluetoothDisallowed) {
2073 final ComponentName oppLauncherComponent = new ComponentName("com.android.bluetooth",
2074 "com.android.bluetooth.opp.BluetoothOppLauncherActivity");
2075 final int newState = bluetoothDisallowed
2076 ? PackageManager.COMPONENT_ENABLED_STATE_DISABLED
2077 : PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
2078 try {
2079 mContext.getPackageManager()
2080 .setComponentEnabledSetting(oppLauncherComponent, newState, 0);
2081 } catch (Exception e) {
2082 // The component was not found, do nothing.
2083 }
2084 }
2085
Mike Lockwood726d4de2014-10-28 14:06:28 -07002086 @Override
Pavlin Radoslavov6e8faff2016-02-23 11:54:37 -08002087 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06002088 if (!DumpUtils.checkDumpPermission(mContext, TAG, writer)) return;
Pavlin Radoslavov6e8faff2016-02-23 11:54:37 -08002089 String errorMsg = null;
Marie Janssen59804562016-12-28 14:13:21 -08002090
2091 boolean protoOut = (args.length > 0) && args[0].startsWith("--proto");
2092
2093 if (!protoOut) {
2094 writer.println("Bluetooth Status");
2095 writer.println(" enabled: " + isEnabled());
2096 writer.println(" state: " + BluetoothAdapter.nameForState(mState));
2097 writer.println(" address: " + mAddress);
2098 writer.println(" name: " + mName);
2099 if (mEnable) {
2100 long onDuration = System.currentTimeMillis() - mActiveLogs.getLast().getTime();
2101 String onDurationString = String.format("%02d:%02d:%02d.%03d",
2102 (int)(onDuration / (1000 * 60 * 60)),
2103 (int)((onDuration / (1000 * 60)) % 60),
2104 (int)((onDuration / 1000) % 60),
2105 (int)(onDuration % 1000));
2106 writer.println(" time since enabled: " + onDurationString + "\n");
2107 }
2108
Marie Janssena95924d2017-01-18 09:37:52 -08002109 if (mActiveLogs.size() == 0) {
2110 writer.println("Bluetooth never enabled!");
2111 } else {
2112 writer.println("Enable log:");
2113 for (ActiveLog log : mActiveLogs) {
2114 writer.println(" " + log);
2115 }
Marie Janssen59804562016-12-28 14:13:21 -08002116 }
2117
Marie Janssene54b4222017-03-16 18:10:59 -07002118 writer.println("Bluetooth crashed " + mCrashes + " time" + (mCrashes == 1 ? "" : "s"));
2119 if (mCrashes == CRASH_LOG_MAX_SIZE) writer.println("(last " + CRASH_LOG_MAX_SIZE + ")");
2120 for (Long time : mCrashTimestamps) {
2121 writer.println(" " + timeToLog(time.longValue()));
2122 }
2123
Marie Janssena95924d2017-01-18 09:37:52 -08002124 String bleAppString = "No BLE Apps registered.";
2125 if (mBleApps.size() == 1) {
2126 bleAppString = "1 BLE App registered:";
2127 } else if (mBleApps.size() > 1) {
2128 bleAppString = mBleApps.size() + " BLE Apps registered:";
2129 }
2130 writer.println("\n" + bleAppString);
Marie Janssen59804562016-12-28 14:13:21 -08002131 for (ClientDeathRecipient app : mBleApps.values()) {
Marie Janssena95924d2017-01-18 09:37:52 -08002132 writer.println(" " + app.getPackageName());
Marie Janssen59804562016-12-28 14:13:21 -08002133 }
2134
Marie Janssena95924d2017-01-18 09:37:52 -08002135 writer.println("");
Marie Janssen59804562016-12-28 14:13:21 -08002136 writer.flush();
Marie Janssenf5ec5382017-01-03 11:37:38 -08002137 if (args.length == 0) {
Marie Janssena95924d2017-01-18 09:37:52 -08002138 // Add arg to produce output
2139 args = new String[1];
2140 args[0] = "--print";
Marie Janssenf5ec5382017-01-03 11:37:38 -08002141 }
Marie Janssen59804562016-12-28 14:13:21 -08002142 }
2143
Pavlin Radoslavov6e8faff2016-02-23 11:54:37 -08002144 if (mBluetoothBinder == null) {
2145 errorMsg = "Bluetooth Service not connected";
2146 } else {
2147 try {
2148 mBluetoothBinder.dump(fd, args);
2149 } catch (RemoteException re) {
Marie Janssen59804562016-12-28 14:13:21 -08002150 errorMsg = "RemoteException while dumping Bluetooth Service";
Pavlin Radoslavov6e8faff2016-02-23 11:54:37 -08002151 }
Mike Lockwood726d4de2014-10-28 14:06:28 -07002152 }
Pavlin Radoslavov6e8faff2016-02-23 11:54:37 -08002153 if (errorMsg != null) {
2154 // Silently return if we are extracting metrics in Protobuf format
Marie Janssen59804562016-12-28 14:13:21 -08002155 if (protoOut) return;
Pavlin Radoslavov6e8faff2016-02-23 11:54:37 -08002156 writer.println(errorMsg);
2157 }
Mike Lockwood726d4de2014-10-28 14:06:28 -07002158 }
fredc0f420372012-04-12 00:02:00 -07002159}