blob: 417531217b744cefc5d32dcd8d378b6bebb4b8e9 [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;
Marie Janssencb21ad72016-12-13 10:51:02 -0800107
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -0700108 private static final int MAX_SAVE_RETRIES = 3;
109 private static final int MAX_ERROR_RESTART_RETRIES = 6;
Zhihai Xudd9d17d2013-01-08 17:05:58 -0800110
Zhihai Xu401202b2012-12-03 11:36:21 -0800111 // Bluetooth persisted setting is off
112 private static final int BLUETOOTH_OFF=0;
113 // Bluetooth persisted setting is on
114 // and Airplane mode won't affect Bluetooth state at start up
115 private static final int BLUETOOTH_ON_BLUETOOTH=1;
116 // Bluetooth persisted setting is on
117 // but Airplane mode will affect Bluetooth state at start up
118 // and Airplane mode will have higher priority.
119 private static final int BLUETOOTH_ON_AIRPLANE=2;
fredc0f420372012-04-12 00:02:00 -0700120
Matthew Xieddf7e472013-03-01 18:41:02 -0800121 private static final int SERVICE_IBLUETOOTH = 1;
122 private static final int SERVICE_IBLUETOOTHGATT = 2;
123
fredc0f420372012-04-12 00:02:00 -0700124 private final Context mContext;
Matthew Xiecdce0b92012-07-12 19:06:15 -0700125
126 // Locks are not provided for mName and mAddress.
127 // They are accessed in handler or broadcast receiver, same thread context.
fredc0f420372012-04-12 00:02:00 -0700128 private String mAddress;
129 private String mName;
Matthew Xie6fde3092012-07-11 17:10:07 -0700130 private final ContentResolver mContentResolver;
131 private final RemoteCallbackList<IBluetoothManagerCallback> mCallbacks;
132 private final RemoteCallbackList<IBluetoothStateChangeCallback> mStateChangeCallbacks;
Marie Janssen9db28eb2016-01-12 16:05:15 -0800133 private IBinder mBluetoothBinder;
fredc649fe492012-04-19 01:07:18 -0700134 private IBluetooth mBluetooth;
Matthew Xieddf7e472013-03-01 18:41:02 -0800135 private IBluetoothGatt mBluetoothGatt;
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700136 private final ReentrantReadWriteLock mBluetoothLock =
137 new ReentrantReadWriteLock();
fredc649fe492012-04-19 01:07:18 -0700138 private boolean mBinding;
139 private boolean mUnbinding;
Zhihai Xu401202b2012-12-03 11:36:21 -0800140 // used inside handler thread
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700141 private boolean mQuietEnable = false;
Zhihai Xu401202b2012-12-03 11:36:21 -0800142 // configuarion from external IBinder call which is used to
143 // synchronize with broadcast receiver.
144 private boolean mQuietEnableExternal;
145 // configuarion from external IBinder call which is used to
146 // synchronize with broadcast receiver.
147 private boolean mEnableExternal;
148 // used inside handler thread
Zhihai Xu40874a02012-10-08 17:57:03 -0700149 private boolean mEnable;
150 private int mState;
Zhihai Xu40874a02012-10-08 17:57:03 -0700151 private final BluetoothHandler mHandler;
Zhihai Xudd9d17d2013-01-08 17:05:58 -0800152 private int mErrorRecoveryRetryCounter;
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200153 private final int mSystemUiUid;
fredc0f420372012-04-12 00:02:00 -0700154
Benjamin Franze8b98922014-11-12 15:57:54 +0000155 // Save a ProfileServiceConnections object for each of the bound
156 // bluetooth profile services
157 private final Map <Integer, ProfileServiceConnections> mProfileServices =
158 new HashMap <Integer, ProfileServiceConnections>();
159
Svetoslav Ganovc2ac5bd2016-06-29 17:31:44 -0700160 private final boolean mPermissionReviewRequired;
161
fredc649fe492012-04-19 01:07:18 -0700162 private void registerForAirplaneMode(IntentFilter filter) {
163 final ContentResolver resolver = mContext.getContentResolver();
Christopher Tatec09cdce2012-09-10 16:50:14 -0700164 final String airplaneModeRadios = Settings.Global.getString(resolver,
165 Settings.Global.AIRPLANE_MODE_RADIOS);
166 final String toggleableRadios = Settings.Global.getString(resolver,
167 Settings.Global.AIRPLANE_MODE_TOGGLEABLE_RADIOS);
fredc649fe492012-04-19 01:07:18 -0700168 boolean mIsAirplaneSensitive = airplaneModeRadios == null ? true :
Christopher Tatec09cdce2012-09-10 16:50:14 -0700169 airplaneModeRadios.contains(Settings.Global.RADIO_BLUETOOTH);
fredc649fe492012-04-19 01:07:18 -0700170 if (mIsAirplaneSensitive) {
171 filter.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED);
172 }
173 }
174
fredcbf072a72012-05-09 16:52:50 -0700175 private final IBluetoothCallback mBluetoothCallback = new IBluetoothCallback.Stub() {
176 @Override
177 public void onBluetoothStateChange(int prevState, int newState) throws RemoteException {
178 Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_STATE_CHANGE,prevState,newState);
179 mHandler.sendMessage(msg);
180 }
181 };
182
Lenka Trochtova13a05192016-12-02 12:19:39 +0100183 private final UserRestrictionsListener mUserRestrictionsListener =
184 new UserRestrictionsListener() {
185 @Override
186 public void onUserRestrictionsChanged(int userId, Bundle newRestrictions,
187 Bundle prevRestrictions) {
188 final boolean bluetoothDisallowed =
189 newRestrictions.getBoolean(UserManager.DISALLOW_BLUETOOTH);
190 if ((mEnable || mEnableExternal) && bluetoothDisallowed) {
Svetoslav Ganovc2ac5bd2016-06-29 17:31:44 -0700191 try {
192 disable("android.os.UserManagerInternal", true);
193 } catch (RemoteException e) {
194 // Shouldn't happen: startConsentUiIfNeeded not called
195 // when from system.
196 }
Lenka Trochtova13a05192016-12-02 12:19:39 +0100197 }
198 }
199 };
200
fredcbf072a72012-05-09 16:52:50 -0700201 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
fredc0f420372012-04-12 00:02:00 -0700202 @Override
203 public void onReceive(Context context, Intent intent) {
204 String action = intent.getAction();
fredcbf072a72012-05-09 16:52:50 -0700205 if (BluetoothAdapter.ACTION_LOCAL_NAME_CHANGED.equals(action)) {
fredc0f420372012-04-12 00:02:00 -0700206 String newName = intent.getStringExtra(BluetoothAdapter.EXTRA_LOCAL_NAME);
Jeff Sharkey67609c72016-03-05 14:29:13 -0700207 if (DBG) Slog.d(TAG, "Bluetooth Adapter name changed to " + newName);
fredc0f420372012-04-12 00:02:00 -0700208 if (newName != null) {
209 storeNameAndAddress(newName, null);
210 }
fredc649fe492012-04-19 01:07:18 -0700211 } else if (Intent.ACTION_AIRPLANE_MODE_CHANGED.equals(action)) {
Zhihai Xu401202b2012-12-03 11:36:21 -0800212 synchronized(mReceiver) {
213 if (isBluetoothPersistedStateOn()) {
214 if (isAirplaneModeOn()) {
215 persistBluetoothSetting(BLUETOOTH_ON_AIRPLANE);
216 } else {
217 persistBluetoothSetting(BLUETOOTH_ON_BLUETOOTH);
218 }
219 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800220
221 int st = BluetoothAdapter.STATE_OFF;
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700222 try {
223 mBluetoothLock.readLock().lock();
224 if (mBluetooth != null) {
Nitin Arorad055adb2015-03-02 15:03:51 -0800225 st = mBluetooth.getState();
Nitin Arorad055adb2015-03-02 15:03:51 -0800226 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700227 } catch (RemoteException e) {
228 Slog.e(TAG, "Unable to call getState", e);
229 } finally {
230 mBluetoothLock.readLock().unlock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800231 }
Marie Janssencb21ad72016-12-13 10:51:02 -0800232 Slog.d(TAG, "State " + BluetoothAdapter.nameForState(st));
Nitin Arorad055adb2015-03-02 15:03:51 -0800233
Zhihai Xu401202b2012-12-03 11:36:21 -0800234 if (isAirplaneModeOn()) {
Nitin Arorad055adb2015-03-02 15:03:51 -0800235 // Clear registered LE apps to force shut-off
Marie Janssen2977c3e2016-11-09 12:01:24 -0800236 clearBleApps();
Nitin Arorad055adb2015-03-02 15:03:51 -0800237 if (st == BluetoothAdapter.STATE_BLE_ON) {
238 //if state is BLE_ON make sure you trigger disableBLE part
239 try {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700240 mBluetoothLock.readLock().lock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800241 if (mBluetooth != null) {
242 mBluetooth.onBrEdrDown();
Marie Janssen6a383a72016-10-25 10:47:51 -0700243 mEnable = false;
Nitin Arorad055adb2015-03-02 15:03:51 -0800244 mEnableExternal = false;
245 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700246 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700247 Slog.e(TAG,"Unable to call onBrEdrDown", e);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700248 } finally {
Pavlin Radoslavov7ee53be2016-06-09 12:58:07 -0700249 mBluetoothLock.readLock().unlock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800250 }
251 } else if (st == BluetoothAdapter.STATE_ON){
252 // disable without persisting the setting
Jeff Sharkey67609c72016-03-05 14:29:13 -0700253 Slog.d(TAG, "Calling disable");
Nitin Arorad055adb2015-03-02 15:03:51 -0800254 sendDisableMsg();
255 }
Zhihai Xu401202b2012-12-03 11:36:21 -0800256 } else if (mEnableExternal) {
257 // enable without persisting the setting
Jeff Sharkey67609c72016-03-05 14:29:13 -0700258 Slog.d(TAG, "Calling enable");
Zhihai Xu401202b2012-12-03 11:36:21 -0800259 sendEnableMsg(mQuietEnableExternal);
260 }
fredc649fe492012-04-19 01:07:18 -0700261 }
fredc0f420372012-04-12 00:02:00 -0700262 }
263 }
264 };
265
266 BluetoothManagerService(Context context) {
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700267 mHandler = new BluetoothHandler(IoThread.get().getLooper());
Zhihai Xu40874a02012-10-08 17:57:03 -0700268
fredc0f420372012-04-12 00:02:00 -0700269 mContext = context;
Svetoslav Ganovc2ac5bd2016-06-29 17:31:44 -0700270
271 mPermissionReviewRequired = Build.PERMISSIONS_REVIEW_REQUIRED
272 || context.getResources().getBoolean(
273 com.android.internal.R.bool.config_permissionReviewRequired);
274
fredc0f420372012-04-12 00:02:00 -0700275 mBluetooth = null;
Marie Janssen9db28eb2016-01-12 16:05:15 -0800276 mBluetoothBinder = null;
Nitin Arorad055adb2015-03-02 15:03:51 -0800277 mBluetoothGatt = null;
fredc0f420372012-04-12 00:02:00 -0700278 mBinding = false;
279 mUnbinding = false;
Zhihai Xu40874a02012-10-08 17:57:03 -0700280 mEnable = false;
281 mState = BluetoothAdapter.STATE_OFF;
Zhihai Xu401202b2012-12-03 11:36:21 -0800282 mQuietEnableExternal = false;
283 mEnableExternal = false;
fredc0f420372012-04-12 00:02:00 -0700284 mAddress = null;
285 mName = null;
Zhihai Xudd9d17d2013-01-08 17:05:58 -0800286 mErrorRecoveryRetryCounter = 0;
fredc0f420372012-04-12 00:02:00 -0700287 mContentResolver = context.getContentResolver();
Wei Wange4a744b2015-06-11 17:50:29 -0700288 // Observe BLE scan only mode settings change.
289 registerForBleScanModeChange();
fredcd6883532012-04-25 17:46:13 -0700290 mCallbacks = new RemoteCallbackList<IBluetoothManagerCallback>();
291 mStateChangeCallbacks = new RemoteCallbackList<IBluetoothStateChangeCallback>();
Miao Chou658bf2f2015-06-26 17:14:35 -0700292 IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_LOCAL_NAME_CHANGED);
Matthew Xie6fde3092012-07-11 17:10:07 -0700293 registerForAirplaneMode(filter);
Dianne Hackbornd83a0962014-05-02 16:28:33 -0700294 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
Matthew Xie6fde3092012-07-11 17:10:07 -0700295 mContext.registerReceiver(mReceiver, filter);
fredc0f420372012-04-12 00:02:00 -0700296 loadStoredNameAndAddress();
Zhihai Xu401202b2012-12-03 11:36:21 -0800297 if (isBluetoothPersistedStateOn()) {
298 mEnableExternal = true;
fredc0f420372012-04-12 00:02:00 -0700299 }
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200300
301 int sysUiUid = -1;
302 try {
Jeff Sharkeye06b4d12016-01-06 14:51:50 -0700303 sysUiUid = mContext.getPackageManager().getPackageUidAsUser("com.android.systemui",
Jeff Sharkeyc5967e92016-01-07 18:50:29 -0700304 PackageManager.MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM);
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200305 } catch (PackageManager.NameNotFoundException e) {
Joe LaPennaacddf2b2015-09-04 12:52:42 -0700306 // Some platforms, such as wearables do not have a system ui.
Jeff Sharkey67609c72016-03-05 14:29:13 -0700307 Slog.w(TAG, "Unable to resolve SystemUI's UID.", e);
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200308 }
309 mSystemUiUid = sysUiUid;
fredc0f420372012-04-12 00:02:00 -0700310 }
311
fredc649fe492012-04-19 01:07:18 -0700312 /**
313 * Returns true if airplane mode is currently on
314 */
315 private final boolean isAirplaneModeOn() {
Christopher Tatec09cdce2012-09-10 16:50:14 -0700316 return Settings.Global.getInt(mContext.getContentResolver(),
317 Settings.Global.AIRPLANE_MODE_ON, 0) == 1;
fredc649fe492012-04-19 01:07:18 -0700318 }
319
320 /**
321 * Returns true if the Bluetooth saved state is "on"
322 */
323 private final boolean isBluetoothPersistedStateOn() {
Jeff Brownbf6f6f92012-09-25 15:03:20 -0700324 return Settings.Global.getInt(mContentResolver,
Andre Eisenbach8c184312016-09-06 18:03:10 -0700325 Settings.Global.BLUETOOTH_ON, BLUETOOTH_ON_BLUETOOTH) != BLUETOOTH_OFF;
Zhihai Xu401202b2012-12-03 11:36:21 -0800326 }
327
328 /**
329 * Returns true if the Bluetooth saved state is BLUETOOTH_ON_BLUETOOTH
330 */
331 private final boolean isBluetoothPersistedStateOnBluetooth() {
332 return Settings.Global.getInt(mContentResolver,
Andre Eisenbach8c184312016-09-06 18:03:10 -0700333 Settings.Global.BLUETOOTH_ON, BLUETOOTH_ON_BLUETOOTH) == BLUETOOTH_ON_BLUETOOTH;
fredc649fe492012-04-19 01:07:18 -0700334 }
335
336 /**
337 * Save the Bluetooth on/off state
338 *
339 */
Zhihai Xu401202b2012-12-03 11:36:21 -0800340 private void persistBluetoothSetting(int value) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -0700341 Settings.Global.putInt(mContext.getContentResolver(),
342 Settings.Global.BLUETOOTH_ON,
Zhihai Xu401202b2012-12-03 11:36:21 -0800343 value);
fredc649fe492012-04-19 01:07:18 -0700344 }
345
346 /**
347 * Returns true if the Bluetooth Adapter's name and address is
348 * locally cached
349 * @return
350 */
fredc0f420372012-04-12 00:02:00 -0700351 private boolean isNameAndAddressSet() {
352 return mName !=null && mAddress!= null && mName.length()>0 && mAddress.length()>0;
353 }
354
fredc649fe492012-04-19 01:07:18 -0700355 /**
356 * Retrieve the Bluetooth Adapter's name and address and save it in
357 * in the local cache
358 */
fredc0f420372012-04-12 00:02:00 -0700359 private void loadStoredNameAndAddress() {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700360 if (DBG) Slog.d(TAG, "Loading stored name and address");
Zhihai Xud31c3222012-10-31 16:08:57 -0700361 if (mContext.getResources().getBoolean
362 (com.android.internal.R.bool.config_bluetooth_address_validation) &&
363 Settings.Secure.getInt(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDR_VALID, 0) == 0) {
364 // if the valid flag is not set, don't load the address and name
Jeff Sharkey67609c72016-03-05 14:29:13 -0700365 if (DBG) Slog.d(TAG, "invalid bluetooth name and address stored");
Zhihai Xud31c3222012-10-31 16:08:57 -0700366 return;
367 }
fredc0f420372012-04-12 00:02:00 -0700368 mName = Settings.Secure.getString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_NAME);
369 mAddress = Settings.Secure.getString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDRESS);
Jeff Sharkey67609c72016-03-05 14:29:13 -0700370 if (DBG) Slog.d(TAG, "Stored bluetooth Name=" + mName + ",Address=" + mAddress);
fredc0f420372012-04-12 00:02:00 -0700371 }
372
fredc649fe492012-04-19 01:07:18 -0700373 /**
374 * Save the Bluetooth name and address in the persistent store.
375 * Only non-null values will be saved.
376 * @param name
377 * @param address
378 */
fredc0f420372012-04-12 00:02:00 -0700379 private void storeNameAndAddress(String name, String address) {
380 if (name != null) {
381 Settings.Secure.putString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_NAME, name);
fredc0f420372012-04-12 00:02:00 -0700382 mName = name;
Jeff Sharkey67609c72016-03-05 14:29:13 -0700383 if (DBG) Slog.d(TAG,"Stored Bluetooth name: " +
fredc649fe492012-04-19 01:07:18 -0700384 Settings.Secure.getString(mContentResolver,SECURE_SETTINGS_BLUETOOTH_NAME));
fredc0f420372012-04-12 00:02:00 -0700385 }
386
387 if (address != null) {
388 Settings.Secure.putString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDRESS, address);
fredc0f420372012-04-12 00:02:00 -0700389 mAddress=address;
Jeff Sharkey67609c72016-03-05 14:29:13 -0700390 if (DBG) Slog.d(TAG,"Stored Bluetoothaddress: " +
fredc649fe492012-04-19 01:07:18 -0700391 Settings.Secure.getString(mContentResolver,SECURE_SETTINGS_BLUETOOTH_ADDRESS));
fredc0f420372012-04-12 00:02:00 -0700392 }
Zhihai Xud31c3222012-10-31 16:08:57 -0700393
394 if ((name != null) && (address != null)) {
395 Settings.Secure.putInt(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDR_VALID, 1);
396 }
fredc0f420372012-04-12 00:02:00 -0700397 }
398
399 public IBluetooth registerAdapter(IBluetoothManagerCallback callback){
Natalie Silvanovich55db6462014-05-01 16:12:23 -0700400 if (callback == null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700401 Slog.w(TAG, "Callback is null in registerAdapter");
Natalie Silvanovich55db6462014-05-01 16:12:23 -0700402 return null;
403 }
fredc0f420372012-04-12 00:02:00 -0700404 Message msg = mHandler.obtainMessage(MESSAGE_REGISTER_ADAPTER);
405 msg.obj = callback;
406 mHandler.sendMessage(msg);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700407
408 return mBluetooth;
fredc0f420372012-04-12 00:02:00 -0700409 }
410
411 public void unregisterAdapter(IBluetoothManagerCallback callback) {
Natalie Silvanovich55db6462014-05-01 16:12:23 -0700412 if (callback == null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700413 Slog.w(TAG, "Callback is null in unregisterAdapter");
Natalie Silvanovich55db6462014-05-01 16:12:23 -0700414 return;
415 }
fredc0f420372012-04-12 00:02:00 -0700416 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
417 "Need BLUETOOTH permission");
418 Message msg = mHandler.obtainMessage(MESSAGE_UNREGISTER_ADAPTER);
419 msg.obj = callback;
420 mHandler.sendMessage(msg);
421 }
422
423 public void registerStateChangeCallback(IBluetoothStateChangeCallback callback) {
424 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
425 "Need BLUETOOTH permission");
Marie Janssencb21ad72016-12-13 10:51:02 -0800426 if (callback == null) {
427 Slog.w(TAG, "registerStateChangeCallback: Callback is null!");
428 return;
429 }
fredc0f420372012-04-12 00:02:00 -0700430 Message msg = mHandler.obtainMessage(MESSAGE_REGISTER_STATE_CHANGE_CALLBACK);
431 msg.obj = callback;
432 mHandler.sendMessage(msg);
433 }
434
435 public void unregisterStateChangeCallback(IBluetoothStateChangeCallback callback) {
436 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
437 "Need BLUETOOTH permission");
Marie Janssencb21ad72016-12-13 10:51:02 -0800438 if (callback == null) {
439 Slog.w(TAG, "unregisterStateChangeCallback: Callback is null!");
440 return;
441 }
fredc0f420372012-04-12 00:02:00 -0700442 Message msg = mHandler.obtainMessage(MESSAGE_UNREGISTER_STATE_CHANGE_CALLBACK);
443 msg.obj = callback;
444 mHandler.sendMessage(msg);
445 }
446
447 public boolean isEnabled() {
Zhihai Xu6eb76522012-11-29 15:41:04 -0800448 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
449 (!checkIfCallerIsForegroundUser())) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700450 Slog.w(TAG,"isEnabled(): not allowed for non-active and non system user");
Zhihai Xu40874a02012-10-08 17:57:03 -0700451 return false;
452 }
453
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700454 try {
455 mBluetoothLock.readLock().lock();
456 if (mBluetooth != null) return mBluetooth.isEnabled();
457 } catch (RemoteException e) {
458 Slog.e(TAG, "isEnabled()", e);
459 } finally {
460 mBluetoothLock.readLock().unlock();
fredc0f420372012-04-12 00:02:00 -0700461 }
462 return false;
463 }
464
Christine Hallstrom995c90a2016-05-25 15:49:08 -0700465 public int getState() {
466 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
467 (!checkIfCallerIsForegroundUser())) {
Marie Janssencb21ad72016-12-13 10:51:02 -0800468 Slog.w(TAG, "getState(): report OFF for non-active and non system user");
Christine Hallstrom995c90a2016-05-25 15:49:08 -0700469 return BluetoothAdapter.STATE_OFF;
470 }
471
472 try {
473 mBluetoothLock.readLock().lock();
474 if (mBluetooth != null) return mBluetooth.getState();
475 } catch (RemoteException e) {
476 Slog.e(TAG, "getState()", e);
477 } finally {
478 mBluetoothLock.readLock().unlock();
479 }
480 return BluetoothAdapter.STATE_OFF;
481 }
482
Nitin Arorad055adb2015-03-02 15:03:51 -0800483 class ClientDeathRecipient implements IBinder.DeathRecipient {
484 public void binderDied() {
Marie Janssen6a383a72016-10-25 10:47:51 -0700485 if (DBG) Slog.d(TAG, "Binder is dead - unregister Ble App");
Marie Janssen2977c3e2016-11-09 12:01:24 -0800486 if (isBleAppPresent()) {
487 // Nothing to do, another app is here.
488 return;
489 }
490 if (DBG) Slog.d(TAG, "Disabling LE only mode after application crash");
491 try {
492 mBluetoothLock.readLock().lock();
493 if (mBluetooth != null &&
494 mBluetooth.getState() == BluetoothAdapter.STATE_BLE_ON) {
495 mEnable = false;
496 mBluetooth.onBrEdrDown();
Nitin Arorad055adb2015-03-02 15:03:51 -0800497 }
Marie Janssen2977c3e2016-11-09 12:01:24 -0800498 } catch (RemoteException e) {
499 Slog.e(TAG,"Unable to call onBrEdrDown", e);
500 } finally {
501 mBluetoothLock.readLock().unlock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800502 }
503 }
504 }
505
506 /** Internal death rec list */
Marie Janssen2977c3e2016-11-09 12:01:24 -0800507 Map<IBinder, ClientDeathRecipient> mBleApps = new ConcurrentHashMap<IBinder, ClientDeathRecipient>();
Nitin Arorad055adb2015-03-02 15:03:51 -0800508
Wei Wang67d84162015-04-26 17:04:29 -0700509 @Override
510 public boolean isBleScanAlwaysAvailable() {
Marie Janssen6a383a72016-10-25 10:47:51 -0700511 if (isAirplaneModeOn() && !mEnable) {
512 return false;
513 }
Wei Wang67d84162015-04-26 17:04:29 -0700514 try {
515 return (Settings.Global.getInt(mContentResolver,
516 Settings.Global.BLE_SCAN_ALWAYS_AVAILABLE)) != 0;
517 } catch (SettingNotFoundException e) {
518 }
519 return false;
520 }
521
Wei Wange4a744b2015-06-11 17:50:29 -0700522 // Monitor change of BLE scan only mode settings.
523 private void registerForBleScanModeChange() {
524 ContentObserver contentObserver = new ContentObserver(null) {
525 @Override
526 public void onChange(boolean selfChange) {
Marie Janssen2977c3e2016-11-09 12:01:24 -0800527 if (isBleScanAlwaysAvailable()) {
528 // Nothing to do
529 return;
530 }
531 // BLE scan is not available.
532 disableBleScanMode();
533 clearBleApps();
534 try {
535 mBluetoothLock.readLock().lock();
536 if (mBluetooth != null) mBluetooth.onBrEdrDown();
537 } catch (RemoteException e) {
538 Slog.e(TAG, "error when disabling bluetooth", e);
539 } finally {
540 mBluetoothLock.readLock().unlock();
Wei Wange4a744b2015-06-11 17:50:29 -0700541 }
542 }
543 };
544
545 mContentResolver.registerContentObserver(
546 Settings.Global.getUriFor(Settings.Global.BLE_SCAN_ALWAYS_AVAILABLE),
547 false, contentObserver);
548 }
549
550 // Disable ble scan only mode.
551 private void disableBleScanMode() {
552 try {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700553 mBluetoothLock.writeLock().lock();
Wei Wange4a744b2015-06-11 17:50:29 -0700554 if (mBluetooth != null && (mBluetooth.getState() != BluetoothAdapter.STATE_ON)) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700555 if (DBG) Slog.d(TAG, "Reseting the mEnable flag for clean disable");
Wei Wange4a744b2015-06-11 17:50:29 -0700556 mEnable = false;
557 }
558 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700559 Slog.e(TAG, "getState()", e);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700560 } finally {
561 mBluetoothLock.writeLock().unlock();
Wei Wange4a744b2015-06-11 17:50:29 -0700562 }
563 }
564
Nitin Arorad055adb2015-03-02 15:03:51 -0800565 public int updateBleAppCount(IBinder token, boolean enable) {
566 if (enable) {
567 ClientDeathRecipient r = mBleApps.get(token);
568 if (r == null) {
569 ClientDeathRecipient deathRec = new ClientDeathRecipient();
570 try {
571 token.linkToDeath(deathRec, 0);
572 } catch (RemoteException ex) {
573 throw new IllegalArgumentException("Wake lock is already dead.");
574 }
575 mBleApps.put(token, deathRec);
Jeff Sharkey67609c72016-03-05 14:29:13 -0700576 if (DBG) Slog.d(TAG, "Registered for death Notification");
Nitin Arorad055adb2015-03-02 15:03:51 -0800577 }
578
579 } else {
580 ClientDeathRecipient r = mBleApps.get(token);
581 if (r != null) {
Wei Wange4a744b2015-06-11 17:50:29 -0700582 // Unregister death recipient as the app goes away.
583 token.unlinkToDeath(r, 0);
Nitin Arorad055adb2015-03-02 15:03:51 -0800584 mBleApps.remove(token);
Jeff Sharkey67609c72016-03-05 14:29:13 -0700585 if (DBG) Slog.d(TAG, "Unregistered for death Notification");
Nitin Arorad055adb2015-03-02 15:03:51 -0800586 }
587 }
Marie Janssen2977c3e2016-11-09 12:01:24 -0800588 int appCount = mBleApps.size();
589 if (DBG) Slog.d(TAG, appCount + " registered Ble Apps");
590 if (appCount == 0 && mEnable) {
Wei Wange4a744b2015-06-11 17:50:29 -0700591 disableBleScanMode();
Nitin Arorad055adb2015-03-02 15:03:51 -0800592 }
Marie Janssen2977c3e2016-11-09 12:01:24 -0800593 return appCount;
Nitin Arorad055adb2015-03-02 15:03:51 -0800594 }
595
Wei Wange4a744b2015-06-11 17:50:29 -0700596 // Clear all apps using BLE scan only mode.
597 private void clearBleApps() {
Marie Janssen2977c3e2016-11-09 12:01:24 -0800598 mBleApps.clear();
Wei Wange4a744b2015-06-11 17:50:29 -0700599 }
600
Nitin Arorad055adb2015-03-02 15:03:51 -0800601 /** @hide*/
602 public boolean isBleAppPresent() {
Marie Janssen2977c3e2016-11-09 12:01:24 -0800603 if (DBG) Slog.d(TAG, "isBleAppPresent() count: " + mBleApps.size());
604 return mBleApps.size() > 0;
Nitin Arorad055adb2015-03-02 15:03:51 -0800605 }
606
607 /**
608 * Action taken when GattService is turned off
609 */
610 private void onBluetoothGattServiceUp() {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700611 if (DBG) Slog.d(TAG,"BluetoothGatt Service is Up");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700612 try {
613 mBluetoothLock.readLock().lock();
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700614 if (isBleAppPresent() == false && mBluetooth != null
615 && mBluetooth.getState() == BluetoothAdapter.STATE_BLE_ON) {
Nitin Arorad055adb2015-03-02 15:03:51 -0800616 mBluetooth.onLeServiceUp();
617
618 // waive WRITE_SECURE_SETTINGS permission check
619 long callingIdentity = Binder.clearCallingIdentity();
620 persistBluetoothSetting(BLUETOOTH_ON_BLUETOOTH);
621 Binder.restoreCallingIdentity(callingIdentity);
622 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700623 } catch (RemoteException e) {
624 Slog.e(TAG,"Unable to call onServiceUp", e);
625 } finally {
626 mBluetoothLock.readLock().unlock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800627 }
628 }
629
630 /**
631 * Inform BluetoothAdapter instances that BREDR part is down
632 * and turn off all service and stack if no LE app needs it
633 */
634 private void sendBrEdrDownCallback() {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700635 if (DBG) Slog.d(TAG,"Calling sendBrEdrDownCallback callbacks");
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700636
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700637 if (mBluetooth == null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700638 Slog.w(TAG, "Bluetooth handle is null");
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700639 return;
640 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800641
642 if (isBleAppPresent() == false) {
643 try {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700644 mBluetoothLock.readLock().lock();
645 if (mBluetooth != null) mBluetooth.onBrEdrDown();
646 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700647 Slog.e(TAG, "Call to onBrEdrDown() failed.", e);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700648 } finally {
649 mBluetoothLock.readLock().unlock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800650 }
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700651 } else {
652 // Need to stay at BLE ON. Disconnect all Gatt connections
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700653 try {
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700654 mBluetoothGatt.unregAll();
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700655 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700656 Slog.e(TAG, "Unable to disconnect all apps.", e);
Nitin Arorad055adb2015-03-02 15:03:51 -0800657 }
658 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800659 }
660
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700661 public boolean enableNoAutoConnect()
662 {
Lenka Trochtova13a05192016-12-02 12:19:39 +0100663 if (isBluetoothDisallowed()) {
664 if (DBG) {
665 Slog.d(TAG, "enableNoAutoConnect(): not enabling - bluetooth disallowed");
666 }
667 return false;
668 }
669
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700670 mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
671 "Need BLUETOOTH ADMIN permission");
Zhihai Xu40874a02012-10-08 17:57:03 -0700672
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700673 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700674 Slog.d(TAG,"enableNoAutoConnect(): mBluetooth =" + mBluetooth +
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700675 " mBinding = " + mBinding);
676 }
Martijn Coenen8385c5a2012-11-29 10:14:16 -0800677 int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
678
679 if (callingAppId != Process.NFC_UID) {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700680 throw new SecurityException("no permission to enable Bluetooth quietly");
681 }
Martijn Coenen8385c5a2012-11-29 10:14:16 -0800682
Zhihai Xu401202b2012-12-03 11:36:21 -0800683 synchronized(mReceiver) {
684 mQuietEnableExternal = true;
685 mEnableExternal = true;
686 sendEnableMsg(true);
687 }
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700688 return true;
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700689 }
Ajay Panicker4bb48302016-03-31 14:14:27 -0700690
Svetoslav Ganovc2ac5bd2016-06-29 17:31:44 -0700691 public boolean enable(String packageName) throws RemoteException {
Lenka Trochtova13a05192016-12-02 12:19:39 +0100692 if (isBluetoothDisallowed()) {
693 if (DBG) {
694 Slog.d(TAG,"enable(): not enabling - bluetooth disallowed");
695 }
696 return false;
697 }
698
Svetoslav Ganovc2ac5bd2016-06-29 17:31:44 -0700699 final int callingUid = Binder.getCallingUid();
700 final boolean callerSystem = UserHandle.getAppId(callingUid) == Process.SYSTEM_UID;
701
702 if (!callerSystem) {
703 if (!checkIfCallerIsForegroundUser()) {
704 Slog.w(TAG, "enable(): not allowed for non-active and non system user");
705 return false;
706 }
707
708 mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
709 "Need BLUETOOTH ADMIN permission");
710
711 if (!isEnabled() && mPermissionReviewRequired
712 && startConsentUiIfNeeded(packageName, callingUid,
713 BluetoothAdapter.ACTION_REQUEST_ENABLE)) {
714 return false;
715 }
fredcf2458862012-04-16 15:18:27 -0700716 }
717
Zhihai Xu401202b2012-12-03 11:36:21 -0800718 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700719 Slog.d(TAG,"enable(): mBluetooth =" + mBluetooth +
Marie Janssencb21ad72016-12-13 10:51:02 -0800720 " mBinding = " + mBinding + " mState = " +
721 BluetoothAdapter.nameForState(mState));
Sanket Agarwal090bf552016-04-21 14:10:55 -0700722 }
Zhihai Xu401202b2012-12-03 11:36:21 -0800723
724 synchronized(mReceiver) {
725 mQuietEnableExternal = false;
726 mEnableExternal = true;
727 // waive WRITE_SECURE_SETTINGS permission check
Zhihai Xu401202b2012-12-03 11:36:21 -0800728 sendEnableMsg(false);
729 }
Jeff Sharkey67609c72016-03-05 14:29:13 -0700730 if (DBG) Slog.d(TAG, "enable returning");
Zhihai Xu401202b2012-12-03 11:36:21 -0800731 return true;
fredc0f420372012-04-12 00:02:00 -0700732 }
733
Svetoslav Ganovc2ac5bd2016-06-29 17:31:44 -0700734 public boolean disable(String packageName, boolean persist) throws RemoteException {
735 final int callingUid = Binder.getCallingUid();
736 final boolean callerSystem = UserHandle.getAppId(callingUid) == Process.SYSTEM_UID;
Zhihai Xu40874a02012-10-08 17:57:03 -0700737
Svetoslav Ganovc2ac5bd2016-06-29 17:31:44 -0700738 if (!callerSystem) {
739 if (!checkIfCallerIsForegroundUser()) {
740 Slog.w(TAG, "disable(): not allowed for non-active and non system user");
741 return false;
742 }
743
744 mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
745 "Need BLUETOOTH ADMIN permission");
746
747 if (isEnabled() && mPermissionReviewRequired
748 && startConsentUiIfNeeded(packageName, callingUid,
749 BluetoothAdapter.ACTION_REQUEST_DISABLE)) {
750 return false;
751 }
Zhihai Xu40874a02012-10-08 17:57:03 -0700752 }
753
fredcf2458862012-04-16 15:18:27 -0700754 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700755 Slog.d(TAG,"disable(): mBluetooth = " + mBluetooth +
Matthew Xiecdce0b92012-07-12 19:06:15 -0700756 " mBinding = " + mBinding);
757 }
fredcf2458862012-04-16 15:18:27 -0700758
Zhihai Xu401202b2012-12-03 11:36:21 -0800759 synchronized(mReceiver) {
760 if (persist) {
761 // waive WRITE_SECURE_SETTINGS permission check
762 long callingIdentity = Binder.clearCallingIdentity();
763 persistBluetoothSetting(BLUETOOTH_OFF);
764 Binder.restoreCallingIdentity(callingIdentity);
765 }
766 mEnableExternal = false;
767 sendDisableMsg();
768 }
fredc0f420372012-04-12 00:02:00 -0700769 return true;
770 }
771
Svetoslav Ganovc2ac5bd2016-06-29 17:31:44 -0700772 private boolean startConsentUiIfNeeded(String packageName,
773 int callingUid, String intentAction) throws RemoteException {
774 try {
775 // Validate the package only if we are going to use it
776 ApplicationInfo applicationInfo = mContext.getPackageManager()
777 .getApplicationInfoAsUser(packageName,
778 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
779 UserHandle.getUserId(callingUid));
780 if (applicationInfo.uid != callingUid) {
781 throw new SecurityException("Package " + callingUid
782 + " not in uid " + callingUid);
783 }
784
785 // Legacy apps in permission review mode trigger a user prompt
786 if (applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
787 Intent intent = new Intent(intentAction);
788 mContext.startActivity(intent);
789 return true;
790 }
791 } catch (PackageManager.NameNotFoundException e) {
792 throw new RemoteException(e.getMessage());
793 }
794 return false;
795 }
796
fredc649fe492012-04-19 01:07:18 -0700797 public void unbindAndFinish() {
fredcf2458862012-04-16 15:18:27 -0700798 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700799 Slog.d(TAG,"unbindAndFinish(): " + mBluetooth +
Marie Janssencb21ad72016-12-13 10:51:02 -0800800 " mBinding = " + mBinding + " mUnbinding = " + mUnbinding);
fredcf2458862012-04-16 15:18:27 -0700801 }
802
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700803 try {
804 mBluetoothLock.writeLock().lock();
fredc0f420372012-04-12 00:02:00 -0700805 if (mUnbinding) return;
806 mUnbinding = true;
Pavlin Radoslavove47ec142016-06-01 22:25:18 -0700807 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
Pavlin Radoslavov74f60c02016-09-21 17:28:11 -0700808 mHandler.removeMessages(MESSAGE_BIND_PROFILE_SERVICE);
Zhihai Xu40874a02012-10-08 17:57:03 -0700809 if (mBluetooth != null) {
Andre Eisenbach305fdab2015-11-11 21:43:26 -0800810 //Unregister callback object
811 try {
812 mBluetooth.unregisterCallback(mBluetoothCallback);
813 } catch (RemoteException re) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700814 Slog.e(TAG, "Unable to unregister BluetoothCallback",re);
fredcbf072a72012-05-09 16:52:50 -0700815 }
Marie Janssen9db28eb2016-01-12 16:05:15 -0800816 mBluetoothBinder = null;
fredcd6883532012-04-25 17:46:13 -0700817 mBluetooth = null;
fredc0f420372012-04-12 00:02:00 -0700818 mContext.unbindService(mConnection);
fredcd6883532012-04-25 17:46:13 -0700819 mUnbinding = false;
Zhihai Xu40874a02012-10-08 17:57:03 -0700820 mBinding = false;
fredcf2458862012-04-16 15:18:27 -0700821 } else {
Marie Janssencb21ad72016-12-13 10:51:02 -0800822 mUnbinding = false;
fredc0f420372012-04-12 00:02:00 -0700823 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800824 mBluetoothGatt = null;
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700825 } finally {
826 mBluetoothLock.writeLock().unlock();
fredc0f420372012-04-12 00:02:00 -0700827 }
828 }
829
Matthew Xieddf7e472013-03-01 18:41:02 -0800830 public IBluetoothGatt getBluetoothGatt() {
831 // sync protection
832 return mBluetoothGatt;
833 }
834
Benjamin Franze8b98922014-11-12 15:57:54 +0000835 @Override
836 public boolean bindBluetoothProfileService(int bluetoothProfile,
837 IBluetoothProfileServiceConnection proxy) {
838 if (!mEnable) {
839 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700840 Slog.d(TAG, "Trying to bind to profile: " + bluetoothProfile +
Benjamin Franze8b98922014-11-12 15:57:54 +0000841 ", while Bluetooth was disabled");
842 }
843 return false;
844 }
845 synchronized (mProfileServices) {
846 ProfileServiceConnections psc = mProfileServices.get(new Integer(bluetoothProfile));
847 if (psc == null) {
848 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700849 Slog.d(TAG, "Creating new ProfileServiceConnections object for"
Benjamin Franze8b98922014-11-12 15:57:54 +0000850 + " profile: " + bluetoothProfile);
851 }
Benjamin Franz5b614592014-12-09 18:58:45 +0000852
853 if (bluetoothProfile != BluetoothProfile.HEADSET) return false;
854
855 Intent intent = new Intent(IBluetoothHeadset.class.getName());
Benjamin Franze8b98922014-11-12 15:57:54 +0000856 psc = new ProfileServiceConnections(intent);
Benjamin Franz5b614592014-12-09 18:58:45 +0000857 if (!psc.bindService()) return false;
858
Benjamin Franze8b98922014-11-12 15:57:54 +0000859 mProfileServices.put(new Integer(bluetoothProfile), psc);
Benjamin Franze8b98922014-11-12 15:57:54 +0000860 }
861 }
862
863 // Introducing a delay to give the client app time to prepare
864 Message addProxyMsg = mHandler.obtainMessage(MESSAGE_ADD_PROXY_DELAYED);
865 addProxyMsg.arg1 = bluetoothProfile;
866 addProxyMsg.obj = proxy;
867 mHandler.sendMessageDelayed(addProxyMsg, ADD_PROXY_DELAY_MS);
868 return true;
869 }
870
871 @Override
872 public void unbindBluetoothProfileService(int bluetoothProfile,
873 IBluetoothProfileServiceConnection proxy) {
874 synchronized (mProfileServices) {
875 ProfileServiceConnections psc = mProfileServices.get(new Integer(bluetoothProfile));
876 if (psc == null) {
877 return;
878 }
879 psc.removeProxy(proxy);
880 }
881 }
882
883 private void unbindAllBluetoothProfileServices() {
884 synchronized (mProfileServices) {
885 for (Integer i : mProfileServices.keySet()) {
886 ProfileServiceConnections psc = mProfileServices.get(i);
Benjamin Franz5b614592014-12-09 18:58:45 +0000887 try {
888 mContext.unbindService(psc);
889 } catch (IllegalArgumentException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700890 Slog.e(TAG, "Unable to unbind service with intent: " + psc.mIntent, e);
Benjamin Franz5b614592014-12-09 18:58:45 +0000891 }
Benjamin Franze8b98922014-11-12 15:57:54 +0000892 psc.removeAllProxies();
893 }
894 mProfileServices.clear();
895 }
896 }
897
898 /**
Miao Chou658bf2f2015-06-26 17:14:35 -0700899 * Send enable message and set adapter name and address. Called when the boot phase becomes
900 * PHASE_SYSTEM_SERVICES_READY.
901 */
902 public void handleOnBootPhase() {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700903 if (DBG) Slog.d(TAG, "Bluetooth boot completed");
Lenka Trochtova13a05192016-12-02 12:19:39 +0100904 UserManagerInternal userManagerInternal =
905 LocalServices.getService(UserManagerInternal.class);
906 userManagerInternal.addUserRestrictionsListener(mUserRestrictionsListener);
907 if (isBluetoothDisallowed()) {
908 return;
909 }
Miao Chou658bf2f2015-06-26 17:14:35 -0700910 if (mEnableExternal && isBluetoothPersistedStateOnBluetooth()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700911 if (DBG) Slog.d(TAG, "Auto-enabling Bluetooth.");
Miao Chou658bf2f2015-06-26 17:14:35 -0700912 sendEnableMsg(mQuietEnableExternal);
Ajay Panickerbf796d82016-03-11 13:47:20 -0800913 } else if (!isNameAndAddressSet()) {
914 if (DBG) Slog.d(TAG, "Getting adapter name and address");
Ajay Panicker4bb48302016-03-31 14:14:27 -0700915 Message getMsg = mHandler.obtainMessage(MESSAGE_GET_NAME_AND_ADDRESS);
916 mHandler.sendMessage(getMsg);
Miao Chou658bf2f2015-06-26 17:14:35 -0700917 }
Miao Chou658bf2f2015-06-26 17:14:35 -0700918 }
919
920 /**
921 * Called when switching to a different foreground user.
922 */
923 public void handleOnSwitchUser(int userHandle) {
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -0700924 if (DBG) Slog.d(TAG, "User " + userHandle + " switched");
925 mHandler.obtainMessage(MESSAGE_USER_SWITCHED, userHandle, 0).sendToTarget();
926 }
927
928 /**
929 * Called when user is unlocked.
930 */
931 public void handleOnUnlockUser(int userHandle) {
932 if (DBG) Slog.d(TAG, "User " + userHandle + " unlocked");
933 mHandler.obtainMessage(MESSAGE_USER_UNLOCKED, userHandle, 0).sendToTarget();
Miao Chou658bf2f2015-06-26 17:14:35 -0700934 }
935
936 /**
Benjamin Franze8b98922014-11-12 15:57:54 +0000937 * This class manages the clients connected to a given ProfileService
938 * and maintains the connection with that service.
939 */
940 final private class ProfileServiceConnections implements ServiceConnection,
941 IBinder.DeathRecipient {
942 final RemoteCallbackList<IBluetoothProfileServiceConnection> mProxies =
943 new RemoteCallbackList <IBluetoothProfileServiceConnection>();
944 IBinder mService;
945 ComponentName mClassName;
946 Intent mIntent;
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700947 boolean mInvokingProxyCallbacks = false;
Benjamin Franze8b98922014-11-12 15:57:54 +0000948
949 ProfileServiceConnections(Intent intent) {
950 mService = null;
951 mClassName = null;
952 mIntent = intent;
953 }
954
Benjamin Franz5b614592014-12-09 18:58:45 +0000955 private boolean bindService() {
956 if (mIntent != null && mService == null &&
957 doBind(mIntent, this, 0, UserHandle.CURRENT_OR_SELF)) {
Benjamin Franze8b98922014-11-12 15:57:54 +0000958 Message msg = mHandler.obtainMessage(MESSAGE_BIND_PROFILE_SERVICE);
959 msg.obj = this;
960 mHandler.sendMessageDelayed(msg, TIMEOUT_BIND_MS);
Benjamin Franz5b614592014-12-09 18:58:45 +0000961 return true;
Benjamin Franze8b98922014-11-12 15:57:54 +0000962 }
Jeff Sharkey67609c72016-03-05 14:29:13 -0700963 Slog.w(TAG, "Unable to bind with intent: " + mIntent);
Benjamin Franz5b614592014-12-09 18:58:45 +0000964 return false;
Benjamin Franze8b98922014-11-12 15:57:54 +0000965 }
966
967 private void addProxy(IBluetoothProfileServiceConnection proxy) {
968 mProxies.register(proxy);
969 if (mService != null) {
970 try{
971 proxy.onServiceConnected(mClassName, mService);
972 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700973 Slog.e(TAG, "Unable to connect to proxy", e);
Benjamin Franze8b98922014-11-12 15:57:54 +0000974 }
975 } else {
976 if (!mHandler.hasMessages(MESSAGE_BIND_PROFILE_SERVICE, this)) {
977 Message msg = mHandler.obtainMessage(MESSAGE_BIND_PROFILE_SERVICE);
978 msg.obj = this;
979 mHandler.sendMessage(msg);
980 }
981 }
982 }
983
984 private void removeProxy(IBluetoothProfileServiceConnection proxy) {
985 if (proxy != null) {
986 if (mProxies.unregister(proxy)) {
987 try {
988 proxy.onServiceDisconnected(mClassName);
989 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700990 Slog.e(TAG, "Unable to disconnect proxy", e);
Benjamin Franze8b98922014-11-12 15:57:54 +0000991 }
992 }
993 } else {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700994 Slog.w(TAG, "Trying to remove a null proxy");
Benjamin Franze8b98922014-11-12 15:57:54 +0000995 }
996 }
997
998 private void removeAllProxies() {
999 onServiceDisconnected(mClassName);
1000 mProxies.kill();
1001 }
1002
1003 @Override
1004 public void onServiceConnected(ComponentName className, IBinder service) {
1005 // remove timeout message
1006 mHandler.removeMessages(MESSAGE_BIND_PROFILE_SERVICE, this);
1007 mService = service;
1008 mClassName = className;
1009 try {
1010 mService.linkToDeath(this, 0);
1011 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001012 Slog.e(TAG, "Unable to linkToDeath", e);
Benjamin Franze8b98922014-11-12 15:57:54 +00001013 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001014
1015 if (mInvokingProxyCallbacks) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001016 Slog.e(TAG, "Proxy callbacks already in progress.");
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001017 return;
Benjamin Franze8b98922014-11-12 15:57:54 +00001018 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001019 mInvokingProxyCallbacks = true;
1020
1021 final int n = mProxies.beginBroadcast();
1022 try {
1023 for (int i = 0; i < n; i++) {
1024 try {
1025 mProxies.getBroadcastItem(i).onServiceConnected(className, service);
1026 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001027 Slog.e(TAG, "Unable to connect to proxy", e);
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001028 }
1029 }
1030 } finally {
1031 mProxies.finishBroadcast();
1032 mInvokingProxyCallbacks = false;
1033 }
Benjamin Franze8b98922014-11-12 15:57:54 +00001034 }
1035
1036 @Override
1037 public void onServiceDisconnected(ComponentName className) {
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001038 if (mService == null) return;
Benjamin Franze8b98922014-11-12 15:57:54 +00001039 mService.unlinkToDeath(this, 0);
1040 mService = null;
1041 mClassName = null;
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001042
1043 if (mInvokingProxyCallbacks) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001044 Slog.e(TAG, "Proxy callbacks already in progress.");
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001045 return;
Benjamin Franze8b98922014-11-12 15:57:54 +00001046 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001047 mInvokingProxyCallbacks = true;
1048
1049 final int n = mProxies.beginBroadcast();
1050 try {
1051 for (int i = 0; i < n; i++) {
1052 try {
1053 mProxies.getBroadcastItem(i).onServiceDisconnected(className);
1054 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001055 Slog.e(TAG, "Unable to disconnect from proxy", e);
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001056 }
1057 }
1058 } finally {
1059 mProxies.finishBroadcast();
1060 mInvokingProxyCallbacks = false;
1061 }
Benjamin Franze8b98922014-11-12 15:57:54 +00001062 }
1063
1064 @Override
1065 public void binderDied() {
1066 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001067 Slog.w(TAG, "Profile service for profile: " + mClassName
Benjamin Franze8b98922014-11-12 15:57:54 +00001068 + " died.");
1069 }
1070 onServiceDisconnected(mClassName);
1071 // Trigger rebind
1072 Message msg = mHandler.obtainMessage(MESSAGE_BIND_PROFILE_SERVICE);
1073 msg.obj = this;
1074 mHandler.sendMessageDelayed(msg, TIMEOUT_BIND_MS);
1075 }
1076 }
1077
fredcbf072a72012-05-09 16:52:50 -07001078 private void sendBluetoothStateCallback(boolean isUp) {
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001079 try {
1080 int n = mStateChangeCallbacks.beginBroadcast();
Jeff Sharkey67609c72016-03-05 14:29:13 -07001081 if (DBG) Slog.d(TAG,"Broadcasting onBluetoothStateChange("+isUp+") to " + n + " receivers.");
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001082 for (int i=0; i <n;i++) {
1083 try {
1084 mStateChangeCallbacks.getBroadcastItem(i).onBluetoothStateChange(isUp);
1085 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001086 Slog.e(TAG, "Unable to call onBluetoothStateChange() on callback #" + i , e);
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001087 }
fredcbf072a72012-05-09 16:52:50 -07001088 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001089 } finally {
1090 mStateChangeCallbacks.finishBroadcast();
fredcbf072a72012-05-09 16:52:50 -07001091 }
fredcbf072a72012-05-09 16:52:50 -07001092 }
1093
1094 /**
Zhihai Xu40874a02012-10-08 17:57:03 -07001095 * Inform BluetoothAdapter instances that Adapter service is up
1096 */
1097 private void sendBluetoothServiceUpCallback() {
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001098 try {
1099 int n = mCallbacks.beginBroadcast();
Jeff Sharkey67609c72016-03-05 14:29:13 -07001100 Slog.d(TAG,"Broadcasting onBluetoothServiceUp() to " + n + " receivers.");
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001101 for (int i=0; i <n;i++) {
1102 try {
1103 mCallbacks.getBroadcastItem(i).onBluetoothServiceUp(mBluetooth);
1104 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001105 Slog.e(TAG, "Unable to call onBluetoothServiceUp() on callback #" + i, e);
Zhihai Xu40874a02012-10-08 17:57:03 -07001106 }
1107 }
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001108 } finally {
1109 mCallbacks.finishBroadcast();
Zhihai Xu40874a02012-10-08 17:57:03 -07001110 }
1111 }
1112 /**
fredcbf072a72012-05-09 16:52:50 -07001113 * Inform BluetoothAdapter instances that Adapter service is down
1114 */
1115 private void sendBluetoothServiceDownCallback() {
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001116 try {
1117 int n = mCallbacks.beginBroadcast();
Jeff Sharkey67609c72016-03-05 14:29:13 -07001118 Slog.d(TAG,"Broadcasting onBluetoothServiceDown() to " + n + " receivers.");
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001119 for (int i=0; i <n;i++) {
1120 try {
1121 mCallbacks.getBroadcastItem(i).onBluetoothServiceDown();
1122 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001123 Slog.e(TAG, "Unable to call onBluetoothServiceDown() on callback #" + i, e);
fredcd6883532012-04-25 17:46:13 -07001124 }
1125 }
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001126 } finally {
1127 mCallbacks.finishBroadcast();
fredcd6883532012-04-25 17:46:13 -07001128 }
1129 }
Svet Ganov408abf72015-05-12 19:13:36 -07001130
fredc0f420372012-04-12 00:02:00 -07001131 public String getAddress() {
Matthew Xieaf5ddbf2012-12-04 10:47:43 -08001132 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
Svet Ganov408abf72015-05-12 19:13:36 -07001133 "Need BLUETOOTH permission");
Zhihai Xu40874a02012-10-08 17:57:03 -07001134
Zhihai Xu6eb76522012-11-29 15:41:04 -08001135 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
Svet Ganov408abf72015-05-12 19:13:36 -07001136 (!checkIfCallerIsForegroundUser())) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001137 Slog.w(TAG,"getAddress(): not allowed for non-active and non system user");
Zhihai Xu6eb76522012-11-29 15:41:04 -08001138 return null;
Zhihai Xu40874a02012-10-08 17:57:03 -07001139 }
1140
Svet Ganov408abf72015-05-12 19:13:36 -07001141 if (mContext.checkCallingOrSelfPermission(Manifest.permission.LOCAL_MAC_ADDRESS)
1142 != PackageManager.PERMISSION_GRANTED) {
1143 return BluetoothAdapter.DEFAULT_MAC_ADDRESS;
1144 }
1145
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001146 try {
1147 mBluetoothLock.readLock().lock();
1148 if (mBluetooth != null) return mBluetooth.getAddress();
1149 } catch (RemoteException e) {
1150 Slog.e(TAG, "getAddress(): Unable to retrieve address remotely. Returning cached address", e);
1151 } finally {
1152 mBluetoothLock.readLock().unlock();
fredc116d1d462012-04-20 14:47:08 -07001153 }
Ajay Panickerbf796d82016-03-11 13:47:20 -08001154
Matthew Xiecdce0b92012-07-12 19:06:15 -07001155 // mAddress is accessed from outside.
1156 // It is alright without a lock. Here, bluetooth is off, no other thread is
1157 // changing mAddress
fredc0f420372012-04-12 00:02:00 -07001158 return mAddress;
1159 }
fredc649fe492012-04-19 01:07:18 -07001160
fredc0f420372012-04-12 00:02:00 -07001161 public String getName() {
Matthew Xieaf5ddbf2012-12-04 10:47:43 -08001162 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
1163 "Need BLUETOOTH permission");
Zhihai Xu40874a02012-10-08 17:57:03 -07001164
Zhihai Xu6eb76522012-11-29 15:41:04 -08001165 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
1166 (!checkIfCallerIsForegroundUser())) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001167 Slog.w(TAG,"getName(): not allowed for non-active and non system user");
Zhihai Xu6eb76522012-11-29 15:41:04 -08001168 return null;
Zhihai Xu40874a02012-10-08 17:57:03 -07001169 }
1170
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001171 try {
1172 mBluetoothLock.readLock().lock();
1173 if (mBluetooth != null) return mBluetooth.getName();
1174 } catch (RemoteException e) {
1175 Slog.e(TAG, "getName(): Unable to retrieve name remotely. Returning cached name", e);
1176 } finally {
1177 mBluetoothLock.readLock().unlock();
fredc116d1d462012-04-20 14:47:08 -07001178 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001179
Matthew Xiecdce0b92012-07-12 19:06:15 -07001180 // mName is accessed from outside.
1181 // It alright without a lock. Here, bluetooth is off, no other thread is
1182 // changing mName
fredc0f420372012-04-12 00:02:00 -07001183 return mName;
1184 }
1185
fredc0f420372012-04-12 00:02:00 -07001186 private class BluetoothServiceConnection implements ServiceConnection {
Marie Janssencb21ad72016-12-13 10:51:02 -08001187 public void onServiceConnected(ComponentName componentName, IBinder service) {
1188 String name = componentName.getClassName();
1189 if (DBG) Slog.d(TAG, "BluetoothServiceConnection: " + name);
fredc0f420372012-04-12 00:02:00 -07001190 Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_SERVICE_CONNECTED);
Marie Janssencb21ad72016-12-13 10:51:02 -08001191 if (name.equals("com.android.bluetooth.btservice.AdapterService")) {
Matthew Xieddf7e472013-03-01 18:41:02 -08001192 msg.arg1 = SERVICE_IBLUETOOTH;
Marie Janssencb21ad72016-12-13 10:51:02 -08001193 } else if (name.equals("com.android.bluetooth.gatt.GattService")) {
Matthew Xieddf7e472013-03-01 18:41:02 -08001194 msg.arg1 = SERVICE_IBLUETOOTHGATT;
1195 } else {
Marie Janssencb21ad72016-12-13 10:51:02 -08001196 Slog.e(TAG, "Unknown service connected: " + name);
Matthew Xieddf7e472013-03-01 18:41:02 -08001197 return;
1198 }
fredc0f420372012-04-12 00:02:00 -07001199 msg.obj = service;
1200 mHandler.sendMessage(msg);
1201 }
1202
Marie Janssencb21ad72016-12-13 10:51:02 -08001203 public void onServiceDisconnected(ComponentName componentName) {
1204 // Called if we unexpectedly disconnect.
1205 String name = componentName.getClassName();
1206 if (DBG) Slog.d(TAG, "BluetoothServiceConnection, disconnected: " + name);
fredc0f420372012-04-12 00:02:00 -07001207 Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED);
Marie Janssencb21ad72016-12-13 10:51:02 -08001208 if (name.equals("com.android.bluetooth.btservice.AdapterService")) {
Matthew Xieddf7e472013-03-01 18:41:02 -08001209 msg.arg1 = SERVICE_IBLUETOOTH;
Marie Janssencb21ad72016-12-13 10:51:02 -08001210 } else if (name.equals("com.android.bluetooth.gatt.GattService")) {
Matthew Xieddf7e472013-03-01 18:41:02 -08001211 msg.arg1 = SERVICE_IBLUETOOTHGATT;
1212 } else {
Marie Janssencb21ad72016-12-13 10:51:02 -08001213 Slog.e(TAG, "Unknown service disconnected: " + name);
Matthew Xieddf7e472013-03-01 18:41:02 -08001214 return;
1215 }
fredc0f420372012-04-12 00:02:00 -07001216 mHandler.sendMessage(msg);
1217 }
1218 }
1219
1220 private BluetoothServiceConnection mConnection = new BluetoothServiceConnection();
1221
Zhihai Xu40874a02012-10-08 17:57:03 -07001222 private class BluetoothHandler extends Handler {
Ajay Panicker4bb48302016-03-31 14:14:27 -07001223 boolean mGetNameAddressOnly = false;
1224
Zhihai Xu40874a02012-10-08 17:57:03 -07001225 public BluetoothHandler(Looper looper) {
1226 super(looper);
1227 }
1228
fredc0f420372012-04-12 00:02:00 -07001229 @Override
1230 public void handleMessage(Message msg) {
fredc0f420372012-04-12 00:02:00 -07001231 switch (msg.what) {
Ajay Panicker4bb48302016-03-31 14:14:27 -07001232 case MESSAGE_GET_NAME_AND_ADDRESS:
1233 if (DBG) Slog.d(TAG, "MESSAGE_GET_NAME_AND_ADDRESS");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001234 try {
1235 mBluetoothLock.writeLock().lock();
Ajay Panicker4bb48302016-03-31 14:14:27 -07001236 if ((mBluetooth == null) && (!mBinding)) {
1237 if (DBG) Slog.d(TAG, "Binding to service to get name and address");
1238 mGetNameAddressOnly = true;
1239 Message timeoutMsg = mHandler.obtainMessage(MESSAGE_TIMEOUT_BIND);
1240 mHandler.sendMessageDelayed(timeoutMsg, TIMEOUT_BIND_MS);
1241 Intent i = new Intent(IBluetooth.class.getName());
1242 if (!doBind(i, mConnection,
1243 Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT,
1244 UserHandle.CURRENT)) {
1245 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
1246 } else {
1247 mBinding = true;
1248 }
1249 } else if (mBluetooth != null) {
1250 try {
1251 storeNameAndAddress(mBluetooth.getName(),
1252 mBluetooth.getAddress());
1253 } catch (RemoteException re) {
1254 Slog.e(TAG, "Unable to grab names", re);
1255 }
1256 if (mGetNameAddressOnly && !mEnable) {
1257 unbindAndFinish();
1258 }
1259 mGetNameAddressOnly = false;
1260 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001261 } finally {
1262 mBluetoothLock.writeLock().unlock();
Ajay Panicker4bb48302016-03-31 14:14:27 -07001263 }
1264 break;
1265
Matthew Xiecdce0b92012-07-12 19:06:15 -07001266 case MESSAGE_ENABLE:
fredcf2458862012-04-16 15:18:27 -07001267 if (DBG) {
Marie Janssencb21ad72016-12-13 10:51:02 -08001268 Slog.d(TAG, "MESSAGE_ENABLE(" + msg.arg1 + "): mBluetooth = " + mBluetooth);
fredc649fe492012-04-19 01:07:18 -07001269 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001270 mHandler.removeMessages(MESSAGE_RESTART_BLUETOOTH_SERVICE);
1271 mEnable = true;
Calvin Ona0b91d72016-06-15 17:58:23 -07001272
1273 // Use service interface to get the exact state
1274 try {
1275 mBluetoothLock.readLock().lock();
1276 if (mBluetooth != null) {
1277 int state = mBluetooth.getState();
1278 if (state == BluetoothAdapter.STATE_BLE_ON) {
1279 Slog.w(TAG, "BT is in BLE_ON State");
1280 mBluetooth.onLeServiceUp();
1281 break;
1282 }
1283 }
1284 } catch (RemoteException e) {
1285 Slog.e(TAG, "", e);
1286 } finally {
1287 mBluetoothLock.readLock().unlock();
1288 }
1289
1290 mQuietEnable = (msg.arg1 == 1);
Pavlin Radoslavove47ec142016-06-01 22:25:18 -07001291 if (mBluetooth == null) {
Calvin Ona0b91d72016-06-15 17:58:23 -07001292 handleEnable(mQuietEnable);
Pavlin Radoslavove47ec142016-06-01 22:25:18 -07001293 } else {
1294 //
1295 // We need to wait until transitioned to STATE_OFF and
1296 // the previous Bluetooth process has exited. The
1297 // waiting period has three components:
1298 // (a) Wait until the local state is STATE_OFF. This
1299 // is accomplished by "waitForOnOff(false, true)".
1300 // (b) Wait until the STATE_OFF state is updated to
1301 // all components.
1302 // (c) Wait until the Bluetooth process exits, and
1303 // ActivityManager detects it.
1304 // The waiting for (b) and (c) is accomplished by
1305 // delaying the MESSAGE_RESTART_BLUETOOTH_SERVICE
1306 // message. On slower devices, that delay needs to be
1307 // on the order of (2 * SERVICE_RESTART_TIME_MS).
1308 //
1309 waitForOnOff(false, true);
Pavlin Radoslavove47ec142016-06-01 22:25:18 -07001310 Message restartMsg = mHandler.obtainMessage(
1311 MESSAGE_RESTART_BLUETOOTH_SERVICE);
1312 mHandler.sendMessageDelayed(restartMsg,
1313 2 * SERVICE_RESTART_TIME_MS);
1314 }
fredc649fe492012-04-19 01:07:18 -07001315 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001316
fredc0f420372012-04-12 00:02:00 -07001317 case MESSAGE_DISABLE:
Marie Janssencb21ad72016-12-13 10:51:02 -08001318 if (DBG) Slog.d(TAG, "MESSAGE_DISABLE: mBluetooth = " + mBluetooth);
Zhihai Xu40874a02012-10-08 17:57:03 -07001319 mHandler.removeMessages(MESSAGE_RESTART_BLUETOOTH_SERVICE);
1320 if (mEnable && mBluetooth != null) {
1321 waitForOnOff(true, false);
1322 mEnable = false;
Zhihai Xu401202b2012-12-03 11:36:21 -08001323 handleDisable();
Zhihai Xu40874a02012-10-08 17:57:03 -07001324 waitForOnOff(false, false);
1325 } else {
1326 mEnable = false;
Zhihai Xu401202b2012-12-03 11:36:21 -08001327 handleDisable();
Zhihai Xu40874a02012-10-08 17:57:03 -07001328 }
fredc0f420372012-04-12 00:02:00 -07001329 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001330
fredc0f420372012-04-12 00:02:00 -07001331 case MESSAGE_REGISTER_ADAPTER:
1332 {
1333 IBluetoothManagerCallback callback = (IBluetoothManagerCallback) msg.obj;
Marie Janssencb21ad72016-12-13 10:51:02 -08001334 mCallbacks.register(callback);
fredc0f420372012-04-12 00:02:00 -07001335 break;
Marie Janssencb21ad72016-12-13 10:51:02 -08001336 }
fredc0f420372012-04-12 00:02:00 -07001337 case MESSAGE_UNREGISTER_ADAPTER:
1338 {
1339 IBluetoothManagerCallback callback = (IBluetoothManagerCallback) msg.obj;
Marie Janssencb21ad72016-12-13 10:51:02 -08001340 mCallbacks.unregister(callback);
fredc0f420372012-04-12 00:02:00 -07001341 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001342 }
fredc0f420372012-04-12 00:02:00 -07001343 case MESSAGE_REGISTER_STATE_CHANGE_CALLBACK:
1344 {
1345 IBluetoothStateChangeCallback callback = (IBluetoothStateChangeCallback) msg.obj;
Marie Janssencb21ad72016-12-13 10:51:02 -08001346 mStateChangeCallbacks.register(callback);
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;
Marie Janssencb21ad72016-12-13 10:51:02 -08001352 mStateChangeCallbacks.unregister(callback);
fredc0f420372012-04-12 00:02:00 -07001353 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001354 }
Benjamin Franze8b98922014-11-12 15:57:54 +00001355 case MESSAGE_ADD_PROXY_DELAYED:
1356 {
1357 ProfileServiceConnections psc = mProfileServices.get(
1358 new Integer(msg.arg1));
1359 if (psc == null) {
1360 break;
1361 }
1362 IBluetoothProfileServiceConnection proxy =
1363 (IBluetoothProfileServiceConnection) msg.obj;
1364 psc.addProxy(proxy);
1365 break;
1366 }
1367 case MESSAGE_BIND_PROFILE_SERVICE:
1368 {
1369 ProfileServiceConnections psc = (ProfileServiceConnections) msg.obj;
1370 removeMessages(MESSAGE_BIND_PROFILE_SERVICE, msg.obj);
1371 if (psc == null) {
1372 break;
1373 }
1374 psc.bindService();
1375 break;
1376 }
fredc0f420372012-04-12 00:02:00 -07001377 case MESSAGE_BLUETOOTH_SERVICE_CONNECTED:
1378 {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001379 if (DBG) Slog.d(TAG,"MESSAGE_BLUETOOTH_SERVICE_CONNECTED: " + msg.arg1);
fredc0f420372012-04-12 00:02:00 -07001380
1381 IBinder service = (IBinder) msg.obj;
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001382 try {
1383 mBluetoothLock.writeLock().lock();
Matthew Xieddf7e472013-03-01 18:41:02 -08001384 if (msg.arg1 == SERVICE_IBLUETOOTHGATT) {
1385 mBluetoothGatt = IBluetoothGatt.Stub.asInterface(service);
Nitin Arorad055adb2015-03-02 15:03:51 -08001386 onBluetoothGattServiceUp();
Matthew Xieddf7e472013-03-01 18:41:02 -08001387 break;
1388 } // else must be SERVICE_IBLUETOOTH
1389
1390 //Remove timeout
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001391 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
Matthew Xieddf7e472013-03-01 18:41:02 -08001392
fredc0f420372012-04-12 00:02:00 -07001393 mBinding = false;
Marie Janssen9db28eb2016-01-12 16:05:15 -08001394 mBluetoothBinder = service;
fredc0f420372012-04-12 00:02:00 -07001395 mBluetooth = IBluetooth.Stub.asInterface(service);
fredc0f420372012-04-12 00:02:00 -07001396
Ajay Panicker4bb48302016-03-31 14:14:27 -07001397 if (!isNameAndAddressSet()) {
1398 Message getMsg = mHandler.obtainMessage(MESSAGE_GET_NAME_AND_ADDRESS);
1399 mHandler.sendMessage(getMsg);
1400 if (mGetNameAddressOnly) return;
1401 }
1402
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001403 try {
1404 boolean enableHciSnoopLog = (Settings.Secure.getInt(mContentResolver,
1405 Settings.Secure.BLUETOOTH_HCI_LOG, 0) == 1);
1406 if (!mBluetooth.configHciSnoopLog(enableHciSnoopLog)) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001407 Slog.e(TAG,"IBluetooth.configHciSnoopLog return false");
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001408 }
1409 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001410 Slog.e(TAG,"Unable to call configHciSnoopLog", e);
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001411 }
1412
Matthew Xiecdce0b92012-07-12 19:06:15 -07001413 //Register callback object
fredcbf072a72012-05-09 16:52:50 -07001414 try {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001415 mBluetooth.registerCallback(mBluetoothCallback);
1416 } catch (RemoteException re) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001417 Slog.e(TAG, "Unable to register BluetoothCallback",re);
fredcbf072a72012-05-09 16:52:50 -07001418 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001419 //Inform BluetoothAdapter instances that service is up
Zhihai Xu40874a02012-10-08 17:57:03 -07001420 sendBluetoothServiceUpCallback();
1421
Matthew Xiecdce0b92012-07-12 19:06:15 -07001422 //Do enable request
1423 try {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001424 if (mQuietEnable == false) {
Marie Janssencb21ad72016-12-13 10:51:02 -08001425 if (!mBluetooth.enable()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001426 Slog.e(TAG,"IBluetooth.enable() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001427 }
Marie Janssencb21ad72016-12-13 10:51:02 -08001428 } else {
1429 if (!mBluetooth.enableNoAutoConnect()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001430 Slog.e(TAG,"IBluetooth.enableNoAutoConnect() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001431 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001432 }
1433 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001434 Slog.e(TAG,"Unable to call enable()",e);
Matthew Xiecdce0b92012-07-12 19:06:15 -07001435 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001436 } finally {
1437 mBluetoothLock.writeLock().unlock();
Freda8c6df02012-07-11 10:25:23 -07001438 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001439
1440 if (!mEnable) {
1441 waitForOnOff(true, false);
Zhihai Xu401202b2012-12-03 11:36:21 -08001442 handleDisable();
Zhihai Xu40874a02012-10-08 17:57:03 -07001443 waitForOnOff(false, false);
1444 }
fredc649fe492012-04-19 01:07:18 -07001445 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001446 }
fredcbf072a72012-05-09 16:52:50 -07001447 case MESSAGE_BLUETOOTH_STATE_CHANGE:
fredc0f420372012-04-12 00:02:00 -07001448 {
fredcbf072a72012-05-09 16:52:50 -07001449 int prevState = msg.arg1;
1450 int newState = msg.arg2;
Marie Janssencb21ad72016-12-13 10:51:02 -08001451 if (DBG) {
1452 Slog.d(TAG, "MESSAGE_BLUETOOTH_STATE_CHANGE: " + BluetoothAdapter.nameForState(prevState) + " > " +
1453 BluetoothAdapter.nameForState(newState));
1454 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001455 mState = newState;
1456 bluetoothStateChangeHandler(prevState, newState);
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001457 // handle error state transition case from TURNING_ON to OFF
1458 // unbind and rebind bluetooth service and enable bluetooth
Nitin Arorad055adb2015-03-02 15:03:51 -08001459 if ((prevState == BluetoothAdapter.STATE_BLE_TURNING_ON) &&
Calvin Ona0b91d72016-06-15 17:58:23 -07001460 (newState == BluetoothAdapter.STATE_OFF) &&
1461 (mBluetooth != null) && mEnable) {
Marie Janssen2977c3e2016-11-09 12:01:24 -08001462 recoverBluetoothServiceFromError(false);
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001463 }
Nitin Arorad055adb2015-03-02 15:03:51 -08001464 if ((prevState == BluetoothAdapter.STATE_TURNING_ON) &&
Calvin Ona0b91d72016-06-15 17:58:23 -07001465 (newState == BluetoothAdapter.STATE_BLE_ON) &&
1466 (mBluetooth != null) && mEnable) {
Marie Janssen2977c3e2016-11-09 12:01:24 -08001467 recoverBluetoothServiceFromError(true);
Nitin Arorad055adb2015-03-02 15:03:51 -08001468 }
Calvin Ona0b91d72016-06-15 17:58:23 -07001469 // If we tried to enable BT while BT was in the process of shutting down,
1470 // wait for the BT process to fully tear down and then force a restart
1471 // here. This is a bit of a hack (b/29363429).
1472 if ((prevState == BluetoothAdapter.STATE_BLE_TURNING_OFF) &&
1473 (newState == BluetoothAdapter.STATE_OFF)) {
1474 if (mEnable) {
1475 Slog.d(TAG, "Entering STATE_OFF but mEnabled is true; restarting.");
1476 waitForOnOff(false, true);
1477 Message restartMsg = mHandler.obtainMessage(
1478 MESSAGE_RESTART_BLUETOOTH_SERVICE);
1479 mHandler.sendMessageDelayed(restartMsg, 2 * SERVICE_RESTART_TIME_MS);
1480 }
1481 }
Nitin Arorad055adb2015-03-02 15:03:51 -08001482 if (newState == BluetoothAdapter.STATE_ON ||
Calvin Ona0b91d72016-06-15 17:58:23 -07001483 newState == BluetoothAdapter.STATE_BLE_ON) {
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001484 // bluetooth is working, reset the counter
1485 if (mErrorRecoveryRetryCounter != 0) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001486 Slog.w(TAG, "bluetooth is recovered from error");
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001487 mErrorRecoveryRetryCounter = 0;
1488 }
1489 }
fredc649fe492012-04-19 01:07:18 -07001490 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001491 }
fredc0f420372012-04-12 00:02:00 -07001492 case MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED:
1493 {
Marie Janssencb21ad72016-12-13 10:51:02 -08001494 Slog.e(TAG, "MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED(" + msg.arg1 + ")");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001495 try {
1496 mBluetoothLock.writeLock().lock();
Matthew Xieddf7e472013-03-01 18:41:02 -08001497 if (msg.arg1 == SERVICE_IBLUETOOTH) {
1498 // if service is unbinded already, do nothing and return
1499 if (mBluetooth == null) break;
1500 mBluetooth = null;
1501 } else if (msg.arg1 == SERVICE_IBLUETOOTHGATT) {
1502 mBluetoothGatt = null;
1503 break;
1504 } else {
Marie Janssencb21ad72016-12-13 10:51:02 -08001505 Slog.e(TAG, "Unknown argument for service disconnect!");
Matthew Xieddf7e472013-03-01 18:41:02 -08001506 break;
1507 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001508 } finally {
1509 mBluetoothLock.writeLock().unlock();
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301510 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001511
1512 if (mEnable) {
1513 mEnable = false;
1514 // Send a Bluetooth Restart message
1515 Message restartMsg = mHandler.obtainMessage(
1516 MESSAGE_RESTART_BLUETOOTH_SERVICE);
1517 mHandler.sendMessageDelayed(restartMsg,
1518 SERVICE_RESTART_TIME_MS);
1519 }
1520
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001521 sendBluetoothServiceDownCallback();
Zhihai Xu40874a02012-10-08 17:57:03 -07001522
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001523 // Send BT state broadcast to update
1524 // the BT icon correctly
1525 if ((mState == BluetoothAdapter.STATE_TURNING_ON) ||
Calvin Ona0b91d72016-06-15 17:58:23 -07001526 (mState == BluetoothAdapter.STATE_ON)) {
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001527 bluetoothStateChangeHandler(BluetoothAdapter.STATE_ON,
1528 BluetoothAdapter.STATE_TURNING_OFF);
1529 mState = BluetoothAdapter.STATE_TURNING_OFF;
Zhihai Xu40874a02012-10-08 17:57:03 -07001530 }
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001531 if (mState == BluetoothAdapter.STATE_TURNING_OFF) {
1532 bluetoothStateChangeHandler(BluetoothAdapter.STATE_TURNING_OFF,
1533 BluetoothAdapter.STATE_OFF);
1534 }
1535
1536 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
1537 mState = BluetoothAdapter.STATE_OFF;
fredc649fe492012-04-19 01:07:18 -07001538 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001539 }
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301540 case MESSAGE_RESTART_BLUETOOTH_SERVICE:
1541 {
Marie Janssencb21ad72016-12-13 10:51:02 -08001542 Slog.d(TAG, "MESSAGE_RESTART_BLUETOOTH_SERVICE");
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301543 /* Enable without persisting the setting as
1544 it doesnt change when IBluetooth
1545 service restarts */
Zhihai Xu40874a02012-10-08 17:57:03 -07001546 mEnable = true;
Zhihai Xu401202b2012-12-03 11:36:21 -08001547 handleEnable(mQuietEnable);
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301548 break;
1549 }
Marie Janssencb21ad72016-12-13 10:51:02 -08001550 case MESSAGE_TIMEOUT_BIND: {
1551 Slog.e(TAG, "MESSAGE_TIMEOUT_BIND");
1552 mBluetoothLock.writeLock().lock();
1553 mBinding = false;
1554 mBluetoothLock.writeLock().unlock();
1555 break;
1556 }
fredc0f420372012-04-12 00:02:00 -07001557 case MESSAGE_TIMEOUT_UNBIND:
1558 {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001559 Slog.e(TAG, "MESSAGE_TIMEOUT_UNBIND");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001560 mBluetoothLock.writeLock().lock();
1561 mUnbinding = false;
1562 mBluetoothLock.writeLock().unlock();
fredc649fe492012-04-19 01:07:18 -07001563 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001564 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001565
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001566 case MESSAGE_USER_SWITCHED: {
1567 if (DBG) Slog.d(TAG, "MESSAGE_USER_SWITCHED");
Zhihai Xu40874a02012-10-08 17:57:03 -07001568 mHandler.removeMessages(MESSAGE_USER_SWITCHED);
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001569
Zhihai Xu40874a02012-10-08 17:57:03 -07001570 /* disable and enable BT when detect a user switch */
1571 if (mEnable && mBluetooth != null) {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001572 try {
1573 mBluetoothLock.readLock().lock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001574 if (mBluetooth != null) {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001575 mBluetooth.unregisterCallback(mBluetoothCallback);
Zhihai Xu40874a02012-10-08 17:57:03 -07001576 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001577 } catch (RemoteException re) {
1578 Slog.e(TAG, "Unable to unregister", re);
1579 } finally {
1580 mBluetoothLock.readLock().unlock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001581 }
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001582
1583 if (mState == BluetoothAdapter.STATE_TURNING_OFF) {
1584 // MESSAGE_USER_SWITCHED happened right after MESSAGE_ENABLE
1585 bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_OFF);
1586 mState = BluetoothAdapter.STATE_OFF;
1587 }
1588 if (mState == BluetoothAdapter.STATE_OFF) {
1589 bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_TURNING_ON);
1590 mState = BluetoothAdapter.STATE_TURNING_ON;
1591 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001592
1593 waitForOnOff(true, false);
1594
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001595 if (mState == BluetoothAdapter.STATE_TURNING_ON) {
1596 bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_ON);
1597 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001598
Benjamin Franze8b98922014-11-12 15:57:54 +00001599 unbindAllBluetoothProfileServices();
Zhihai Xu40874a02012-10-08 17:57:03 -07001600 // disable
Zhihai Xu401202b2012-12-03 11:36:21 -08001601 handleDisable();
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001602 // Pbap service need receive STATE_TURNING_OFF intent to close
1603 bluetoothStateChangeHandler(BluetoothAdapter.STATE_ON,
1604 BluetoothAdapter.STATE_TURNING_OFF);
Zhihai Xu40874a02012-10-08 17:57:03 -07001605
Pavlin Radoslavov41401112016-06-27 15:25:18 -07001606 boolean didDisableTimeout = !waitForOnOff(false, true);
Zhihai Xu40874a02012-10-08 17:57:03 -07001607
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001608 bluetoothStateChangeHandler(BluetoothAdapter.STATE_TURNING_OFF,
Zhihai Xu40874a02012-10-08 17:57:03 -07001609 BluetoothAdapter.STATE_OFF);
Zhihai Xu40874a02012-10-08 17:57:03 -07001610 sendBluetoothServiceDownCallback();
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001611
Pavlin Radoslavove957a8a2016-05-24 15:28:41 -07001612 try {
1613 mBluetoothLock.writeLock().lock();
1614 if (mBluetooth != null) {
1615 mBluetooth = null;
1616 // Unbind
1617 mContext.unbindService(mConnection);
1618 }
1619 mBluetoothGatt = null;
1620 } finally {
1621 mBluetoothLock.writeLock().unlock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001622 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001623
Pavlin Radoslavov41401112016-06-27 15:25:18 -07001624 //
1625 // If disabling Bluetooth times out, wait for an
1626 // additional amount of time to ensure the process is
1627 // shut down completely before attempting to restart.
1628 //
1629 if (didDisableTimeout) {
1630 SystemClock.sleep(3000);
1631 } else {
1632 SystemClock.sleep(100);
1633 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001634
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001635 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
1636 mState = BluetoothAdapter.STATE_OFF;
Zhihai Xu40874a02012-10-08 17:57:03 -07001637 // enable
Zhihai Xu401202b2012-12-03 11:36:21 -08001638 handleEnable(mQuietEnable);
John Spurlock8a985d22014-02-25 09:40:05 -05001639 } else if (mBinding || mBluetooth != null) {
Zhihai Xu40874a02012-10-08 17:57:03 -07001640 Message userMsg = mHandler.obtainMessage(MESSAGE_USER_SWITCHED);
1641 userMsg.arg2 = 1 + msg.arg2;
Marie Janssencb21ad72016-12-13 10:51:02 -08001642 // if user is switched when service is binding retry after a delay
Zhihai Xu40874a02012-10-08 17:57:03 -07001643 mHandler.sendMessageDelayed(userMsg, USER_SWITCHED_TIME_MS);
1644 if (DBG) {
Marie Janssencb21ad72016-12-13 10:51:02 -08001645 Slog.d(TAG, "Retry MESSAGE_USER_SWITCHED " + userMsg.arg2);
Zhihai Xu40874a02012-10-08 17:57:03 -07001646 }
John Spurlock8a985d22014-02-25 09:40:05 -05001647 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001648 break;
1649 }
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001650 case MESSAGE_USER_UNLOCKED: {
1651 if (DBG) Slog.d(TAG, "MESSAGE_USER_UNLOCKED");
1652 mHandler.removeMessages(MESSAGE_USER_SWITCHED);
1653
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001654 if (mEnable && !mBinding && (mBluetooth == null)) {
1655 // We should be connected, but we gave up for some
1656 // reason; maybe the Bluetooth service wasn't encryption
1657 // aware, so try binding again.
1658 if (DBG) Slog.d(TAG, "Enabled but not bound; retrying after unlock");
1659 handleEnable(mQuietEnable);
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001660 }
1661 }
fredc0f420372012-04-12 00:02:00 -07001662 }
1663 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001664 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001665
Zhihai Xu401202b2012-12-03 11:36:21 -08001666 private void handleEnable(boolean quietMode) {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001667 mQuietEnable = quietMode;
1668
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001669 try {
1670 mBluetoothLock.writeLock().lock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001671 if ((mBluetooth == null) && (!mBinding)) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001672 //Start bind timeout and bind
1673 Message timeoutMsg=mHandler.obtainMessage(MESSAGE_TIMEOUT_BIND);
1674 mHandler.sendMessageDelayed(timeoutMsg,TIMEOUT_BIND_MS);
Matthew Xiecdce0b92012-07-12 19:06:15 -07001675 Intent i = new Intent(IBluetooth.class.getName());
Dianne Hackbornce09f5a2014-10-10 15:03:13 -07001676 if (!doBind(i, mConnection,Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT,
1677 UserHandle.CURRENT)) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001678 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
Zhihai Xu40874a02012-10-08 17:57:03 -07001679 } else {
1680 mBinding = true;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001681 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001682 } else if (mBluetooth != null) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001683 //Enable bluetooth
1684 try {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001685 if (!mQuietEnable) {
1686 if(!mBluetooth.enable()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001687 Slog.e(TAG,"IBluetooth.enable() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001688 }
1689 }
1690 else {
1691 if(!mBluetooth.enableNoAutoConnect()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001692 Slog.e(TAG,"IBluetooth.enableNoAutoConnect() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001693 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001694 }
1695 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001696 Slog.e(TAG,"Unable to call enable()",e);
Matthew Xiecdce0b92012-07-12 19:06:15 -07001697 }
1698 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001699 } finally {
1700 mBluetoothLock.writeLock().unlock();
Matthew Xiecdce0b92012-07-12 19:06:15 -07001701 }
1702 }
1703
Dianne Hackborn221ea892013-08-04 16:50:16 -07001704 boolean doBind(Intent intent, ServiceConnection conn, int flags, UserHandle user) {
1705 ComponentName comp = intent.resolveSystemService(mContext.getPackageManager(), 0);
1706 intent.setComponent(comp);
1707 if (comp == null || !mContext.bindServiceAsUser(intent, conn, flags, user)) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001708 Slog.e(TAG, "Fail to bind to: " + intent);
Dianne Hackborn221ea892013-08-04 16:50:16 -07001709 return false;
1710 }
1711 return true;
1712 }
1713
Zhihai Xu401202b2012-12-03 11:36:21 -08001714 private void handleDisable() {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001715 try {
1716 mBluetoothLock.readLock().lock();
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001717 if (mBluetooth != null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001718 if (DBG) Slog.d(TAG,"Sending off request.");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001719 if (!mBluetooth.disable()) {
1720 Slog.e(TAG,"IBluetooth.disable() returned false");
Matthew Xiecdce0b92012-07-12 19:06:15 -07001721 }
1722 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001723 } catch (RemoteException e) {
1724 Slog.e(TAG,"Unable to call disable()",e);
1725 } finally {
1726 mBluetoothLock.readLock().unlock();
Matthew Xiecdce0b92012-07-12 19:06:15 -07001727 }
1728 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001729
1730 private boolean checkIfCallerIsForegroundUser() {
1731 int foregroundUser;
1732 int callingUser = UserHandle.getCallingUserId();
Martijn Coenen8385c5a2012-11-29 10:14:16 -08001733 int callingUid = Binder.getCallingUid();
Zhihai Xu40874a02012-10-08 17:57:03 -07001734 long callingIdentity = Binder.clearCallingIdentity();
Benjamin Franze8b98922014-11-12 15:57:54 +00001735 UserManager um = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
1736 UserInfo ui = um.getProfileParent(callingUser);
1737 int parentUser = (ui != null) ? ui.id : UserHandle.USER_NULL;
Martijn Coenen8385c5a2012-11-29 10:14:16 -08001738 int callingAppId = UserHandle.getAppId(callingUid);
Zhihai Xu40874a02012-10-08 17:57:03 -07001739 boolean valid = false;
1740 try {
1741 foregroundUser = ActivityManager.getCurrentUser();
Martijn Coenen8385c5a2012-11-29 10:14:16 -08001742 valid = (callingUser == foregroundUser) ||
Benjamin Franze8b98922014-11-12 15:57:54 +00001743 parentUser == foregroundUser ||
Adrian Roosbd9a9a52014-08-18 15:31:57 +02001744 callingAppId == Process.NFC_UID ||
1745 callingAppId == mSystemUiUid;
Marie Janssencb21ad72016-12-13 10:51:02 -08001746 if (DBG && !valid) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001747 Slog.d(TAG, "checkIfCallerIsForegroundUser: valid=" + valid
Zhihai Xu40874a02012-10-08 17:57:03 -07001748 + " callingUser=" + callingUser
Benjamin Franze8b98922014-11-12 15:57:54 +00001749 + " parentUser=" + parentUser
Zhihai Xu40874a02012-10-08 17:57:03 -07001750 + " foregroundUser=" + foregroundUser);
1751 }
1752 } finally {
1753 Binder.restoreCallingIdentity(callingIdentity);
1754 }
1755 return valid;
1756 }
1757
Nitin Arorad055adb2015-03-02 15:03:51 -08001758 private void sendBleStateChanged(int prevState, int newState) {
Marie Janssencb21ad72016-12-13 10:51:02 -08001759 if (DBG) Slog.d(TAG,"Sending BLE State Change: " + BluetoothAdapter.nameForState(prevState) +
1760 " > " + BluetoothAdapter.nameForState(newState));
Nitin Arorad055adb2015-03-02 15:03:51 -08001761 // Send broadcast message to everyone else
1762 Intent intent = new Intent(BluetoothAdapter.ACTION_BLE_STATE_CHANGED);
1763 intent.putExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE, prevState);
1764 intent.putExtra(BluetoothAdapter.EXTRA_STATE, newState);
1765 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1766 mContext.sendBroadcastAsUser(intent, UserHandle.ALL, BLUETOOTH_PERM);
1767 }
1768
Zhihai Xu40874a02012-10-08 17:57:03 -07001769 private void bluetoothStateChangeHandler(int prevState, int newState) {
Nitin Arorad055adb2015-03-02 15:03:51 -08001770 boolean isStandardBroadcast = true;
Marie Janssencb21ad72016-12-13 10:51:02 -08001771 if (prevState == newState) { // No change. Nothing to do.
1772 return;
1773 }
1774 // Notify all proxy objects first of adapter state change
1775 if (newState == BluetoothAdapter.STATE_BLE_ON ||
1776 newState == BluetoothAdapter.STATE_OFF) {
1777 boolean intermediate_off = (prevState == BluetoothAdapter.STATE_TURNING_OFF
1778 && newState == BluetoothAdapter.STATE_BLE_ON);
Zhihai Xu40874a02012-10-08 17:57:03 -07001779
Marie Janssencb21ad72016-12-13 10:51:02 -08001780 if (newState == BluetoothAdapter.STATE_OFF) {
1781 // If Bluetooth is off, send service down event to proxy objects, and unbind
1782 if (DBG) Slog.d(TAG, "Bluetooth is complete send Service Down");
1783 sendBluetoothServiceDownCallback();
1784 unbindAndFinish();
Nitin Arorad055adb2015-03-02 15:03:51 -08001785 sendBleStateChanged(prevState, newState);
Marie Janssencb21ad72016-12-13 10:51:02 -08001786 // Don't broadcast as it has already been broadcast before
Nitin Arorad055adb2015-03-02 15:03:51 -08001787 isStandardBroadcast = false;
1788
Marie Janssencb21ad72016-12-13 10:51:02 -08001789 } else if (!intermediate_off) {
1790 // connect to GattService
1791 if (DBG) Slog.d(TAG, "Bluetooth is in LE only mode");
1792 if (mBluetoothGatt != null) {
1793 if (DBG) Slog.d(TAG, "Calling BluetoothGattServiceUp");
1794 onBluetoothGattServiceUp();
1795 } else {
1796 if (DBG) Slog.d(TAG, "Binding Bluetooth GATT service");
1797 if (mContext.getPackageManager().hasSystemFeature(
1798 PackageManager.FEATURE_BLUETOOTH_LE)) {
1799 Intent i = new Intent(IBluetoothGatt.class.getName());
1800 doBind(i, mConnection, Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT, UserHandle.CURRENT);
1801 }
Nitin Arorad055adb2015-03-02 15:03:51 -08001802 }
Marie Janssencb21ad72016-12-13 10:51:02 -08001803 sendBleStateChanged(prevState, newState);
1804 //Don't broadcase this as std intent
1805 isStandardBroadcast = false;
1806
1807 } else if (intermediate_off) {
1808 if (DBG) Slog.d(TAG, "Intermediate off, back to LE only mode");
1809 // For LE only mode, broadcast as is
1810 sendBleStateChanged(prevState, newState);
1811 sendBluetoothStateCallback(false); // BT is OFF for general users
1812 // Broadcast as STATE_OFF
1813 newState = BluetoothAdapter.STATE_OFF;
1814 sendBrEdrDownCallback();
Nitin Arorad055adb2015-03-02 15:03:51 -08001815 }
Marie Janssencb21ad72016-12-13 10:51:02 -08001816 } else if (newState == BluetoothAdapter.STATE_ON) {
1817 boolean isUp = (newState == BluetoothAdapter.STATE_ON);
1818 sendBluetoothStateCallback(isUp);
1819 sendBleStateChanged(prevState, newState);
1820
1821 } else if (newState == BluetoothAdapter.STATE_BLE_TURNING_ON ||
1822 newState == BluetoothAdapter.STATE_BLE_TURNING_OFF ) {
1823 sendBleStateChanged(prevState, newState);
1824 isStandardBroadcast = false;
1825
1826 } else if (newState == BluetoothAdapter.STATE_TURNING_ON ||
1827 newState == BluetoothAdapter.STATE_TURNING_OFF) {
1828 sendBleStateChanged(prevState, newState);
1829 }
1830
1831 if (isStandardBroadcast) {
1832 if (prevState == BluetoothAdapter.STATE_BLE_ON) {
1833 // Show prevState of BLE_ON as OFF to standard users
1834 prevState = BluetoothAdapter.STATE_OFF;
1835 }
1836 Intent intent = new Intent(BluetoothAdapter.ACTION_STATE_CHANGED);
1837 intent.putExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE, prevState);
1838 intent.putExtra(BluetoothAdapter.EXTRA_STATE, newState);
1839 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1840 mContext.sendBroadcastAsUser(intent, UserHandle.ALL, BLUETOOTH_PERM);
Zhihai Xu40874a02012-10-08 17:57:03 -07001841 }
1842 }
1843
1844 /**
1845 * if on is true, wait for state become ON
1846 * if off is true, wait for state become OFF
1847 * if both on and off are false, wait for state not ON
1848 */
1849 private boolean waitForOnOff(boolean on, boolean off) {
1850 int i = 0;
1851 while (i < 10) {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001852 try {
1853 mBluetoothLock.readLock().lock();
1854 if (mBluetooth == null) break;
1855 if (on) {
1856 if (mBluetooth.getState() == BluetoothAdapter.STATE_ON) return true;
1857 } else if (off) {
1858 if (mBluetooth.getState() == BluetoothAdapter.STATE_OFF) return true;
1859 } else {
1860 if (mBluetooth.getState() != BluetoothAdapter.STATE_ON) return true;
Zhihai Xu40874a02012-10-08 17:57:03 -07001861 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001862 } catch (RemoteException e) {
1863 Slog.e(TAG, "getState()", e);
1864 break;
1865 } finally {
1866 mBluetoothLock.readLock().unlock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001867 }
1868 if (on || off) {
1869 SystemClock.sleep(300);
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07001870 } else {
Zhihai Xu40874a02012-10-08 17:57:03 -07001871 SystemClock.sleep(50);
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07001872 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001873 i++;
1874 }
Jeff Sharkey67609c72016-03-05 14:29:13 -07001875 Slog.e(TAG,"waitForOnOff time out");
Zhihai Xu40874a02012-10-08 17:57:03 -07001876 return false;
1877 }
Zhihai Xu681ae7f2012-11-12 15:14:18 -08001878
Zhihai Xu401202b2012-12-03 11:36:21 -08001879 private void sendDisableMsg() {
1880 mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_DISABLE));
1881 }
1882
1883 private void sendEnableMsg(boolean quietMode) {
1884 mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_ENABLE,
1885 quietMode ? 1 : 0, 0));
1886 }
1887
Marie Janssen2977c3e2016-11-09 12:01:24 -08001888 private void recoverBluetoothServiceFromError(boolean clearBle) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001889 Slog.e(TAG,"recoverBluetoothServiceFromError");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001890 try {
1891 mBluetoothLock.readLock().lock();
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001892 if (mBluetooth != null) {
1893 //Unregister callback object
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001894 mBluetooth.unregisterCallback(mBluetoothCallback);
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001895 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001896 } catch (RemoteException re) {
1897 Slog.e(TAG, "Unable to unregister", re);
1898 } finally {
1899 mBluetoothLock.readLock().unlock();
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001900 }
1901
1902 SystemClock.sleep(500);
1903
1904 // disable
1905 handleDisable();
1906
1907 waitForOnOff(false, true);
1908
1909 sendBluetoothServiceDownCallback();
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001910
Pavlin Radoslavove957a8a2016-05-24 15:28:41 -07001911 try {
1912 mBluetoothLock.writeLock().lock();
1913 if (mBluetooth != null) {
1914 mBluetooth = null;
1915 // Unbind
1916 mContext.unbindService(mConnection);
1917 }
1918 mBluetoothGatt = null;
1919 } finally {
1920 mBluetoothLock.writeLock().unlock();
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001921 }
1922
1923 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
1924 mState = BluetoothAdapter.STATE_OFF;
1925
Marie Janssen2977c3e2016-11-09 12:01:24 -08001926 if (clearBle) {
1927 clearBleApps();
1928 }
1929
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001930 mEnable = false;
1931
1932 if (mErrorRecoveryRetryCounter++ < MAX_ERROR_RESTART_RETRIES) {
1933 // Send a Bluetooth Restart message to reenable bluetooth
1934 Message restartMsg = mHandler.obtainMessage(
1935 MESSAGE_RESTART_BLUETOOTH_SERVICE);
1936 mHandler.sendMessageDelayed(restartMsg, ERROR_RESTART_TIME_MS);
1937 } else {
1938 // todo: notify user to power down and power up phone to make bluetooth work.
1939 }
1940 }
Mike Lockwood726d4de2014-10-28 14:06:28 -07001941
Lenka Trochtova13a05192016-12-02 12:19:39 +01001942 private boolean isBluetoothDisallowed() {
1943 long callingIdentity = Binder.clearCallingIdentity();
1944 try {
1945 return mContext.getSystemService(UserManager.class)
1946 .hasUserRestriction(UserManager.DISALLOW_BLUETOOTH, UserHandle.SYSTEM);
1947 } finally {
1948 Binder.restoreCallingIdentity(callingIdentity);
1949 }
1950 }
1951
Mike Lockwood726d4de2014-10-28 14:06:28 -07001952 @Override
Pavlin Radoslavov6e8faff2016-02-23 11:54:37 -08001953 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1954 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DUMP, TAG);
1955 String errorMsg = null;
1956 if (mBluetoothBinder == null) {
1957 errorMsg = "Bluetooth Service not connected";
1958 } else {
1959 try {
1960 mBluetoothBinder.dump(fd, args);
1961 } catch (RemoteException re) {
1962 errorMsg = "RemoteException while calling Bluetooth Service";
1963 }
Mike Lockwood726d4de2014-10-28 14:06:28 -07001964 }
Pavlin Radoslavov6e8faff2016-02-23 11:54:37 -08001965 if (errorMsg != null) {
1966 // Silently return if we are extracting metrics in Protobuf format
1967 if ((args.length > 0) && args[0].startsWith("--proto"))
1968 return;
1969 writer.println(errorMsg);
1970 }
Mike Lockwood726d4de2014-10-28 14:06:28 -07001971 }
fredc0f420372012-04-12 00:02:00 -07001972}