blob: 5cf9eead5de73507afe766972bc00f0921dd1446 [file] [log] [blame]
fredc0f420372012-04-12 00:02:00 -07001/*
Zhihai Xufa0fd392012-10-23 17:31:56 -07002 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
fredc0f420372012-04-12 00:02:00 -070015 */
16
17package com.android.server;
18
Svet Ganov408abf72015-05-12 19:13:36 -070019import android.Manifest;
Zhihai Xu40874a02012-10-08 17:57:03 -070020import android.app.ActivityManager;
fredc0f420372012-04-12 00:02:00 -070021import android.bluetooth.BluetoothAdapter;
Benjamin Franze8b98922014-11-12 15:57:54 +000022import android.bluetooth.BluetoothProfile;
fredc0f420372012-04-12 00:02:00 -070023import android.bluetooth.IBluetooth;
fredcbf072a72012-05-09 16:52:50 -070024import android.bluetooth.IBluetoothCallback;
Wei Wange4a744b2015-06-11 17:50:29 -070025import android.bluetooth.IBluetoothGatt;
Benjamin Franze8b98922014-11-12 15:57:54 +000026import android.bluetooth.IBluetoothHeadset;
fredc0f420372012-04-12 00:02:00 -070027import android.bluetooth.IBluetoothManager;
28import android.bluetooth.IBluetoothManagerCallback;
Benjamin Franze8b98922014-11-12 15:57:54 +000029import android.bluetooth.IBluetoothProfileServiceConnection;
fredc0f420372012-04-12 00:02:00 -070030import android.bluetooth.IBluetoothStateChangeCallback;
fredc0f420372012-04-12 00:02:00 -070031import android.content.BroadcastReceiver;
32import android.content.ComponentName;
33import android.content.ContentResolver;
34import android.content.Context;
35import android.content.Intent;
36import android.content.IntentFilter;
37import android.content.ServiceConnection;
Svetoslav Ganovc2ac5bd2016-06-29 17:31:44 -070038import android.content.pm.ApplicationInfo;
Matthew Xie32ab77b2013-05-08 19:26:57 -070039import android.content.pm.PackageManager;
Benjamin Franze8b98922014-11-12 15:57:54 +000040import android.content.pm.UserInfo;
Wei Wange4a744b2015-06-11 17:50:29 -070041import android.database.ContentObserver;
Zhihai Xu40874a02012-10-08 17:57:03 -070042import android.os.Binder;
Lenka Trochtova13a05192016-12-02 12:19:39 +010043import android.os.Bundle;
Svetoslav Ganovc2ac5bd2016-06-29 17:31:44 -070044import android.os.Build;
fredc0f420372012-04-12 00:02:00 -070045import android.os.Handler;
fredc0f420372012-04-12 00:02:00 -070046import android.os.IBinder;
Zhihai Xu40874a02012-10-08 17:57:03 -070047import android.os.Looper;
fredc0f420372012-04-12 00:02:00 -070048import android.os.Message;
Zhihai Xu40874a02012-10-08 17:57:03 -070049import android.os.Process;
fredcd6883532012-04-25 17:46:13 -070050import android.os.RemoteCallbackList;
fredc0f420372012-04-12 00:02:00 -070051import android.os.RemoteException;
Zhihai Xu40874a02012-10-08 17:57:03 -070052import android.os.SystemClock;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070053import android.os.UserHandle;
Benjamin Franze8b98922014-11-12 15:57:54 +000054import android.os.UserManager;
Lenka Trochtova13a05192016-12-02 12:19:39 +010055import android.os.UserManagerInternal;
56import android.os.UserManagerInternal.UserRestrictionsListener;
fredc0f420372012-04-12 00:02:00 -070057import android.provider.Settings;
Wei Wang67d84162015-04-26 17:04:29 -070058import android.provider.Settings.SettingNotFoundException;
Jeff Sharkey67609c72016-03-05 14:29:13 -070059import android.util.Slog;
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -070060import java.util.concurrent.locks.ReentrantReadWriteLock;
Mike Lockwood726d4de2014-10-28 14:06:28 -070061
62import java.io.FileDescriptor;
63import java.io.PrintWriter;
Marie Janssen2977c3e2016-11-09 12:01:24 -080064import java.util.concurrent.ConcurrentHashMap;
Benjamin Franze8b98922014-11-12 15:57:54 +000065import java.util.HashMap;
66import java.util.Map;
Miao Chou658bf2f2015-06-26 17:14:35 -070067
fredc0f420372012-04-12 00:02:00 -070068class BluetoothManagerService extends IBluetoothManager.Stub {
69 private static final String TAG = "BluetoothManagerService";
Pavlin Radoslavov41401112016-06-27 15:25:18 -070070 private static final boolean DBG = true;
fredc0f420372012-04-12 00:02:00 -070071
fredc0f420372012-04-12 00:02:00 -070072 private static final String BLUETOOTH_ADMIN_PERM = android.Manifest.permission.BLUETOOTH_ADMIN;
73 private static final String BLUETOOTH_PERM = android.Manifest.permission.BLUETOOTH;
fredc0f420372012-04-12 00:02:00 -070074 private static final String ACTION_SERVICE_STATE_CHANGED="com.android.bluetooth.btservice.action.STATE_CHANGED";
75 private static final String EXTRA_ACTION="action";
Zhihai Xud31c3222012-10-31 16:08:57 -070076 private static final String SECURE_SETTINGS_BLUETOOTH_ADDR_VALID="bluetooth_addr_valid";
fredc0f420372012-04-12 00:02:00 -070077 private static final String SECURE_SETTINGS_BLUETOOTH_ADDRESS="bluetooth_address";
78 private static final String SECURE_SETTINGS_BLUETOOTH_NAME="bluetooth_name";
fredc0f420372012-04-12 00:02:00 -070079 private static final int TIMEOUT_BIND_MS = 3000; //Maximum msec to wait for a bind
80 private static final int TIMEOUT_SAVE_MS = 500; //Maximum msec to wait for a save
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +053081 //Maximum msec to wait for service restart
82 private static final int SERVICE_RESTART_TIME_MS = 200;
Zhihai Xudd9d17d2013-01-08 17:05:58 -080083 //Maximum msec to wait for restart due to error
84 private static final int ERROR_RESTART_TIME_MS = 3000;
Zhihai Xu40874a02012-10-08 17:57:03 -070085 //Maximum msec to delay MESSAGE_USER_SWITCHED
86 private static final int USER_SWITCHED_TIME_MS = 200;
Benjamin Franze8b98922014-11-12 15:57:54 +000087 // Delay for the addProxy function in msec
88 private static final int ADD_PROXY_DELAY_MS = 100;
fredc0f420372012-04-12 00:02:00 -070089
90 private static final int MESSAGE_ENABLE = 1;
91 private static final int MESSAGE_DISABLE = 2;
fredc649fe492012-04-19 01:07:18 -070092 private static final int MESSAGE_REGISTER_ADAPTER = 20;
93 private static final int MESSAGE_UNREGISTER_ADAPTER = 21;
94 private static final int MESSAGE_REGISTER_STATE_CHANGE_CALLBACK = 30;
95 private static final int MESSAGE_UNREGISTER_STATE_CHANGE_CALLBACK = 31;
96 private static final int MESSAGE_BLUETOOTH_SERVICE_CONNECTED = 40;
97 private static final int MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED = 41;
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +053098 private static final int MESSAGE_RESTART_BLUETOOTH_SERVICE = 42;
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -070099 private static final int MESSAGE_BLUETOOTH_STATE_CHANGE = 60;
100 private static final int MESSAGE_TIMEOUT_BIND = 100;
101 private static final int MESSAGE_TIMEOUT_UNBIND = 101;
Ajay Panicker4bb48302016-03-31 14:14:27 -0700102 private static final int MESSAGE_GET_NAME_AND_ADDRESS = 200;
Zhihai Xu40874a02012-10-08 17:57:03 -0700103 private static final int MESSAGE_USER_SWITCHED = 300;
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -0700104 private static final int MESSAGE_USER_UNLOCKED = 301;
Benjamin Franze8b98922014-11-12 15:57:54 +0000105 private static final int MESSAGE_ADD_PROXY_DELAYED = 400;
106 private static final int MESSAGE_BIND_PROFILE_SERVICE = 401;
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -0700107 private static final int MAX_SAVE_RETRIES = 3;
108 private static final int MAX_ERROR_RESTART_RETRIES = 6;
Zhihai Xudd9d17d2013-01-08 17:05:58 -0800109
Zhihai Xu401202b2012-12-03 11:36:21 -0800110 // Bluetooth persisted setting is off
111 private static final int BLUETOOTH_OFF=0;
112 // Bluetooth persisted setting is on
113 // and Airplane mode won't affect Bluetooth state at start up
114 private static final int BLUETOOTH_ON_BLUETOOTH=1;
115 // Bluetooth persisted setting is on
116 // but Airplane mode will affect Bluetooth state at start up
117 // and Airplane mode will have higher priority.
118 private static final int BLUETOOTH_ON_AIRPLANE=2;
fredc0f420372012-04-12 00:02:00 -0700119
Matthew Xieddf7e472013-03-01 18:41:02 -0800120 private static final int SERVICE_IBLUETOOTH = 1;
121 private static final int SERVICE_IBLUETOOTHGATT = 2;
122
fredc0f420372012-04-12 00:02:00 -0700123 private final Context mContext;
Matthew Xiecdce0b92012-07-12 19:06:15 -0700124
125 // Locks are not provided for mName and mAddress.
126 // They are accessed in handler or broadcast receiver, same thread context.
fredc0f420372012-04-12 00:02:00 -0700127 private String mAddress;
128 private String mName;
Matthew Xie6fde3092012-07-11 17:10:07 -0700129 private final ContentResolver mContentResolver;
130 private final RemoteCallbackList<IBluetoothManagerCallback> mCallbacks;
131 private final RemoteCallbackList<IBluetoothStateChangeCallback> mStateChangeCallbacks;
Marie Janssen9db28eb2016-01-12 16:05:15 -0800132 private IBinder mBluetoothBinder;
fredc649fe492012-04-19 01:07:18 -0700133 private IBluetooth mBluetooth;
Matthew Xieddf7e472013-03-01 18:41:02 -0800134 private IBluetoothGatt mBluetoothGatt;
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700135 private final ReentrantReadWriteLock mBluetoothLock =
136 new ReentrantReadWriteLock();
fredc649fe492012-04-19 01:07:18 -0700137 private boolean mBinding;
138 private boolean mUnbinding;
Zhihai Xu401202b2012-12-03 11:36:21 -0800139 // used inside handler thread
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700140 private boolean mQuietEnable = false;
Zhihai Xu401202b2012-12-03 11:36:21 -0800141 // configuarion from external IBinder call which is used to
142 // synchronize with broadcast receiver.
143 private boolean mQuietEnableExternal;
144 // configuarion from external IBinder call which is used to
145 // synchronize with broadcast receiver.
146 private boolean mEnableExternal;
147 // used inside handler thread
Zhihai Xu40874a02012-10-08 17:57:03 -0700148 private boolean mEnable;
149 private int mState;
Zhihai Xu40874a02012-10-08 17:57:03 -0700150 private final BluetoothHandler mHandler;
Zhihai Xudd9d17d2013-01-08 17:05:58 -0800151 private int mErrorRecoveryRetryCounter;
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200152 private final int mSystemUiUid;
fredc0f420372012-04-12 00:02:00 -0700153
Benjamin Franze8b98922014-11-12 15:57:54 +0000154 // Save a ProfileServiceConnections object for each of the bound
155 // bluetooth profile services
156 private final Map <Integer, ProfileServiceConnections> mProfileServices =
157 new HashMap <Integer, ProfileServiceConnections>();
158
Svetoslav Ganovc2ac5bd2016-06-29 17:31:44 -0700159 private final boolean mPermissionReviewRequired;
160
fredc649fe492012-04-19 01:07:18 -0700161 private void registerForAirplaneMode(IntentFilter filter) {
162 final ContentResolver resolver = mContext.getContentResolver();
Christopher Tatec09cdce2012-09-10 16:50:14 -0700163 final String airplaneModeRadios = Settings.Global.getString(resolver,
164 Settings.Global.AIRPLANE_MODE_RADIOS);
165 final String toggleableRadios = Settings.Global.getString(resolver,
166 Settings.Global.AIRPLANE_MODE_TOGGLEABLE_RADIOS);
fredc649fe492012-04-19 01:07:18 -0700167 boolean mIsAirplaneSensitive = airplaneModeRadios == null ? true :
Christopher Tatec09cdce2012-09-10 16:50:14 -0700168 airplaneModeRadios.contains(Settings.Global.RADIO_BLUETOOTH);
fredc649fe492012-04-19 01:07:18 -0700169 if (mIsAirplaneSensitive) {
170 filter.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED);
171 }
172 }
173
fredcbf072a72012-05-09 16:52:50 -0700174 private final IBluetoothCallback mBluetoothCallback = new IBluetoothCallback.Stub() {
175 @Override
176 public void onBluetoothStateChange(int prevState, int newState) throws RemoteException {
177 Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_STATE_CHANGE,prevState,newState);
178 mHandler.sendMessage(msg);
179 }
180 };
181
Lenka Trochtova13a05192016-12-02 12:19:39 +0100182 private final UserRestrictionsListener mUserRestrictionsListener =
183 new UserRestrictionsListener() {
184 @Override
185 public void onUserRestrictionsChanged(int userId, Bundle newRestrictions,
186 Bundle prevRestrictions) {
187 final boolean bluetoothDisallowed =
188 newRestrictions.getBoolean(UserManager.DISALLOW_BLUETOOTH);
189 if ((mEnable || mEnableExternal) && bluetoothDisallowed) {
Svetoslav Ganovc2ac5bd2016-06-29 17:31:44 -0700190 try {
191 disable("android.os.UserManagerInternal", true);
192 } catch (RemoteException e) {
193 // Shouldn't happen: startConsentUiIfNeeded not called
194 // when from system.
195 }
Lenka Trochtova13a05192016-12-02 12:19:39 +0100196 }
197 }
198 };
199
fredcbf072a72012-05-09 16:52:50 -0700200 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
fredc0f420372012-04-12 00:02:00 -0700201 @Override
202 public void onReceive(Context context, Intent intent) {
203 String action = intent.getAction();
fredcbf072a72012-05-09 16:52:50 -0700204 if (BluetoothAdapter.ACTION_LOCAL_NAME_CHANGED.equals(action)) {
fredc0f420372012-04-12 00:02:00 -0700205 String newName = intent.getStringExtra(BluetoothAdapter.EXTRA_LOCAL_NAME);
Jeff Sharkey67609c72016-03-05 14:29:13 -0700206 if (DBG) Slog.d(TAG, "Bluetooth Adapter name changed to " + newName);
fredc0f420372012-04-12 00:02:00 -0700207 if (newName != null) {
208 storeNameAndAddress(newName, null);
209 }
fredc649fe492012-04-19 01:07:18 -0700210 } else if (Intent.ACTION_AIRPLANE_MODE_CHANGED.equals(action)) {
Zhihai Xu401202b2012-12-03 11:36:21 -0800211 synchronized(mReceiver) {
212 if (isBluetoothPersistedStateOn()) {
213 if (isAirplaneModeOn()) {
214 persistBluetoothSetting(BLUETOOTH_ON_AIRPLANE);
215 } else {
216 persistBluetoothSetting(BLUETOOTH_ON_BLUETOOTH);
217 }
218 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800219
220 int st = BluetoothAdapter.STATE_OFF;
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700221 try {
222 mBluetoothLock.readLock().lock();
223 if (mBluetooth != null) {
Nitin Arorad055adb2015-03-02 15:03:51 -0800224 st = mBluetooth.getState();
Nitin Arorad055adb2015-03-02 15:03:51 -0800225 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700226 } catch (RemoteException e) {
227 Slog.e(TAG, "Unable to call getState", e);
228 } finally {
229 mBluetoothLock.readLock().unlock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800230 }
Jeff Sharkey67609c72016-03-05 14:29:13 -0700231 Slog.d(TAG, "state" + st);
Nitin Arorad055adb2015-03-02 15:03:51 -0800232
Zhihai Xu401202b2012-12-03 11:36:21 -0800233 if (isAirplaneModeOn()) {
Nitin Arorad055adb2015-03-02 15:03:51 -0800234 // Clear registered LE apps to force shut-off
Marie Janssen2977c3e2016-11-09 12:01:24 -0800235 clearBleApps();
Nitin Arorad055adb2015-03-02 15:03:51 -0800236 if (st == BluetoothAdapter.STATE_BLE_ON) {
237 //if state is BLE_ON make sure you trigger disableBLE part
238 try {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700239 mBluetoothLock.readLock().lock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800240 if (mBluetooth != null) {
241 mBluetooth.onBrEdrDown();
Marie Janssen6a383a72016-10-25 10:47:51 -0700242 mEnable = false;
Nitin Arorad055adb2015-03-02 15:03:51 -0800243 mEnableExternal = false;
244 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700245 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700246 Slog.e(TAG,"Unable to call onBrEdrDown", e);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700247 } finally {
Pavlin Radoslavov7ee53be2016-06-09 12:58:07 -0700248 mBluetoothLock.readLock().unlock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800249 }
250 } else if (st == BluetoothAdapter.STATE_ON){
251 // disable without persisting the setting
Jeff Sharkey67609c72016-03-05 14:29:13 -0700252 Slog.d(TAG, "Calling disable");
Nitin Arorad055adb2015-03-02 15:03:51 -0800253 sendDisableMsg();
254 }
Zhihai Xu401202b2012-12-03 11:36:21 -0800255 } else if (mEnableExternal) {
256 // enable without persisting the setting
Jeff Sharkey67609c72016-03-05 14:29:13 -0700257 Slog.d(TAG, "Calling enable");
Zhihai Xu401202b2012-12-03 11:36:21 -0800258 sendEnableMsg(mQuietEnableExternal);
259 }
fredc649fe492012-04-19 01:07:18 -0700260 }
fredc0f420372012-04-12 00:02:00 -0700261 }
262 }
263 };
264
265 BluetoothManagerService(Context context) {
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700266 mHandler = new BluetoothHandler(IoThread.get().getLooper());
Zhihai Xu40874a02012-10-08 17:57:03 -0700267
fredc0f420372012-04-12 00:02:00 -0700268 mContext = context;
Svetoslav Ganovc2ac5bd2016-06-29 17:31:44 -0700269
270 mPermissionReviewRequired = Build.PERMISSIONS_REVIEW_REQUIRED
271 || context.getResources().getBoolean(
272 com.android.internal.R.bool.config_permissionReviewRequired);
273
fredc0f420372012-04-12 00:02:00 -0700274 mBluetooth = null;
Marie Janssen9db28eb2016-01-12 16:05:15 -0800275 mBluetoothBinder = null;
Nitin Arorad055adb2015-03-02 15:03:51 -0800276 mBluetoothGatt = null;
fredc0f420372012-04-12 00:02:00 -0700277 mBinding = false;
278 mUnbinding = false;
Zhihai Xu40874a02012-10-08 17:57:03 -0700279 mEnable = false;
280 mState = BluetoothAdapter.STATE_OFF;
Zhihai Xu401202b2012-12-03 11:36:21 -0800281 mQuietEnableExternal = false;
282 mEnableExternal = false;
fredc0f420372012-04-12 00:02:00 -0700283 mAddress = null;
284 mName = null;
Zhihai Xudd9d17d2013-01-08 17:05:58 -0800285 mErrorRecoveryRetryCounter = 0;
fredc0f420372012-04-12 00:02:00 -0700286 mContentResolver = context.getContentResolver();
Wei Wange4a744b2015-06-11 17:50:29 -0700287 // Observe BLE scan only mode settings change.
288 registerForBleScanModeChange();
fredcd6883532012-04-25 17:46:13 -0700289 mCallbacks = new RemoteCallbackList<IBluetoothManagerCallback>();
290 mStateChangeCallbacks = new RemoteCallbackList<IBluetoothStateChangeCallback>();
Miao Chou658bf2f2015-06-26 17:14:35 -0700291 IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_LOCAL_NAME_CHANGED);
Matthew Xie6fde3092012-07-11 17:10:07 -0700292 registerForAirplaneMode(filter);
Dianne Hackbornd83a0962014-05-02 16:28:33 -0700293 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
Matthew Xie6fde3092012-07-11 17:10:07 -0700294 mContext.registerReceiver(mReceiver, filter);
fredc0f420372012-04-12 00:02:00 -0700295 loadStoredNameAndAddress();
Zhihai Xu401202b2012-12-03 11:36:21 -0800296 if (isBluetoothPersistedStateOn()) {
297 mEnableExternal = true;
fredc0f420372012-04-12 00:02:00 -0700298 }
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200299
300 int sysUiUid = -1;
301 try {
Jeff Sharkeye06b4d12016-01-06 14:51:50 -0700302 sysUiUid = mContext.getPackageManager().getPackageUidAsUser("com.android.systemui",
Jeff Sharkeyc5967e92016-01-07 18:50:29 -0700303 PackageManager.MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM);
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200304 } catch (PackageManager.NameNotFoundException e) {
Joe LaPennaacddf2b2015-09-04 12:52:42 -0700305 // Some platforms, such as wearables do not have a system ui.
Jeff Sharkey67609c72016-03-05 14:29:13 -0700306 Slog.w(TAG, "Unable to resolve SystemUI's UID.", e);
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200307 }
308 mSystemUiUid = sysUiUid;
fredc0f420372012-04-12 00:02:00 -0700309 }
310
fredc649fe492012-04-19 01:07:18 -0700311 /**
312 * Returns true if airplane mode is currently on
313 */
314 private final boolean isAirplaneModeOn() {
Christopher Tatec09cdce2012-09-10 16:50:14 -0700315 return Settings.Global.getInt(mContext.getContentResolver(),
316 Settings.Global.AIRPLANE_MODE_ON, 0) == 1;
fredc649fe492012-04-19 01:07:18 -0700317 }
318
319 /**
320 * Returns true if the Bluetooth saved state is "on"
321 */
322 private final boolean isBluetoothPersistedStateOn() {
Jeff Brownbf6f6f92012-09-25 15:03:20 -0700323 return Settings.Global.getInt(mContentResolver,
Andre Eisenbach8c184312016-09-06 18:03:10 -0700324 Settings.Global.BLUETOOTH_ON, BLUETOOTH_ON_BLUETOOTH) != BLUETOOTH_OFF;
Zhihai Xu401202b2012-12-03 11:36:21 -0800325 }
326
327 /**
328 * Returns true if the Bluetooth saved state is BLUETOOTH_ON_BLUETOOTH
329 */
330 private final boolean isBluetoothPersistedStateOnBluetooth() {
331 return Settings.Global.getInt(mContentResolver,
Andre Eisenbach8c184312016-09-06 18:03:10 -0700332 Settings.Global.BLUETOOTH_ON, BLUETOOTH_ON_BLUETOOTH) == BLUETOOTH_ON_BLUETOOTH;
fredc649fe492012-04-19 01:07:18 -0700333 }
334
335 /**
336 * Save the Bluetooth on/off state
337 *
338 */
Zhihai Xu401202b2012-12-03 11:36:21 -0800339 private void persistBluetoothSetting(int value) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -0700340 Settings.Global.putInt(mContext.getContentResolver(),
341 Settings.Global.BLUETOOTH_ON,
Zhihai Xu401202b2012-12-03 11:36:21 -0800342 value);
fredc649fe492012-04-19 01:07:18 -0700343 }
344
345 /**
346 * Returns true if the Bluetooth Adapter's name and address is
347 * locally cached
348 * @return
349 */
fredc0f420372012-04-12 00:02:00 -0700350 private boolean isNameAndAddressSet() {
351 return mName !=null && mAddress!= null && mName.length()>0 && mAddress.length()>0;
352 }
353
fredc649fe492012-04-19 01:07:18 -0700354 /**
355 * Retrieve the Bluetooth Adapter's name and address and save it in
356 * in the local cache
357 */
fredc0f420372012-04-12 00:02:00 -0700358 private void loadStoredNameAndAddress() {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700359 if (DBG) Slog.d(TAG, "Loading stored name and address");
Zhihai Xud31c3222012-10-31 16:08:57 -0700360 if (mContext.getResources().getBoolean
361 (com.android.internal.R.bool.config_bluetooth_address_validation) &&
362 Settings.Secure.getInt(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDR_VALID, 0) == 0) {
363 // if the valid flag is not set, don't load the address and name
Jeff Sharkey67609c72016-03-05 14:29:13 -0700364 if (DBG) Slog.d(TAG, "invalid bluetooth name and address stored");
Zhihai Xud31c3222012-10-31 16:08:57 -0700365 return;
366 }
fredc0f420372012-04-12 00:02:00 -0700367 mName = Settings.Secure.getString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_NAME);
368 mAddress = Settings.Secure.getString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDRESS);
Jeff Sharkey67609c72016-03-05 14:29:13 -0700369 if (DBG) Slog.d(TAG, "Stored bluetooth Name=" + mName + ",Address=" + mAddress);
fredc0f420372012-04-12 00:02:00 -0700370 }
371
fredc649fe492012-04-19 01:07:18 -0700372 /**
373 * Save the Bluetooth name and address in the persistent store.
374 * Only non-null values will be saved.
375 * @param name
376 * @param address
377 */
fredc0f420372012-04-12 00:02:00 -0700378 private void storeNameAndAddress(String name, String address) {
379 if (name != null) {
380 Settings.Secure.putString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_NAME, name);
fredc0f420372012-04-12 00:02:00 -0700381 mName = name;
Jeff Sharkey67609c72016-03-05 14:29:13 -0700382 if (DBG) Slog.d(TAG,"Stored Bluetooth name: " +
fredc649fe492012-04-19 01:07:18 -0700383 Settings.Secure.getString(mContentResolver,SECURE_SETTINGS_BLUETOOTH_NAME));
fredc0f420372012-04-12 00:02:00 -0700384 }
385
386 if (address != null) {
387 Settings.Secure.putString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDRESS, address);
fredc0f420372012-04-12 00:02:00 -0700388 mAddress=address;
Jeff Sharkey67609c72016-03-05 14:29:13 -0700389 if (DBG) Slog.d(TAG,"Stored Bluetoothaddress: " +
fredc649fe492012-04-19 01:07:18 -0700390 Settings.Secure.getString(mContentResolver,SECURE_SETTINGS_BLUETOOTH_ADDRESS));
fredc0f420372012-04-12 00:02:00 -0700391 }
Zhihai Xud31c3222012-10-31 16:08:57 -0700392
393 if ((name != null) && (address != null)) {
394 Settings.Secure.putInt(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDR_VALID, 1);
395 }
fredc0f420372012-04-12 00:02:00 -0700396 }
397
398 public IBluetooth registerAdapter(IBluetoothManagerCallback callback){
Natalie Silvanovich55db6462014-05-01 16:12:23 -0700399 if (callback == null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700400 Slog.w(TAG, "Callback is null in registerAdapter");
Natalie Silvanovich55db6462014-05-01 16:12:23 -0700401 return null;
402 }
fredc0f420372012-04-12 00:02:00 -0700403 Message msg = mHandler.obtainMessage(MESSAGE_REGISTER_ADAPTER);
404 msg.obj = callback;
405 mHandler.sendMessage(msg);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700406
407 return mBluetooth;
fredc0f420372012-04-12 00:02:00 -0700408 }
409
410 public void unregisterAdapter(IBluetoothManagerCallback callback) {
Natalie Silvanovich55db6462014-05-01 16:12:23 -0700411 if (callback == null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700412 Slog.w(TAG, "Callback is null in unregisterAdapter");
Natalie Silvanovich55db6462014-05-01 16:12:23 -0700413 return;
414 }
fredc0f420372012-04-12 00:02:00 -0700415 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
416 "Need BLUETOOTH permission");
417 Message msg = mHandler.obtainMessage(MESSAGE_UNREGISTER_ADAPTER);
418 msg.obj = callback;
419 mHandler.sendMessage(msg);
420 }
421
422 public void registerStateChangeCallback(IBluetoothStateChangeCallback callback) {
423 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
424 "Need BLUETOOTH permission");
425 Message msg = mHandler.obtainMessage(MESSAGE_REGISTER_STATE_CHANGE_CALLBACK);
426 msg.obj = callback;
427 mHandler.sendMessage(msg);
428 }
429
430 public void unregisterStateChangeCallback(IBluetoothStateChangeCallback callback) {
431 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
432 "Need BLUETOOTH permission");
433 Message msg = mHandler.obtainMessage(MESSAGE_UNREGISTER_STATE_CHANGE_CALLBACK);
434 msg.obj = callback;
435 mHandler.sendMessage(msg);
436 }
437
438 public boolean isEnabled() {
Zhihai Xu6eb76522012-11-29 15:41:04 -0800439 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
440 (!checkIfCallerIsForegroundUser())) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700441 Slog.w(TAG,"isEnabled(): not allowed for non-active and non system user");
Zhihai Xu40874a02012-10-08 17:57:03 -0700442 return false;
443 }
444
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700445 try {
446 mBluetoothLock.readLock().lock();
447 if (mBluetooth != null) return mBluetooth.isEnabled();
448 } catch (RemoteException e) {
449 Slog.e(TAG, "isEnabled()", e);
450 } finally {
451 mBluetoothLock.readLock().unlock();
fredc0f420372012-04-12 00:02:00 -0700452 }
453 return false;
454 }
455
Christine Hallstrom995c90a2016-05-25 15:49:08 -0700456 public int getState() {
457 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
458 (!checkIfCallerIsForegroundUser())) {
459 Slog.w(TAG, "getState(): not allowed for non-active and non system user");
460 return BluetoothAdapter.STATE_OFF;
461 }
462
463 try {
464 mBluetoothLock.readLock().lock();
465 if (mBluetooth != null) return mBluetooth.getState();
466 } catch (RemoteException e) {
467 Slog.e(TAG, "getState()", e);
468 } finally {
469 mBluetoothLock.readLock().unlock();
470 }
471 return BluetoothAdapter.STATE_OFF;
472 }
473
Nitin Arorad055adb2015-03-02 15:03:51 -0800474 class ClientDeathRecipient implements IBinder.DeathRecipient {
475 public void binderDied() {
Marie Janssen6a383a72016-10-25 10:47:51 -0700476 if (DBG) Slog.d(TAG, "Binder is dead - unregister Ble App");
Marie Janssen2977c3e2016-11-09 12:01:24 -0800477 if (isBleAppPresent()) {
478 // Nothing to do, another app is here.
479 return;
480 }
481 if (DBG) Slog.d(TAG, "Disabling LE only mode after application crash");
482 try {
483 mBluetoothLock.readLock().lock();
484 if (mBluetooth != null &&
485 mBluetooth.getState() == BluetoothAdapter.STATE_BLE_ON) {
486 mEnable = false;
487 mBluetooth.onBrEdrDown();
Nitin Arorad055adb2015-03-02 15:03:51 -0800488 }
Marie Janssen2977c3e2016-11-09 12:01:24 -0800489 } catch (RemoteException e) {
490 Slog.e(TAG,"Unable to call onBrEdrDown", e);
491 } finally {
492 mBluetoothLock.readLock().unlock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800493 }
494 }
495 }
496
497 /** Internal death rec list */
Marie Janssen2977c3e2016-11-09 12:01:24 -0800498 Map<IBinder, ClientDeathRecipient> mBleApps = new ConcurrentHashMap<IBinder, ClientDeathRecipient>();
Nitin Arorad055adb2015-03-02 15:03:51 -0800499
Wei Wang67d84162015-04-26 17:04:29 -0700500 @Override
501 public boolean isBleScanAlwaysAvailable() {
Marie Janssen6a383a72016-10-25 10:47:51 -0700502 if (isAirplaneModeOn() && !mEnable) {
503 return false;
504 }
Wei Wang67d84162015-04-26 17:04:29 -0700505 try {
506 return (Settings.Global.getInt(mContentResolver,
507 Settings.Global.BLE_SCAN_ALWAYS_AVAILABLE)) != 0;
508 } catch (SettingNotFoundException e) {
509 }
510 return false;
511 }
512
Wei Wange4a744b2015-06-11 17:50:29 -0700513 // Monitor change of BLE scan only mode settings.
514 private void registerForBleScanModeChange() {
515 ContentObserver contentObserver = new ContentObserver(null) {
516 @Override
517 public void onChange(boolean selfChange) {
Marie Janssen2977c3e2016-11-09 12:01:24 -0800518 if (isBleScanAlwaysAvailable()) {
519 // Nothing to do
520 return;
521 }
522 // BLE scan is not available.
523 disableBleScanMode();
524 clearBleApps();
525 try {
526 mBluetoothLock.readLock().lock();
527 if (mBluetooth != null) mBluetooth.onBrEdrDown();
528 } catch (RemoteException e) {
529 Slog.e(TAG, "error when disabling bluetooth", e);
530 } finally {
531 mBluetoothLock.readLock().unlock();
Wei Wange4a744b2015-06-11 17:50:29 -0700532 }
533 }
534 };
535
536 mContentResolver.registerContentObserver(
537 Settings.Global.getUriFor(Settings.Global.BLE_SCAN_ALWAYS_AVAILABLE),
538 false, contentObserver);
539 }
540
541 // Disable ble scan only mode.
542 private void disableBleScanMode() {
543 try {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700544 mBluetoothLock.writeLock().lock();
Wei Wange4a744b2015-06-11 17:50:29 -0700545 if (mBluetooth != null && (mBluetooth.getState() != BluetoothAdapter.STATE_ON)) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700546 if (DBG) Slog.d(TAG, "Reseting the mEnable flag for clean disable");
Wei Wange4a744b2015-06-11 17:50:29 -0700547 mEnable = false;
548 }
549 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700550 Slog.e(TAG, "getState()", e);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700551 } finally {
552 mBluetoothLock.writeLock().unlock();
Wei Wange4a744b2015-06-11 17:50:29 -0700553 }
554 }
555
Nitin Arorad055adb2015-03-02 15:03:51 -0800556 public int updateBleAppCount(IBinder token, boolean enable) {
557 if (enable) {
558 ClientDeathRecipient r = mBleApps.get(token);
559 if (r == null) {
560 ClientDeathRecipient deathRec = new ClientDeathRecipient();
561 try {
562 token.linkToDeath(deathRec, 0);
563 } catch (RemoteException ex) {
564 throw new IllegalArgumentException("Wake lock is already dead.");
565 }
566 mBleApps.put(token, deathRec);
Jeff Sharkey67609c72016-03-05 14:29:13 -0700567 if (DBG) Slog.d(TAG, "Registered for death Notification");
Nitin Arorad055adb2015-03-02 15:03:51 -0800568 }
569
570 } else {
571 ClientDeathRecipient r = mBleApps.get(token);
572 if (r != null) {
Wei Wange4a744b2015-06-11 17:50:29 -0700573 // Unregister death recipient as the app goes away.
574 token.unlinkToDeath(r, 0);
Nitin Arorad055adb2015-03-02 15:03:51 -0800575 mBleApps.remove(token);
Jeff Sharkey67609c72016-03-05 14:29:13 -0700576 if (DBG) Slog.d(TAG, "Unregistered for death Notification");
Nitin Arorad055adb2015-03-02 15:03:51 -0800577 }
578 }
Marie Janssen2977c3e2016-11-09 12:01:24 -0800579 int appCount = mBleApps.size();
580 if (DBG) Slog.d(TAG, appCount + " registered Ble Apps");
581 if (appCount == 0 && mEnable) {
Wei Wange4a744b2015-06-11 17:50:29 -0700582 disableBleScanMode();
Nitin Arorad055adb2015-03-02 15:03:51 -0800583 }
Marie Janssen2977c3e2016-11-09 12:01:24 -0800584 return appCount;
Nitin Arorad055adb2015-03-02 15:03:51 -0800585 }
586
Wei Wange4a744b2015-06-11 17:50:29 -0700587 // Clear all apps using BLE scan only mode.
588 private void clearBleApps() {
Marie Janssen2977c3e2016-11-09 12:01:24 -0800589 mBleApps.clear();
Wei Wange4a744b2015-06-11 17:50:29 -0700590 }
591
Nitin Arorad055adb2015-03-02 15:03:51 -0800592 /** @hide*/
593 public boolean isBleAppPresent() {
Marie Janssen2977c3e2016-11-09 12:01:24 -0800594 if (DBG) Slog.d(TAG, "isBleAppPresent() count: " + mBleApps.size());
595 return mBleApps.size() > 0;
Nitin Arorad055adb2015-03-02 15:03:51 -0800596 }
597
598 /**
599 * Action taken when GattService is turned off
600 */
601 private void onBluetoothGattServiceUp() {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700602 if (DBG) Slog.d(TAG,"BluetoothGatt Service is Up");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700603 try {
604 mBluetoothLock.readLock().lock();
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700605 if (isBleAppPresent() == false && mBluetooth != null
606 && mBluetooth.getState() == BluetoothAdapter.STATE_BLE_ON) {
Nitin Arorad055adb2015-03-02 15:03:51 -0800607 mBluetooth.onLeServiceUp();
608
609 // waive WRITE_SECURE_SETTINGS permission check
610 long callingIdentity = Binder.clearCallingIdentity();
611 persistBluetoothSetting(BLUETOOTH_ON_BLUETOOTH);
612 Binder.restoreCallingIdentity(callingIdentity);
613 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700614 } catch (RemoteException e) {
615 Slog.e(TAG,"Unable to call onServiceUp", e);
616 } finally {
617 mBluetoothLock.readLock().unlock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800618 }
619 }
620
621 /**
622 * Inform BluetoothAdapter instances that BREDR part is down
623 * and turn off all service and stack if no LE app needs it
624 */
625 private void sendBrEdrDownCallback() {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700626 if (DBG) Slog.d(TAG,"Calling sendBrEdrDownCallback callbacks");
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700627
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700628 if (mBluetooth == null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700629 Slog.w(TAG, "Bluetooth handle is null");
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700630 return;
631 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800632
633 if (isBleAppPresent() == false) {
634 try {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700635 mBluetoothLock.readLock().lock();
636 if (mBluetooth != null) mBluetooth.onBrEdrDown();
637 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700638 Slog.e(TAG, "Call to onBrEdrDown() failed.", e);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700639 } finally {
640 mBluetoothLock.readLock().unlock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800641 }
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700642 } else {
643 // Need to stay at BLE ON. Disconnect all Gatt connections
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700644 try {
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700645 mBluetoothGatt.unregAll();
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700646 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700647 Slog.e(TAG, "Unable to disconnect all apps.", e);
Nitin Arorad055adb2015-03-02 15:03:51 -0800648 }
649 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800650 }
651
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700652 public boolean enableNoAutoConnect()
653 {
Lenka Trochtova13a05192016-12-02 12:19:39 +0100654 if (isBluetoothDisallowed()) {
655 if (DBG) {
656 Slog.d(TAG, "enableNoAutoConnect(): not enabling - bluetooth disallowed");
657 }
658 return false;
659 }
660
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700661 mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
662 "Need BLUETOOTH ADMIN permission");
Zhihai Xu40874a02012-10-08 17:57:03 -0700663
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700664 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700665 Slog.d(TAG,"enableNoAutoConnect(): mBluetooth =" + mBluetooth +
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700666 " mBinding = " + mBinding);
667 }
Martijn Coenen8385c5a2012-11-29 10:14:16 -0800668 int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
669
670 if (callingAppId != Process.NFC_UID) {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700671 throw new SecurityException("no permission to enable Bluetooth quietly");
672 }
Martijn Coenen8385c5a2012-11-29 10:14:16 -0800673
Zhihai Xu401202b2012-12-03 11:36:21 -0800674 synchronized(mReceiver) {
675 mQuietEnableExternal = true;
676 mEnableExternal = true;
677 sendEnableMsg(true);
678 }
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700679 return true;
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700680 }
Ajay Panicker4bb48302016-03-31 14:14:27 -0700681
Svetoslav Ganovc2ac5bd2016-06-29 17:31:44 -0700682 public boolean enable(String packageName) throws RemoteException {
Lenka Trochtova13a05192016-12-02 12:19:39 +0100683 if (isBluetoothDisallowed()) {
684 if (DBG) {
685 Slog.d(TAG,"enable(): not enabling - bluetooth disallowed");
686 }
687 return false;
688 }
689
Svetoslav Ganovc2ac5bd2016-06-29 17:31:44 -0700690 final int callingUid = Binder.getCallingUid();
691 final boolean callerSystem = UserHandle.getAppId(callingUid) == Process.SYSTEM_UID;
692
693 if (!callerSystem) {
694 if (!checkIfCallerIsForegroundUser()) {
695 Slog.w(TAG, "enable(): not allowed for non-active and non system user");
696 return false;
697 }
698
699 mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
700 "Need BLUETOOTH ADMIN permission");
701
702 if (!isEnabled() && mPermissionReviewRequired
703 && startConsentUiIfNeeded(packageName, callingUid,
704 BluetoothAdapter.ACTION_REQUEST_ENABLE)) {
705 return false;
706 }
fredcf2458862012-04-16 15:18:27 -0700707 }
708
Zhihai Xu401202b2012-12-03 11:36:21 -0800709 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700710 Slog.d(TAG,"enable(): mBluetooth =" + mBluetooth +
Sanket Agarwal090bf552016-04-21 14:10:55 -0700711 " mBinding = " + mBinding + " mState = " + mState);
712 }
Zhihai Xu401202b2012-12-03 11:36:21 -0800713
714 synchronized(mReceiver) {
715 mQuietEnableExternal = false;
716 mEnableExternal = true;
717 // waive WRITE_SECURE_SETTINGS permission check
Zhihai Xu401202b2012-12-03 11:36:21 -0800718 sendEnableMsg(false);
719 }
Jeff Sharkey67609c72016-03-05 14:29:13 -0700720 if (DBG) Slog.d(TAG, "enable returning");
Zhihai Xu401202b2012-12-03 11:36:21 -0800721 return true;
fredc0f420372012-04-12 00:02:00 -0700722 }
723
Svetoslav Ganovc2ac5bd2016-06-29 17:31:44 -0700724 public boolean disable(String packageName, boolean persist) throws RemoteException {
725 final int callingUid = Binder.getCallingUid();
726 final boolean callerSystem = UserHandle.getAppId(callingUid) == Process.SYSTEM_UID;
Zhihai Xu40874a02012-10-08 17:57:03 -0700727
Svetoslav Ganovc2ac5bd2016-06-29 17:31:44 -0700728 if (!callerSystem) {
729 if (!checkIfCallerIsForegroundUser()) {
730 Slog.w(TAG, "disable(): not allowed for non-active and non system user");
731 return false;
732 }
733
734 mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
735 "Need BLUETOOTH ADMIN permission");
736
737 if (isEnabled() && mPermissionReviewRequired
738 && startConsentUiIfNeeded(packageName, callingUid,
739 BluetoothAdapter.ACTION_REQUEST_DISABLE)) {
740 return false;
741 }
Zhihai Xu40874a02012-10-08 17:57:03 -0700742 }
743
fredcf2458862012-04-16 15:18:27 -0700744 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700745 Slog.d(TAG,"disable(): mBluetooth = " + mBluetooth +
Matthew Xiecdce0b92012-07-12 19:06:15 -0700746 " mBinding = " + mBinding);
747 }
fredcf2458862012-04-16 15:18:27 -0700748
Zhihai Xu401202b2012-12-03 11:36:21 -0800749 synchronized(mReceiver) {
750 if (persist) {
751 // waive WRITE_SECURE_SETTINGS permission check
752 long callingIdentity = Binder.clearCallingIdentity();
753 persistBluetoothSetting(BLUETOOTH_OFF);
754 Binder.restoreCallingIdentity(callingIdentity);
755 }
756 mEnableExternal = false;
757 sendDisableMsg();
758 }
fredc0f420372012-04-12 00:02:00 -0700759 return true;
760 }
761
Svetoslav Ganovc2ac5bd2016-06-29 17:31:44 -0700762 private boolean startConsentUiIfNeeded(String packageName,
763 int callingUid, String intentAction) throws RemoteException {
764 try {
765 // Validate the package only if we are going to use it
766 ApplicationInfo applicationInfo = mContext.getPackageManager()
767 .getApplicationInfoAsUser(packageName,
768 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
769 UserHandle.getUserId(callingUid));
770 if (applicationInfo.uid != callingUid) {
771 throw new SecurityException("Package " + callingUid
772 + " not in uid " + callingUid);
773 }
774
775 // Legacy apps in permission review mode trigger a user prompt
776 if (applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
777 Intent intent = new Intent(intentAction);
778 mContext.startActivity(intent);
779 return true;
780 }
781 } catch (PackageManager.NameNotFoundException e) {
782 throw new RemoteException(e.getMessage());
783 }
784 return false;
785 }
786
fredc649fe492012-04-19 01:07:18 -0700787 public void unbindAndFinish() {
fredcf2458862012-04-16 15:18:27 -0700788 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700789 Slog.d(TAG,"unbindAndFinish(): " + mBluetooth +
Matthew Xiecdce0b92012-07-12 19:06:15 -0700790 " mBinding = " + mBinding);
fredcf2458862012-04-16 15:18:27 -0700791 }
792
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700793 try {
794 mBluetoothLock.writeLock().lock();
fredc0f420372012-04-12 00:02:00 -0700795 if (mUnbinding) return;
796 mUnbinding = true;
Pavlin Radoslavove47ec142016-06-01 22:25:18 -0700797 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
Pavlin Radoslavov74f60c02016-09-21 17:28:11 -0700798 mHandler.removeMessages(MESSAGE_BIND_PROFILE_SERVICE);
Zhihai Xu40874a02012-10-08 17:57:03 -0700799 if (mBluetooth != null) {
Andre Eisenbach305fdab2015-11-11 21:43:26 -0800800 //Unregister callback object
801 try {
802 mBluetooth.unregisterCallback(mBluetoothCallback);
803 } catch (RemoteException re) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700804 Slog.e(TAG, "Unable to unregister BluetoothCallback",re);
fredcbf072a72012-05-09 16:52:50 -0700805 }
Andre Eisenbach305fdab2015-11-11 21:43:26 -0800806
Jeff Sharkey67609c72016-03-05 14:29:13 -0700807 if (DBG) Slog.d(TAG, "Sending unbind request.");
Marie Janssen9db28eb2016-01-12 16:05:15 -0800808 mBluetoothBinder = null;
fredcd6883532012-04-25 17:46:13 -0700809 mBluetooth = null;
810 //Unbind
fredc0f420372012-04-12 00:02:00 -0700811 mContext.unbindService(mConnection);
fredcd6883532012-04-25 17:46:13 -0700812 mUnbinding = false;
Zhihai Xu40874a02012-10-08 17:57:03 -0700813 mBinding = false;
fredcf2458862012-04-16 15:18:27 -0700814 } else {
815 mUnbinding=false;
fredc0f420372012-04-12 00:02:00 -0700816 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800817 mBluetoothGatt = null;
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700818 } finally {
819 mBluetoothLock.writeLock().unlock();
fredc0f420372012-04-12 00:02:00 -0700820 }
821 }
822
Matthew Xieddf7e472013-03-01 18:41:02 -0800823 public IBluetoothGatt getBluetoothGatt() {
824 // sync protection
825 return mBluetoothGatt;
826 }
827
Benjamin Franze8b98922014-11-12 15:57:54 +0000828 @Override
829 public boolean bindBluetoothProfileService(int bluetoothProfile,
830 IBluetoothProfileServiceConnection proxy) {
831 if (!mEnable) {
832 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700833 Slog.d(TAG, "Trying to bind to profile: " + bluetoothProfile +
Benjamin Franze8b98922014-11-12 15:57:54 +0000834 ", while Bluetooth was disabled");
835 }
836 return false;
837 }
838 synchronized (mProfileServices) {
839 ProfileServiceConnections psc = mProfileServices.get(new Integer(bluetoothProfile));
840 if (psc == null) {
841 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700842 Slog.d(TAG, "Creating new ProfileServiceConnections object for"
Benjamin Franze8b98922014-11-12 15:57:54 +0000843 + " profile: " + bluetoothProfile);
844 }
Benjamin Franz5b614592014-12-09 18:58:45 +0000845
846 if (bluetoothProfile != BluetoothProfile.HEADSET) return false;
847
848 Intent intent = new Intent(IBluetoothHeadset.class.getName());
Benjamin Franze8b98922014-11-12 15:57:54 +0000849 psc = new ProfileServiceConnections(intent);
Benjamin Franz5b614592014-12-09 18:58:45 +0000850 if (!psc.bindService()) return false;
851
Benjamin Franze8b98922014-11-12 15:57:54 +0000852 mProfileServices.put(new Integer(bluetoothProfile), psc);
Benjamin Franze8b98922014-11-12 15:57:54 +0000853 }
854 }
855
856 // Introducing a delay to give the client app time to prepare
857 Message addProxyMsg = mHandler.obtainMessage(MESSAGE_ADD_PROXY_DELAYED);
858 addProxyMsg.arg1 = bluetoothProfile;
859 addProxyMsg.obj = proxy;
860 mHandler.sendMessageDelayed(addProxyMsg, ADD_PROXY_DELAY_MS);
861 return true;
862 }
863
864 @Override
865 public void unbindBluetoothProfileService(int bluetoothProfile,
866 IBluetoothProfileServiceConnection proxy) {
867 synchronized (mProfileServices) {
868 ProfileServiceConnections psc = mProfileServices.get(new Integer(bluetoothProfile));
869 if (psc == null) {
870 return;
871 }
872 psc.removeProxy(proxy);
873 }
874 }
875
876 private void unbindAllBluetoothProfileServices() {
877 synchronized (mProfileServices) {
878 for (Integer i : mProfileServices.keySet()) {
879 ProfileServiceConnections psc = mProfileServices.get(i);
Benjamin Franz5b614592014-12-09 18:58:45 +0000880 try {
881 mContext.unbindService(psc);
882 } catch (IllegalArgumentException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700883 Slog.e(TAG, "Unable to unbind service with intent: " + psc.mIntent, e);
Benjamin Franz5b614592014-12-09 18:58:45 +0000884 }
Benjamin Franze8b98922014-11-12 15:57:54 +0000885 psc.removeAllProxies();
886 }
887 mProfileServices.clear();
888 }
889 }
890
891 /**
Miao Chou658bf2f2015-06-26 17:14:35 -0700892 * Send enable message and set adapter name and address. Called when the boot phase becomes
893 * PHASE_SYSTEM_SERVICES_READY.
894 */
895 public void handleOnBootPhase() {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700896 if (DBG) Slog.d(TAG, "Bluetooth boot completed");
Lenka Trochtova13a05192016-12-02 12:19:39 +0100897 UserManagerInternal userManagerInternal =
898 LocalServices.getService(UserManagerInternal.class);
899 userManagerInternal.addUserRestrictionsListener(mUserRestrictionsListener);
900 if (isBluetoothDisallowed()) {
901 return;
902 }
Miao Chou658bf2f2015-06-26 17:14:35 -0700903 if (mEnableExternal && isBluetoothPersistedStateOnBluetooth()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700904 if (DBG) Slog.d(TAG, "Auto-enabling Bluetooth.");
Miao Chou658bf2f2015-06-26 17:14:35 -0700905 sendEnableMsg(mQuietEnableExternal);
Ajay Panickerbf796d82016-03-11 13:47:20 -0800906 } else if (!isNameAndAddressSet()) {
907 if (DBG) Slog.d(TAG, "Getting adapter name and address");
Ajay Panicker4bb48302016-03-31 14:14:27 -0700908 Message getMsg = mHandler.obtainMessage(MESSAGE_GET_NAME_AND_ADDRESS);
909 mHandler.sendMessage(getMsg);
Miao Chou658bf2f2015-06-26 17:14:35 -0700910 }
Miao Chou658bf2f2015-06-26 17:14:35 -0700911 }
912
913 /**
914 * Called when switching to a different foreground user.
915 */
916 public void handleOnSwitchUser(int userHandle) {
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -0700917 if (DBG) Slog.d(TAG, "User " + userHandle + " switched");
918 mHandler.obtainMessage(MESSAGE_USER_SWITCHED, userHandle, 0).sendToTarget();
919 }
920
921 /**
922 * Called when user is unlocked.
923 */
924 public void handleOnUnlockUser(int userHandle) {
925 if (DBG) Slog.d(TAG, "User " + userHandle + " unlocked");
926 mHandler.obtainMessage(MESSAGE_USER_UNLOCKED, userHandle, 0).sendToTarget();
Miao Chou658bf2f2015-06-26 17:14:35 -0700927 }
928
929 /**
Benjamin Franze8b98922014-11-12 15:57:54 +0000930 * This class manages the clients connected to a given ProfileService
931 * and maintains the connection with that service.
932 */
933 final private class ProfileServiceConnections implements ServiceConnection,
934 IBinder.DeathRecipient {
935 final RemoteCallbackList<IBluetoothProfileServiceConnection> mProxies =
936 new RemoteCallbackList <IBluetoothProfileServiceConnection>();
937 IBinder mService;
938 ComponentName mClassName;
939 Intent mIntent;
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700940 boolean mInvokingProxyCallbacks = false;
Benjamin Franze8b98922014-11-12 15:57:54 +0000941
942 ProfileServiceConnections(Intent intent) {
943 mService = null;
944 mClassName = null;
945 mIntent = intent;
946 }
947
Benjamin Franz5b614592014-12-09 18:58:45 +0000948 private boolean bindService() {
949 if (mIntent != null && mService == null &&
950 doBind(mIntent, this, 0, UserHandle.CURRENT_OR_SELF)) {
Benjamin Franze8b98922014-11-12 15:57:54 +0000951 Message msg = mHandler.obtainMessage(MESSAGE_BIND_PROFILE_SERVICE);
952 msg.obj = this;
953 mHandler.sendMessageDelayed(msg, TIMEOUT_BIND_MS);
Benjamin Franz5b614592014-12-09 18:58:45 +0000954 return true;
Benjamin Franze8b98922014-11-12 15:57:54 +0000955 }
Jeff Sharkey67609c72016-03-05 14:29:13 -0700956 Slog.w(TAG, "Unable to bind with intent: " + mIntent);
Benjamin Franz5b614592014-12-09 18:58:45 +0000957 return false;
Benjamin Franze8b98922014-11-12 15:57:54 +0000958 }
959
960 private void addProxy(IBluetoothProfileServiceConnection proxy) {
961 mProxies.register(proxy);
962 if (mService != null) {
963 try{
964 proxy.onServiceConnected(mClassName, mService);
965 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700966 Slog.e(TAG, "Unable to connect to proxy", e);
Benjamin Franze8b98922014-11-12 15:57:54 +0000967 }
968 } else {
969 if (!mHandler.hasMessages(MESSAGE_BIND_PROFILE_SERVICE, this)) {
970 Message msg = mHandler.obtainMessage(MESSAGE_BIND_PROFILE_SERVICE);
971 msg.obj = this;
972 mHandler.sendMessage(msg);
973 }
974 }
975 }
976
977 private void removeProxy(IBluetoothProfileServiceConnection proxy) {
978 if (proxy != null) {
979 if (mProxies.unregister(proxy)) {
980 try {
981 proxy.onServiceDisconnected(mClassName);
982 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700983 Slog.e(TAG, "Unable to disconnect proxy", e);
Benjamin Franze8b98922014-11-12 15:57:54 +0000984 }
985 }
986 } else {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700987 Slog.w(TAG, "Trying to remove a null proxy");
Benjamin Franze8b98922014-11-12 15:57:54 +0000988 }
989 }
990
991 private void removeAllProxies() {
992 onServiceDisconnected(mClassName);
993 mProxies.kill();
994 }
995
996 @Override
997 public void onServiceConnected(ComponentName className, IBinder service) {
998 // remove timeout message
999 mHandler.removeMessages(MESSAGE_BIND_PROFILE_SERVICE, this);
1000 mService = service;
1001 mClassName = className;
1002 try {
1003 mService.linkToDeath(this, 0);
1004 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001005 Slog.e(TAG, "Unable to linkToDeath", e);
Benjamin Franze8b98922014-11-12 15:57:54 +00001006 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001007
1008 if (mInvokingProxyCallbacks) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001009 Slog.e(TAG, "Proxy callbacks already in progress.");
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001010 return;
Benjamin Franze8b98922014-11-12 15:57:54 +00001011 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001012 mInvokingProxyCallbacks = true;
1013
1014 final int n = mProxies.beginBroadcast();
1015 try {
1016 for (int i = 0; i < n; i++) {
1017 try {
1018 mProxies.getBroadcastItem(i).onServiceConnected(className, service);
1019 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001020 Slog.e(TAG, "Unable to connect to proxy", e);
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001021 }
1022 }
1023 } finally {
1024 mProxies.finishBroadcast();
1025 mInvokingProxyCallbacks = false;
1026 }
Benjamin Franze8b98922014-11-12 15:57:54 +00001027 }
1028
1029 @Override
1030 public void onServiceDisconnected(ComponentName className) {
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001031 if (mService == null) return;
Benjamin Franze8b98922014-11-12 15:57:54 +00001032 mService.unlinkToDeath(this, 0);
1033 mService = null;
1034 mClassName = null;
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001035
1036 if (mInvokingProxyCallbacks) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001037 Slog.e(TAG, "Proxy callbacks already in progress.");
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001038 return;
Benjamin Franze8b98922014-11-12 15:57:54 +00001039 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001040 mInvokingProxyCallbacks = true;
1041
1042 final int n = mProxies.beginBroadcast();
1043 try {
1044 for (int i = 0; i < n; i++) {
1045 try {
1046 mProxies.getBroadcastItem(i).onServiceDisconnected(className);
1047 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001048 Slog.e(TAG, "Unable to disconnect from proxy", e);
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001049 }
1050 }
1051 } finally {
1052 mProxies.finishBroadcast();
1053 mInvokingProxyCallbacks = false;
1054 }
Benjamin Franze8b98922014-11-12 15:57:54 +00001055 }
1056
1057 @Override
1058 public void binderDied() {
1059 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001060 Slog.w(TAG, "Profile service for profile: " + mClassName
Benjamin Franze8b98922014-11-12 15:57:54 +00001061 + " died.");
1062 }
1063 onServiceDisconnected(mClassName);
1064 // Trigger rebind
1065 Message msg = mHandler.obtainMessage(MESSAGE_BIND_PROFILE_SERVICE);
1066 msg.obj = this;
1067 mHandler.sendMessageDelayed(msg, TIMEOUT_BIND_MS);
1068 }
1069 }
1070
fredcbf072a72012-05-09 16:52:50 -07001071 private void sendBluetoothStateCallback(boolean isUp) {
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001072 try {
1073 int n = mStateChangeCallbacks.beginBroadcast();
Jeff Sharkey67609c72016-03-05 14:29:13 -07001074 if (DBG) Slog.d(TAG,"Broadcasting onBluetoothStateChange("+isUp+") to " + n + " receivers.");
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001075 for (int i=0; i <n;i++) {
1076 try {
1077 mStateChangeCallbacks.getBroadcastItem(i).onBluetoothStateChange(isUp);
1078 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001079 Slog.e(TAG, "Unable to call onBluetoothStateChange() on callback #" + i , e);
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001080 }
fredcbf072a72012-05-09 16:52:50 -07001081 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001082 } finally {
1083 mStateChangeCallbacks.finishBroadcast();
fredcbf072a72012-05-09 16:52:50 -07001084 }
fredcbf072a72012-05-09 16:52:50 -07001085 }
1086
1087 /**
Zhihai Xu40874a02012-10-08 17:57:03 -07001088 * Inform BluetoothAdapter instances that Adapter service is up
1089 */
1090 private void sendBluetoothServiceUpCallback() {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001091 if (DBG) Slog.d(TAG,"Calling onBluetoothServiceUp callbacks");
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001092 try {
1093 int n = mCallbacks.beginBroadcast();
Jeff Sharkey67609c72016-03-05 14:29:13 -07001094 Slog.d(TAG,"Broadcasting onBluetoothServiceUp() to " + n + " receivers.");
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001095 for (int i=0; i <n;i++) {
1096 try {
1097 mCallbacks.getBroadcastItem(i).onBluetoothServiceUp(mBluetooth);
1098 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001099 Slog.e(TAG, "Unable to call onBluetoothServiceUp() on callback #" + i, e);
Zhihai Xu40874a02012-10-08 17:57:03 -07001100 }
1101 }
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001102 } finally {
1103 mCallbacks.finishBroadcast();
Zhihai Xu40874a02012-10-08 17:57:03 -07001104 }
1105 }
1106 /**
fredcbf072a72012-05-09 16:52:50 -07001107 * Inform BluetoothAdapter instances that Adapter service is down
1108 */
1109 private void sendBluetoothServiceDownCallback() {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001110 if (DBG) Slog.d(TAG,"Calling onBluetoothServiceDown callbacks");
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001111 try {
1112 int n = mCallbacks.beginBroadcast();
Jeff Sharkey67609c72016-03-05 14:29:13 -07001113 Slog.d(TAG,"Broadcasting onBluetoothServiceDown() to " + n + " receivers.");
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001114 for (int i=0; i <n;i++) {
1115 try {
1116 mCallbacks.getBroadcastItem(i).onBluetoothServiceDown();
1117 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001118 Slog.e(TAG, "Unable to call onBluetoothServiceDown() on callback #" + i, e);
fredcd6883532012-04-25 17:46:13 -07001119 }
1120 }
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001121 } finally {
1122 mCallbacks.finishBroadcast();
fredcd6883532012-04-25 17:46:13 -07001123 }
1124 }
Svet Ganov408abf72015-05-12 19:13:36 -07001125
fredc0f420372012-04-12 00:02:00 -07001126 public String getAddress() {
Matthew Xieaf5ddbf2012-12-04 10:47:43 -08001127 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
Svet Ganov408abf72015-05-12 19:13:36 -07001128 "Need BLUETOOTH permission");
Zhihai Xu40874a02012-10-08 17:57:03 -07001129
Zhihai Xu6eb76522012-11-29 15:41:04 -08001130 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
Svet Ganov408abf72015-05-12 19:13:36 -07001131 (!checkIfCallerIsForegroundUser())) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001132 Slog.w(TAG,"getAddress(): not allowed for non-active and non system user");
Zhihai Xu6eb76522012-11-29 15:41:04 -08001133 return null;
Zhihai Xu40874a02012-10-08 17:57:03 -07001134 }
1135
Svet Ganov408abf72015-05-12 19:13:36 -07001136 if (mContext.checkCallingOrSelfPermission(Manifest.permission.LOCAL_MAC_ADDRESS)
1137 != PackageManager.PERMISSION_GRANTED) {
1138 return BluetoothAdapter.DEFAULT_MAC_ADDRESS;
1139 }
1140
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001141 try {
1142 mBluetoothLock.readLock().lock();
1143 if (mBluetooth != null) return mBluetooth.getAddress();
1144 } catch (RemoteException e) {
1145 Slog.e(TAG, "getAddress(): Unable to retrieve address remotely. Returning cached address", e);
1146 } finally {
1147 mBluetoothLock.readLock().unlock();
fredc116d1d462012-04-20 14:47:08 -07001148 }
Ajay Panickerbf796d82016-03-11 13:47:20 -08001149
Matthew Xiecdce0b92012-07-12 19:06:15 -07001150 // mAddress is accessed from outside.
1151 // It is alright without a lock. Here, bluetooth is off, no other thread is
1152 // changing mAddress
fredc0f420372012-04-12 00:02:00 -07001153 return mAddress;
1154 }
fredc649fe492012-04-19 01:07:18 -07001155
fredc0f420372012-04-12 00:02:00 -07001156 public String getName() {
Matthew Xieaf5ddbf2012-12-04 10:47:43 -08001157 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
1158 "Need BLUETOOTH permission");
Zhihai Xu40874a02012-10-08 17:57:03 -07001159
Zhihai Xu6eb76522012-11-29 15:41:04 -08001160 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
1161 (!checkIfCallerIsForegroundUser())) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001162 Slog.w(TAG,"getName(): not allowed for non-active and non system user");
Zhihai Xu6eb76522012-11-29 15:41:04 -08001163 return null;
Zhihai Xu40874a02012-10-08 17:57:03 -07001164 }
1165
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001166 try {
1167 mBluetoothLock.readLock().lock();
1168 if (mBluetooth != null) return mBluetooth.getName();
1169 } catch (RemoteException e) {
1170 Slog.e(TAG, "getName(): Unable to retrieve name remotely. Returning cached name", e);
1171 } finally {
1172 mBluetoothLock.readLock().unlock();
fredc116d1d462012-04-20 14:47:08 -07001173 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001174
Matthew Xiecdce0b92012-07-12 19:06:15 -07001175 // mName is accessed from outside.
1176 // It alright without a lock. Here, bluetooth is off, no other thread is
1177 // changing mName
fredc0f420372012-04-12 00:02:00 -07001178 return mName;
1179 }
1180
fredc0f420372012-04-12 00:02:00 -07001181 private class BluetoothServiceConnection implements ServiceConnection {
fredc0f420372012-04-12 00:02:00 -07001182 public void onServiceConnected(ComponentName className, IBinder service) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001183 if (DBG) Slog.d(TAG, "BluetoothServiceConnection: " + className.getClassName());
fredc0f420372012-04-12 00:02:00 -07001184 Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_SERVICE_CONNECTED);
Matthew Xieddf7e472013-03-01 18:41:02 -08001185 // TBD if (className.getClassName().equals(IBluetooth.class.getName())) {
1186 if (className.getClassName().equals("com.android.bluetooth.btservice.AdapterService")) {
1187 msg.arg1 = SERVICE_IBLUETOOTH;
1188 // } else if (className.getClassName().equals(IBluetoothGatt.class.getName())) {
1189 } else if (className.getClassName().equals("com.android.bluetooth.gatt.GattService")) {
1190 msg.arg1 = SERVICE_IBLUETOOTHGATT;
1191 } else {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001192 Slog.e(TAG, "Unknown service connected: " + className.getClassName());
Matthew Xieddf7e472013-03-01 18:41:02 -08001193 return;
1194 }
fredc0f420372012-04-12 00:02:00 -07001195 msg.obj = service;
1196 mHandler.sendMessage(msg);
1197 }
1198
1199 public void onServiceDisconnected(ComponentName className) {
fredc0f420372012-04-12 00:02:00 -07001200 // Called if we unexpected disconnected.
Jeff Sharkey67609c72016-03-05 14:29:13 -07001201 if (DBG) Slog.d(TAG, "BluetoothServiceConnection, disconnected: " +
Matthew Xieddf7e472013-03-01 18:41:02 -08001202 className.getClassName());
fredc0f420372012-04-12 00:02:00 -07001203 Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED);
Matthew Xieddf7e472013-03-01 18:41:02 -08001204 if (className.getClassName().equals("com.android.bluetooth.btservice.AdapterService")) {
1205 msg.arg1 = SERVICE_IBLUETOOTH;
1206 } else if (className.getClassName().equals("com.android.bluetooth.gatt.GattService")) {
1207 msg.arg1 = SERVICE_IBLUETOOTHGATT;
1208 } else {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001209 Slog.e(TAG, "Unknown service disconnected: " + className.getClassName());
Matthew Xieddf7e472013-03-01 18:41:02 -08001210 return;
1211 }
fredc0f420372012-04-12 00:02:00 -07001212 mHandler.sendMessage(msg);
1213 }
1214 }
1215
1216 private BluetoothServiceConnection mConnection = new BluetoothServiceConnection();
1217
Zhihai Xu40874a02012-10-08 17:57:03 -07001218 private class BluetoothHandler extends Handler {
Ajay Panicker4bb48302016-03-31 14:14:27 -07001219 boolean mGetNameAddressOnly = false;
1220
Zhihai Xu40874a02012-10-08 17:57:03 -07001221 public BluetoothHandler(Looper looper) {
1222 super(looper);
1223 }
1224
fredc0f420372012-04-12 00:02:00 -07001225 @Override
1226 public void handleMessage(Message msg) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001227 if (DBG) Slog.d (TAG, "Message: " + msg.what);
fredc0f420372012-04-12 00:02:00 -07001228 switch (msg.what) {
Ajay Panicker4bb48302016-03-31 14:14:27 -07001229 case MESSAGE_GET_NAME_AND_ADDRESS:
1230 if (DBG) Slog.d(TAG, "MESSAGE_GET_NAME_AND_ADDRESS");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001231 try {
1232 mBluetoothLock.writeLock().lock();
Ajay Panicker4bb48302016-03-31 14:14:27 -07001233 if ((mBluetooth == null) && (!mBinding)) {
1234 if (DBG) Slog.d(TAG, "Binding to service to get name and address");
1235 mGetNameAddressOnly = true;
1236 Message timeoutMsg = mHandler.obtainMessage(MESSAGE_TIMEOUT_BIND);
1237 mHandler.sendMessageDelayed(timeoutMsg, TIMEOUT_BIND_MS);
1238 Intent i = new Intent(IBluetooth.class.getName());
1239 if (!doBind(i, mConnection,
1240 Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT,
1241 UserHandle.CURRENT)) {
1242 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
1243 } else {
1244 mBinding = true;
1245 }
1246 } else if (mBluetooth != null) {
1247 try {
1248 storeNameAndAddress(mBluetooth.getName(),
1249 mBluetooth.getAddress());
1250 } catch (RemoteException re) {
1251 Slog.e(TAG, "Unable to grab names", re);
1252 }
1253 if (mGetNameAddressOnly && !mEnable) {
1254 unbindAndFinish();
1255 }
1256 mGetNameAddressOnly = false;
1257 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001258 } finally {
1259 mBluetoothLock.writeLock().unlock();
Ajay Panicker4bb48302016-03-31 14:14:27 -07001260 }
1261 break;
1262
Matthew Xiecdce0b92012-07-12 19:06:15 -07001263 case MESSAGE_ENABLE:
fredcf2458862012-04-16 15:18:27 -07001264 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001265 Slog.d(TAG, "MESSAGE_ENABLE: mBluetooth = " + mBluetooth);
fredc649fe492012-04-19 01:07:18 -07001266 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001267 mHandler.removeMessages(MESSAGE_RESTART_BLUETOOTH_SERVICE);
1268 mEnable = true;
Calvin Ona0b91d72016-06-15 17:58:23 -07001269
1270 // Use service interface to get the exact state
1271 try {
1272 mBluetoothLock.readLock().lock();
1273 if (mBluetooth != null) {
1274 int state = mBluetooth.getState();
1275 if (state == BluetoothAdapter.STATE_BLE_ON) {
1276 Slog.w(TAG, "BT is in BLE_ON State");
1277 mBluetooth.onLeServiceUp();
1278 break;
1279 }
1280 }
1281 } catch (RemoteException e) {
1282 Slog.e(TAG, "", e);
1283 } finally {
1284 mBluetoothLock.readLock().unlock();
1285 }
1286
1287 mQuietEnable = (msg.arg1 == 1);
Pavlin Radoslavove47ec142016-06-01 22:25:18 -07001288 if (mBluetooth == null) {
Calvin Ona0b91d72016-06-15 17:58:23 -07001289 handleEnable(mQuietEnable);
Pavlin Radoslavove47ec142016-06-01 22:25:18 -07001290 } else {
1291 //
1292 // We need to wait until transitioned to STATE_OFF and
1293 // the previous Bluetooth process has exited. The
1294 // waiting period has three components:
1295 // (a) Wait until the local state is STATE_OFF. This
1296 // is accomplished by "waitForOnOff(false, true)".
1297 // (b) Wait until the STATE_OFF state is updated to
1298 // all components.
1299 // (c) Wait until the Bluetooth process exits, and
1300 // ActivityManager detects it.
1301 // The waiting for (b) and (c) is accomplished by
1302 // delaying the MESSAGE_RESTART_BLUETOOTH_SERVICE
1303 // message. On slower devices, that delay needs to be
1304 // on the order of (2 * SERVICE_RESTART_TIME_MS).
1305 //
1306 waitForOnOff(false, true);
Pavlin Radoslavove47ec142016-06-01 22:25:18 -07001307 Message restartMsg = mHandler.obtainMessage(
1308 MESSAGE_RESTART_BLUETOOTH_SERVICE);
1309 mHandler.sendMessageDelayed(restartMsg,
1310 2 * SERVICE_RESTART_TIME_MS);
1311 }
fredc649fe492012-04-19 01:07:18 -07001312 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001313
fredc0f420372012-04-12 00:02:00 -07001314 case MESSAGE_DISABLE:
Zhihai Xu40874a02012-10-08 17:57:03 -07001315 mHandler.removeMessages(MESSAGE_RESTART_BLUETOOTH_SERVICE);
1316 if (mEnable && mBluetooth != null) {
1317 waitForOnOff(true, false);
1318 mEnable = false;
Zhihai Xu401202b2012-12-03 11:36:21 -08001319 handleDisable();
Zhihai Xu40874a02012-10-08 17:57:03 -07001320 waitForOnOff(false, false);
1321 } else {
1322 mEnable = false;
Zhihai Xu401202b2012-12-03 11:36:21 -08001323 handleDisable();
Zhihai Xu40874a02012-10-08 17:57:03 -07001324 }
fredc0f420372012-04-12 00:02:00 -07001325 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001326
fredc0f420372012-04-12 00:02:00 -07001327 case MESSAGE_REGISTER_ADAPTER:
1328 {
1329 IBluetoothManagerCallback callback = (IBluetoothManagerCallback) msg.obj;
fredcd6883532012-04-25 17:46:13 -07001330 boolean added = mCallbacks.register(callback);
Jeff Sharkey67609c72016-03-05 14:29:13 -07001331 Slog.d(TAG,"Added callback: " + (callback == null? "null": callback) +":" +added );
fredc0f420372012-04-12 00:02:00 -07001332 }
1333 break;
1334 case MESSAGE_UNREGISTER_ADAPTER:
1335 {
1336 IBluetoothManagerCallback callback = (IBluetoothManagerCallback) msg.obj;
fredcd6883532012-04-25 17:46:13 -07001337 boolean removed = mCallbacks.unregister(callback);
Jeff Sharkey67609c72016-03-05 14:29:13 -07001338 Slog.d(TAG,"Removed callback: " + (callback == null? "null": callback) +":" + removed);
fredc0f420372012-04-12 00:02:00 -07001339 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001340 }
fredc0f420372012-04-12 00:02:00 -07001341 case MESSAGE_REGISTER_STATE_CHANGE_CALLBACK:
1342 {
1343 IBluetoothStateChangeCallback callback = (IBluetoothStateChangeCallback) msg.obj;
Matthew Xie9b693992013-10-10 11:21:40 -07001344 if (callback != null) {
1345 mStateChangeCallbacks.register(callback);
1346 }
fredc0f420372012-04-12 00:02:00 -07001347 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001348 }
fredc0f420372012-04-12 00:02:00 -07001349 case MESSAGE_UNREGISTER_STATE_CHANGE_CALLBACK:
1350 {
1351 IBluetoothStateChangeCallback callback = (IBluetoothStateChangeCallback) msg.obj;
Matthew Xie9b693992013-10-10 11:21:40 -07001352 if (callback != null) {
1353 mStateChangeCallbacks.unregister(callback);
1354 }
fredc0f420372012-04-12 00:02:00 -07001355 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001356 }
Benjamin Franze8b98922014-11-12 15:57:54 +00001357 case MESSAGE_ADD_PROXY_DELAYED:
1358 {
1359 ProfileServiceConnections psc = mProfileServices.get(
1360 new Integer(msg.arg1));
1361 if (psc == null) {
1362 break;
1363 }
1364 IBluetoothProfileServiceConnection proxy =
1365 (IBluetoothProfileServiceConnection) msg.obj;
1366 psc.addProxy(proxy);
1367 break;
1368 }
1369 case MESSAGE_BIND_PROFILE_SERVICE:
1370 {
1371 ProfileServiceConnections psc = (ProfileServiceConnections) msg.obj;
1372 removeMessages(MESSAGE_BIND_PROFILE_SERVICE, msg.obj);
1373 if (psc == null) {
1374 break;
1375 }
1376 psc.bindService();
1377 break;
1378 }
fredc0f420372012-04-12 00:02:00 -07001379 case MESSAGE_BLUETOOTH_SERVICE_CONNECTED:
1380 {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001381 if (DBG) Slog.d(TAG,"MESSAGE_BLUETOOTH_SERVICE_CONNECTED: " + msg.arg1);
fredc0f420372012-04-12 00:02:00 -07001382
1383 IBinder service = (IBinder) msg.obj;
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001384 try {
1385 mBluetoothLock.writeLock().lock();
Matthew Xieddf7e472013-03-01 18:41:02 -08001386 if (msg.arg1 == SERVICE_IBLUETOOTHGATT) {
1387 mBluetoothGatt = IBluetoothGatt.Stub.asInterface(service);
Nitin Arorad055adb2015-03-02 15:03:51 -08001388 onBluetoothGattServiceUp();
Matthew Xieddf7e472013-03-01 18:41:02 -08001389 break;
1390 } // else must be SERVICE_IBLUETOOTH
1391
1392 //Remove timeout
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001393 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
Matthew Xieddf7e472013-03-01 18:41:02 -08001394
fredc0f420372012-04-12 00:02:00 -07001395 mBinding = false;
Marie Janssen9db28eb2016-01-12 16:05:15 -08001396 mBluetoothBinder = service;
fredc0f420372012-04-12 00:02:00 -07001397 mBluetooth = IBluetooth.Stub.asInterface(service);
fredc0f420372012-04-12 00:02:00 -07001398
Ajay Panicker4bb48302016-03-31 14:14:27 -07001399 if (!isNameAndAddressSet()) {
1400 Message getMsg = mHandler.obtainMessage(MESSAGE_GET_NAME_AND_ADDRESS);
1401 mHandler.sendMessage(getMsg);
1402 if (mGetNameAddressOnly) return;
1403 }
1404
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001405 try {
1406 boolean enableHciSnoopLog = (Settings.Secure.getInt(mContentResolver,
1407 Settings.Secure.BLUETOOTH_HCI_LOG, 0) == 1);
1408 if (!mBluetooth.configHciSnoopLog(enableHciSnoopLog)) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001409 Slog.e(TAG,"IBluetooth.configHciSnoopLog return false");
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001410 }
1411 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001412 Slog.e(TAG,"Unable to call configHciSnoopLog", e);
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001413 }
1414
Matthew Xiecdce0b92012-07-12 19:06:15 -07001415 //Register callback object
fredcbf072a72012-05-09 16:52:50 -07001416 try {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001417 mBluetooth.registerCallback(mBluetoothCallback);
1418 } catch (RemoteException re) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001419 Slog.e(TAG, "Unable to register BluetoothCallback",re);
fredcbf072a72012-05-09 16:52:50 -07001420 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001421 //Inform BluetoothAdapter instances that service is up
Zhihai Xu40874a02012-10-08 17:57:03 -07001422 sendBluetoothServiceUpCallback();
1423
Matthew Xiecdce0b92012-07-12 19:06:15 -07001424 //Do enable request
1425 try {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001426 if (mQuietEnable == false) {
1427 if(!mBluetooth.enable()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001428 Slog.e(TAG,"IBluetooth.enable() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001429 }
1430 }
1431 else
1432 {
1433 if(!mBluetooth.enableNoAutoConnect()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001434 Slog.e(TAG,"IBluetooth.enableNoAutoConnect() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001435 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001436 }
1437 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001438 Slog.e(TAG,"Unable to call enable()",e);
Matthew Xiecdce0b92012-07-12 19:06:15 -07001439 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001440 } finally {
1441 mBluetoothLock.writeLock().unlock();
Freda8c6df02012-07-11 10:25:23 -07001442 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001443
1444 if (!mEnable) {
1445 waitForOnOff(true, false);
Zhihai Xu401202b2012-12-03 11:36:21 -08001446 handleDisable();
Zhihai Xu40874a02012-10-08 17:57:03 -07001447 waitForOnOff(false, false);
1448 }
fredc649fe492012-04-19 01:07:18 -07001449 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001450 }
fredc649fe492012-04-19 01:07:18 -07001451 case MESSAGE_TIMEOUT_BIND: {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001452 Slog.e(TAG, "MESSAGE_TIMEOUT_BIND");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001453 mBluetoothLock.writeLock().lock();
1454 mBinding = false;
1455 mBluetoothLock.writeLock().unlock();
1456
fredc649fe492012-04-19 01:07:18 -07001457 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001458 }
fredcbf072a72012-05-09 16:52:50 -07001459 case MESSAGE_BLUETOOTH_STATE_CHANGE:
fredc0f420372012-04-12 00:02:00 -07001460 {
fredcbf072a72012-05-09 16:52:50 -07001461 int prevState = msg.arg1;
1462 int newState = msg.arg2;
Jeff Sharkey67609c72016-03-05 14:29:13 -07001463 if (DBG) Slog.d(TAG, "MESSAGE_BLUETOOTH_STATE_CHANGE: prevState = " + prevState + ", newState=" + newState);
Zhihai Xu40874a02012-10-08 17:57:03 -07001464 mState = newState;
1465 bluetoothStateChangeHandler(prevState, newState);
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001466 // handle error state transition case from TURNING_ON to OFF
1467 // unbind and rebind bluetooth service and enable bluetooth
Nitin Arorad055adb2015-03-02 15:03:51 -08001468 if ((prevState == BluetoothAdapter.STATE_BLE_TURNING_ON) &&
Calvin Ona0b91d72016-06-15 17:58:23 -07001469 (newState == BluetoothAdapter.STATE_OFF) &&
1470 (mBluetooth != null) && mEnable) {
Marie Janssen2977c3e2016-11-09 12:01:24 -08001471 recoverBluetoothServiceFromError(false);
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001472 }
Nitin Arorad055adb2015-03-02 15:03:51 -08001473 if ((prevState == BluetoothAdapter.STATE_TURNING_ON) &&
Calvin Ona0b91d72016-06-15 17:58:23 -07001474 (newState == BluetoothAdapter.STATE_BLE_ON) &&
1475 (mBluetooth != null) && mEnable) {
Marie Janssen2977c3e2016-11-09 12:01:24 -08001476 recoverBluetoothServiceFromError(true);
Nitin Arorad055adb2015-03-02 15:03:51 -08001477 }
Calvin Ona0b91d72016-06-15 17:58:23 -07001478 // If we tried to enable BT while BT was in the process of shutting down,
1479 // wait for the BT process to fully tear down and then force a restart
1480 // here. This is a bit of a hack (b/29363429).
1481 if ((prevState == BluetoothAdapter.STATE_BLE_TURNING_OFF) &&
1482 (newState == BluetoothAdapter.STATE_OFF)) {
1483 if (mEnable) {
1484 Slog.d(TAG, "Entering STATE_OFF but mEnabled is true; restarting.");
1485 waitForOnOff(false, true);
1486 Message restartMsg = mHandler.obtainMessage(
1487 MESSAGE_RESTART_BLUETOOTH_SERVICE);
1488 mHandler.sendMessageDelayed(restartMsg, 2 * SERVICE_RESTART_TIME_MS);
1489 }
1490 }
Nitin Arorad055adb2015-03-02 15:03:51 -08001491 if (newState == BluetoothAdapter.STATE_ON ||
Calvin Ona0b91d72016-06-15 17:58:23 -07001492 newState == BluetoothAdapter.STATE_BLE_ON) {
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001493 // bluetooth is working, reset the counter
1494 if (mErrorRecoveryRetryCounter != 0) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001495 Slog.w(TAG, "bluetooth is recovered from error");
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001496 mErrorRecoveryRetryCounter = 0;
1497 }
1498 }
fredc649fe492012-04-19 01:07:18 -07001499 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001500 }
fredc0f420372012-04-12 00:02:00 -07001501 case MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED:
1502 {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001503 Slog.e(TAG, "MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED: " + msg.arg1);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001504 try {
1505 mBluetoothLock.writeLock().lock();
Matthew Xieddf7e472013-03-01 18:41:02 -08001506 if (msg.arg1 == SERVICE_IBLUETOOTH) {
1507 // if service is unbinded already, do nothing and return
1508 if (mBluetooth == null) break;
1509 mBluetooth = null;
1510 } else if (msg.arg1 == SERVICE_IBLUETOOTHGATT) {
1511 mBluetoothGatt = null;
1512 break;
1513 } else {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001514 Slog.e(TAG, "Bad msg.arg1: " + msg.arg1);
Matthew Xieddf7e472013-03-01 18:41:02 -08001515 break;
1516 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001517 } finally {
1518 mBluetoothLock.writeLock().unlock();
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301519 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001520
1521 if (mEnable) {
1522 mEnable = false;
1523 // Send a Bluetooth Restart message
1524 Message restartMsg = mHandler.obtainMessage(
1525 MESSAGE_RESTART_BLUETOOTH_SERVICE);
1526 mHandler.sendMessageDelayed(restartMsg,
1527 SERVICE_RESTART_TIME_MS);
1528 }
1529
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001530 sendBluetoothServiceDownCallback();
Zhihai Xu40874a02012-10-08 17:57:03 -07001531
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001532 // Send BT state broadcast to update
1533 // the BT icon correctly
1534 if ((mState == BluetoothAdapter.STATE_TURNING_ON) ||
Calvin Ona0b91d72016-06-15 17:58:23 -07001535 (mState == BluetoothAdapter.STATE_ON)) {
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001536 bluetoothStateChangeHandler(BluetoothAdapter.STATE_ON,
1537 BluetoothAdapter.STATE_TURNING_OFF);
1538 mState = BluetoothAdapter.STATE_TURNING_OFF;
Zhihai Xu40874a02012-10-08 17:57:03 -07001539 }
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001540 if (mState == BluetoothAdapter.STATE_TURNING_OFF) {
1541 bluetoothStateChangeHandler(BluetoothAdapter.STATE_TURNING_OFF,
1542 BluetoothAdapter.STATE_OFF);
1543 }
1544
1545 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
1546 mState = BluetoothAdapter.STATE_OFF;
fredc649fe492012-04-19 01:07:18 -07001547 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001548 }
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301549 case MESSAGE_RESTART_BLUETOOTH_SERVICE:
1550 {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001551 Slog.d(TAG, "MESSAGE_RESTART_BLUETOOTH_SERVICE:"
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301552 +" Restart IBluetooth service");
1553 /* Enable without persisting the setting as
1554 it doesnt change when IBluetooth
1555 service restarts */
Zhihai Xu40874a02012-10-08 17:57:03 -07001556 mEnable = true;
Zhihai Xu401202b2012-12-03 11:36:21 -08001557 handleEnable(mQuietEnable);
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301558 break;
1559 }
1560
fredc0f420372012-04-12 00:02:00 -07001561 case MESSAGE_TIMEOUT_UNBIND:
1562 {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001563 Slog.e(TAG, "MESSAGE_TIMEOUT_UNBIND");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001564 mBluetoothLock.writeLock().lock();
1565 mUnbinding = false;
1566 mBluetoothLock.writeLock().unlock();
fredc649fe492012-04-19 01:07:18 -07001567 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001568 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001569
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001570 case MESSAGE_USER_SWITCHED: {
1571 if (DBG) Slog.d(TAG, "MESSAGE_USER_SWITCHED");
Zhihai Xu40874a02012-10-08 17:57:03 -07001572 mHandler.removeMessages(MESSAGE_USER_SWITCHED);
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001573
Zhihai Xu40874a02012-10-08 17:57:03 -07001574 /* disable and enable BT when detect a user switch */
1575 if (mEnable && mBluetooth != null) {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001576 try {
1577 mBluetoothLock.readLock().lock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001578 if (mBluetooth != null) {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001579 mBluetooth.unregisterCallback(mBluetoothCallback);
Zhihai Xu40874a02012-10-08 17:57:03 -07001580 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001581 } catch (RemoteException re) {
1582 Slog.e(TAG, "Unable to unregister", re);
1583 } finally {
1584 mBluetoothLock.readLock().unlock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001585 }
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001586
1587 if (mState == BluetoothAdapter.STATE_TURNING_OFF) {
1588 // MESSAGE_USER_SWITCHED happened right after MESSAGE_ENABLE
1589 bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_OFF);
1590 mState = BluetoothAdapter.STATE_OFF;
1591 }
1592 if (mState == BluetoothAdapter.STATE_OFF) {
1593 bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_TURNING_ON);
1594 mState = BluetoothAdapter.STATE_TURNING_ON;
1595 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001596
1597 waitForOnOff(true, false);
1598
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001599 if (mState == BluetoothAdapter.STATE_TURNING_ON) {
1600 bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_ON);
1601 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001602
Benjamin Franze8b98922014-11-12 15:57:54 +00001603 unbindAllBluetoothProfileServices();
Zhihai Xu40874a02012-10-08 17:57:03 -07001604 // disable
Zhihai Xu401202b2012-12-03 11:36:21 -08001605 handleDisable();
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001606 // Pbap service need receive STATE_TURNING_OFF intent to close
1607 bluetoothStateChangeHandler(BluetoothAdapter.STATE_ON,
1608 BluetoothAdapter.STATE_TURNING_OFF);
Zhihai Xu40874a02012-10-08 17:57:03 -07001609
Pavlin Radoslavov41401112016-06-27 15:25:18 -07001610 boolean didDisableTimeout = !waitForOnOff(false, true);
Zhihai Xu40874a02012-10-08 17:57:03 -07001611
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001612 bluetoothStateChangeHandler(BluetoothAdapter.STATE_TURNING_OFF,
Zhihai Xu40874a02012-10-08 17:57:03 -07001613 BluetoothAdapter.STATE_OFF);
Zhihai Xu40874a02012-10-08 17:57:03 -07001614 sendBluetoothServiceDownCallback();
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001615
Pavlin Radoslavove957a8a2016-05-24 15:28:41 -07001616 try {
1617 mBluetoothLock.writeLock().lock();
1618 if (mBluetooth != null) {
1619 mBluetooth = null;
1620 // Unbind
1621 mContext.unbindService(mConnection);
1622 }
1623 mBluetoothGatt = null;
1624 } finally {
1625 mBluetoothLock.writeLock().unlock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001626 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001627
Pavlin Radoslavov41401112016-06-27 15:25:18 -07001628 //
1629 // If disabling Bluetooth times out, wait for an
1630 // additional amount of time to ensure the process is
1631 // shut down completely before attempting to restart.
1632 //
1633 if (didDisableTimeout) {
1634 SystemClock.sleep(3000);
1635 } else {
1636 SystemClock.sleep(100);
1637 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001638
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001639 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
1640 mState = BluetoothAdapter.STATE_OFF;
Zhihai Xu40874a02012-10-08 17:57:03 -07001641 // enable
Zhihai Xu401202b2012-12-03 11:36:21 -08001642 handleEnable(mQuietEnable);
John Spurlock8a985d22014-02-25 09:40:05 -05001643 } else if (mBinding || mBluetooth != null) {
Zhihai Xu40874a02012-10-08 17:57:03 -07001644 Message userMsg = mHandler.obtainMessage(MESSAGE_USER_SWITCHED);
1645 userMsg.arg2 = 1 + msg.arg2;
1646 // if user is switched when service is being binding
1647 // delay sending MESSAGE_USER_SWITCHED
1648 mHandler.sendMessageDelayed(userMsg, USER_SWITCHED_TIME_MS);
1649 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001650 Slog.d(TAG, "delay MESSAGE_USER_SWITCHED " + userMsg.arg2);
Zhihai Xu40874a02012-10-08 17:57:03 -07001651 }
John Spurlock8a985d22014-02-25 09:40:05 -05001652 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001653 break;
1654 }
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001655 case MESSAGE_USER_UNLOCKED: {
1656 if (DBG) Slog.d(TAG, "MESSAGE_USER_UNLOCKED");
1657 mHandler.removeMessages(MESSAGE_USER_SWITCHED);
1658
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001659 if (mEnable && !mBinding && (mBluetooth == null)) {
1660 // We should be connected, but we gave up for some
1661 // reason; maybe the Bluetooth service wasn't encryption
1662 // aware, so try binding again.
1663 if (DBG) Slog.d(TAG, "Enabled but not bound; retrying after unlock");
1664 handleEnable(mQuietEnable);
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001665 }
1666 }
fredc0f420372012-04-12 00:02:00 -07001667 }
1668 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001669 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001670
Zhihai Xu401202b2012-12-03 11:36:21 -08001671 private void handleEnable(boolean quietMode) {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001672 mQuietEnable = quietMode;
1673
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001674 try {
1675 mBluetoothLock.writeLock().lock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001676 if ((mBluetooth == null) && (!mBinding)) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001677 //Start bind timeout and bind
1678 Message timeoutMsg=mHandler.obtainMessage(MESSAGE_TIMEOUT_BIND);
1679 mHandler.sendMessageDelayed(timeoutMsg,TIMEOUT_BIND_MS);
Matthew Xiecdce0b92012-07-12 19:06:15 -07001680 Intent i = new Intent(IBluetooth.class.getName());
Dianne Hackbornce09f5a2014-10-10 15:03:13 -07001681 if (!doBind(i, mConnection,Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT,
1682 UserHandle.CURRENT)) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001683 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
Zhihai Xu40874a02012-10-08 17:57:03 -07001684 } else {
1685 mBinding = true;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001686 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001687 } else if (mBluetooth != null) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001688 //Enable bluetooth
1689 try {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001690 if (!mQuietEnable) {
1691 if(!mBluetooth.enable()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001692 Slog.e(TAG,"IBluetooth.enable() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001693 }
1694 }
1695 else {
1696 if(!mBluetooth.enableNoAutoConnect()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001697 Slog.e(TAG,"IBluetooth.enableNoAutoConnect() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001698 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001699 }
1700 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001701 Slog.e(TAG,"Unable to call enable()",e);
Matthew Xiecdce0b92012-07-12 19:06:15 -07001702 }
1703 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001704 } finally {
1705 mBluetoothLock.writeLock().unlock();
Matthew Xiecdce0b92012-07-12 19:06:15 -07001706 }
1707 }
1708
Dianne Hackborn221ea892013-08-04 16:50:16 -07001709 boolean doBind(Intent intent, ServiceConnection conn, int flags, UserHandle user) {
1710 ComponentName comp = intent.resolveSystemService(mContext.getPackageManager(), 0);
1711 intent.setComponent(comp);
1712 if (comp == null || !mContext.bindServiceAsUser(intent, conn, flags, user)) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001713 Slog.e(TAG, "Fail to bind to: " + intent);
Dianne Hackborn221ea892013-08-04 16:50:16 -07001714 return false;
1715 }
1716 return true;
1717 }
1718
Zhihai Xu401202b2012-12-03 11:36:21 -08001719 private void handleDisable() {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001720 try {
1721 mBluetoothLock.readLock().lock();
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001722 if (mBluetooth != null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001723 if (DBG) Slog.d(TAG,"Sending off request.");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001724 if (!mBluetooth.disable()) {
1725 Slog.e(TAG,"IBluetooth.disable() returned false");
Matthew Xiecdce0b92012-07-12 19:06:15 -07001726 }
1727 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001728 } catch (RemoteException e) {
1729 Slog.e(TAG,"Unable to call disable()",e);
1730 } finally {
1731 mBluetoothLock.readLock().unlock();
Matthew Xiecdce0b92012-07-12 19:06:15 -07001732 }
1733 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001734
1735 private boolean checkIfCallerIsForegroundUser() {
1736 int foregroundUser;
1737 int callingUser = UserHandle.getCallingUserId();
Martijn Coenen8385c5a2012-11-29 10:14:16 -08001738 int callingUid = Binder.getCallingUid();
Zhihai Xu40874a02012-10-08 17:57:03 -07001739 long callingIdentity = Binder.clearCallingIdentity();
Benjamin Franze8b98922014-11-12 15:57:54 +00001740 UserManager um = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
1741 UserInfo ui = um.getProfileParent(callingUser);
1742 int parentUser = (ui != null) ? ui.id : UserHandle.USER_NULL;
Martijn Coenen8385c5a2012-11-29 10:14:16 -08001743 int callingAppId = UserHandle.getAppId(callingUid);
Zhihai Xu40874a02012-10-08 17:57:03 -07001744 boolean valid = false;
1745 try {
1746 foregroundUser = ActivityManager.getCurrentUser();
Martijn Coenen8385c5a2012-11-29 10:14:16 -08001747 valid = (callingUser == foregroundUser) ||
Benjamin Franze8b98922014-11-12 15:57:54 +00001748 parentUser == foregroundUser ||
Adrian Roosbd9a9a52014-08-18 15:31:57 +02001749 callingAppId == Process.NFC_UID ||
1750 callingAppId == mSystemUiUid;
Zhihai Xu40874a02012-10-08 17:57:03 -07001751 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001752 Slog.d(TAG, "checkIfCallerIsForegroundUser: valid=" + valid
Zhihai Xu40874a02012-10-08 17:57:03 -07001753 + " callingUser=" + callingUser
Benjamin Franze8b98922014-11-12 15:57:54 +00001754 + " parentUser=" + parentUser
Zhihai Xu40874a02012-10-08 17:57:03 -07001755 + " foregroundUser=" + foregroundUser);
1756 }
1757 } finally {
1758 Binder.restoreCallingIdentity(callingIdentity);
1759 }
1760 return valid;
1761 }
1762
Nitin Arorad055adb2015-03-02 15:03:51 -08001763 private void sendBleStateChanged(int prevState, int newState) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001764 if (DBG) Slog.d(TAG,"BLE State Change Intent: " + prevState + " -> " + newState);
Nitin Arorad055adb2015-03-02 15:03:51 -08001765 // Send broadcast message to everyone else
1766 Intent intent = new Intent(BluetoothAdapter.ACTION_BLE_STATE_CHANGED);
1767 intent.putExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE, prevState);
1768 intent.putExtra(BluetoothAdapter.EXTRA_STATE, newState);
1769 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1770 mContext.sendBroadcastAsUser(intent, UserHandle.ALL, BLUETOOTH_PERM);
1771 }
1772
Zhihai Xu40874a02012-10-08 17:57:03 -07001773 private void bluetoothStateChangeHandler(int prevState, int newState) {
Nitin Arorad055adb2015-03-02 15:03:51 -08001774 boolean isStandardBroadcast = true;
Zhihai Xu40874a02012-10-08 17:57:03 -07001775 if (prevState != newState) {
1776 //Notify all proxy objects first of adapter state change
Calvin Ona0b91d72016-06-15 17:58:23 -07001777 if (newState == BluetoothAdapter.STATE_BLE_ON ||
1778 newState == BluetoothAdapter.STATE_OFF) {
Nitin Arorad055adb2015-03-02 15:03:51 -08001779 boolean intermediate_off = (prevState == BluetoothAdapter.STATE_TURNING_OFF
1780 && newState == BluetoothAdapter.STATE_BLE_ON);
Zhihai Xu40874a02012-10-08 17:57:03 -07001781
Nitin Arorad055adb2015-03-02 15:03:51 -08001782 if (newState == BluetoothAdapter.STATE_OFF) {
1783 // If Bluetooth is off, send service down event to proxy objects, and unbind
Jeff Sharkey67609c72016-03-05 14:29:13 -07001784 if (DBG) Slog.d(TAG, "Bluetooth is complete turn off");
Pavlin Radoslavove47ec142016-06-01 22:25:18 -07001785 sendBluetoothServiceDownCallback();
1786 unbindAndFinish();
1787 sendBleStateChanged(prevState, newState);
1788 // Don't broadcast as it has already been broadcast before
1789 isStandardBroadcast = false;
Nitin Arorad055adb2015-03-02 15:03:51 -08001790
1791 } else if (!intermediate_off) {
1792 // connect to GattService
Jeff Sharkey67609c72016-03-05 14:29:13 -07001793 if (DBG) Slog.d(TAG, "Bluetooth is in LE only mode");
Nitin Arorad055adb2015-03-02 15:03:51 -08001794 if (mBluetoothGatt != null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001795 if (DBG) Slog.d(TAG, "Calling BluetoothGattServiceUp");
Nitin Arorad055adb2015-03-02 15:03:51 -08001796 onBluetoothGattServiceUp();
1797 } else {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001798 if (DBG) Slog.d(TAG, "Binding Bluetooth GATT service");
Nitin Arorad055adb2015-03-02 15:03:51 -08001799 if (mContext.getPackageManager().hasSystemFeature(
1800 PackageManager.FEATURE_BLUETOOTH_LE)) {
1801 Intent i = new Intent(IBluetoothGatt.class.getName());
1802 doBind(i, mConnection, Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT, UserHandle.CURRENT);
1803 }
1804 }
1805 sendBleStateChanged(prevState, newState);
1806 //Don't broadcase this as std intent
1807 isStandardBroadcast = false;
1808
1809 } else if (intermediate_off){
Jeff Sharkey67609c72016-03-05 14:29:13 -07001810 if (DBG) Slog.d(TAG, "Intermediate off, back to LE only mode");
Nitin Arorad055adb2015-03-02 15:03:51 -08001811 // For LE only mode, broadcast as is
1812 sendBleStateChanged(prevState, newState);
1813 sendBluetoothStateCallback(false); // BT is OFF for general users
1814 // Broadcast as STATE_OFF
1815 newState = BluetoothAdapter.STATE_OFF;
1816 sendBrEdrDownCallback();
Zhihai Xu40874a02012-10-08 17:57:03 -07001817 }
Nitin Arorad055adb2015-03-02 15:03:51 -08001818 } else if (newState == BluetoothAdapter.STATE_ON) {
1819 boolean isUp = (newState==BluetoothAdapter.STATE_ON);
1820 sendBluetoothStateCallback(isUp);
1821 sendBleStateChanged(prevState, newState);
1822
Calvin Ona0b91d72016-06-15 17:58:23 -07001823 } else if (newState == BluetoothAdapter.STATE_BLE_TURNING_ON ||
1824 newState == BluetoothAdapter.STATE_BLE_TURNING_OFF ) {
Nitin Arorad055adb2015-03-02 15:03:51 -08001825 sendBleStateChanged(prevState, newState);
1826 isStandardBroadcast = false;
1827
Calvin Ona0b91d72016-06-15 17:58:23 -07001828 } else if (newState == BluetoothAdapter.STATE_TURNING_ON ||
1829 newState == BluetoothAdapter.STATE_TURNING_OFF) {
Nitin Arorad055adb2015-03-02 15:03:51 -08001830 sendBleStateChanged(prevState, newState);
Zhihai Xu40874a02012-10-08 17:57:03 -07001831 }
1832
Nitin Arorad055adb2015-03-02 15:03:51 -08001833 if (isStandardBroadcast) {
1834 if (prevState == BluetoothAdapter.STATE_BLE_ON) {
1835 // Show prevState of BLE_ON as OFF to standard users
1836 prevState = BluetoothAdapter.STATE_OFF;
1837 }
1838 Intent intent = new Intent(BluetoothAdapter.ACTION_STATE_CHANGED);
1839 intent.putExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE, prevState);
1840 intent.putExtra(BluetoothAdapter.EXTRA_STATE, newState);
1841 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1842 mContext.sendBroadcastAsUser(intent, UserHandle.ALL, BLUETOOTH_PERM);
1843 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001844 }
1845 }
1846
1847 /**
1848 * if on is true, wait for state become ON
1849 * if off is true, wait for state become OFF
1850 * if both on and off are false, wait for state not ON
1851 */
1852 private boolean waitForOnOff(boolean on, boolean off) {
1853 int i = 0;
1854 while (i < 10) {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001855 try {
1856 mBluetoothLock.readLock().lock();
1857 if (mBluetooth == null) break;
1858 if (on) {
1859 if (mBluetooth.getState() == BluetoothAdapter.STATE_ON) return true;
1860 } else if (off) {
1861 if (mBluetooth.getState() == BluetoothAdapter.STATE_OFF) return true;
1862 } else {
1863 if (mBluetooth.getState() != BluetoothAdapter.STATE_ON) return true;
Zhihai Xu40874a02012-10-08 17:57:03 -07001864 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001865 } catch (RemoteException e) {
1866 Slog.e(TAG, "getState()", e);
1867 break;
1868 } finally {
1869 mBluetoothLock.readLock().unlock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001870 }
1871 if (on || off) {
1872 SystemClock.sleep(300);
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07001873 } else {
Zhihai Xu40874a02012-10-08 17:57:03 -07001874 SystemClock.sleep(50);
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07001875 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001876 i++;
1877 }
Jeff Sharkey67609c72016-03-05 14:29:13 -07001878 Slog.e(TAG,"waitForOnOff time out");
Zhihai Xu40874a02012-10-08 17:57:03 -07001879 return false;
1880 }
Zhihai Xu681ae7f2012-11-12 15:14:18 -08001881
Zhihai Xu401202b2012-12-03 11:36:21 -08001882 private void sendDisableMsg() {
1883 mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_DISABLE));
1884 }
1885
1886 private void sendEnableMsg(boolean quietMode) {
1887 mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_ENABLE,
1888 quietMode ? 1 : 0, 0));
1889 }
1890
Marie Janssen2977c3e2016-11-09 12:01:24 -08001891 private void recoverBluetoothServiceFromError(boolean clearBle) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001892 Slog.e(TAG,"recoverBluetoothServiceFromError");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001893 try {
1894 mBluetoothLock.readLock().lock();
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001895 if (mBluetooth != null) {
1896 //Unregister callback object
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001897 mBluetooth.unregisterCallback(mBluetoothCallback);
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001898 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001899 } catch (RemoteException re) {
1900 Slog.e(TAG, "Unable to unregister", re);
1901 } finally {
1902 mBluetoothLock.readLock().unlock();
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001903 }
1904
1905 SystemClock.sleep(500);
1906
1907 // disable
1908 handleDisable();
1909
1910 waitForOnOff(false, true);
1911
1912 sendBluetoothServiceDownCallback();
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001913
Pavlin Radoslavove957a8a2016-05-24 15:28:41 -07001914 try {
1915 mBluetoothLock.writeLock().lock();
1916 if (mBluetooth != null) {
1917 mBluetooth = null;
1918 // Unbind
1919 mContext.unbindService(mConnection);
1920 }
1921 mBluetoothGatt = null;
1922 } finally {
1923 mBluetoothLock.writeLock().unlock();
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001924 }
1925
1926 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
1927 mState = BluetoothAdapter.STATE_OFF;
1928
Marie Janssen2977c3e2016-11-09 12:01:24 -08001929 if (clearBle) {
1930 clearBleApps();
1931 }
1932
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001933 mEnable = false;
1934
1935 if (mErrorRecoveryRetryCounter++ < MAX_ERROR_RESTART_RETRIES) {
1936 // Send a Bluetooth Restart message to reenable bluetooth
1937 Message restartMsg = mHandler.obtainMessage(
1938 MESSAGE_RESTART_BLUETOOTH_SERVICE);
1939 mHandler.sendMessageDelayed(restartMsg, ERROR_RESTART_TIME_MS);
1940 } else {
1941 // todo: notify user to power down and power up phone to make bluetooth work.
1942 }
1943 }
Mike Lockwood726d4de2014-10-28 14:06:28 -07001944
Lenka Trochtova13a05192016-12-02 12:19:39 +01001945 private boolean isBluetoothDisallowed() {
1946 long callingIdentity = Binder.clearCallingIdentity();
1947 try {
1948 return mContext.getSystemService(UserManager.class)
1949 .hasUserRestriction(UserManager.DISALLOW_BLUETOOTH, UserHandle.SYSTEM);
1950 } finally {
1951 Binder.restoreCallingIdentity(callingIdentity);
1952 }
1953 }
1954
Mike Lockwood726d4de2014-10-28 14:06:28 -07001955 @Override
Pavlin Radoslavov6e8faff2016-02-23 11:54:37 -08001956 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1957 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DUMP, TAG);
1958 String errorMsg = null;
1959 if (mBluetoothBinder == null) {
1960 errorMsg = "Bluetooth Service not connected";
1961 } else {
1962 try {
1963 mBluetoothBinder.dump(fd, args);
1964 } catch (RemoteException re) {
1965 errorMsg = "RemoteException while calling Bluetooth Service";
1966 }
Mike Lockwood726d4de2014-10-28 14:06:28 -07001967 }
Pavlin Radoslavov6e8faff2016-02-23 11:54:37 -08001968 if (errorMsg != null) {
1969 // Silently return if we are extracting metrics in Protobuf format
1970 if ((args.length > 0) && args[0].startsWith("--proto"))
1971 return;
1972 writer.println(errorMsg);
1973 }
Mike Lockwood726d4de2014-10-28 14:06:28 -07001974 }
fredc0f420372012-04-12 00:02:00 -07001975}