blob: b0c560353d8a1554d91ff4d575f8535215364324 [file] [log] [blame]
fredc0f420372012-04-12 00:02:00 -07001/*
Zhihai Xufa0fd392012-10-23 17:31:56 -07002 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
fredc0f420372012-04-12 00:02:00 -070015 */
16
17package com.android.server;
18
Svet Ganov408abf72015-05-12 19:13:36 -070019import android.Manifest;
Zhihai Xu40874a02012-10-08 17:57:03 -070020import android.app.ActivityManager;
fredc0f420372012-04-12 00:02:00 -070021import android.bluetooth.BluetoothAdapter;
Benjamin Franze8b98922014-11-12 15:57:54 +000022import android.bluetooth.BluetoothProfile;
fredc0f420372012-04-12 00:02:00 -070023import android.bluetooth.IBluetooth;
fredcbf072a72012-05-09 16:52:50 -070024import android.bluetooth.IBluetoothCallback;
Wei Wange4a744b2015-06-11 17:50:29 -070025import android.bluetooth.IBluetoothGatt;
Benjamin Franze8b98922014-11-12 15:57:54 +000026import android.bluetooth.IBluetoothHeadset;
fredc0f420372012-04-12 00:02:00 -070027import android.bluetooth.IBluetoothManager;
28import android.bluetooth.IBluetoothManagerCallback;
Benjamin Franze8b98922014-11-12 15:57:54 +000029import android.bluetooth.IBluetoothProfileServiceConnection;
fredc0f420372012-04-12 00:02:00 -070030import android.bluetooth.IBluetoothStateChangeCallback;
Svet Ganov77df6f32016-08-17 11:46:34 -070031import android.content.ActivityNotFoundException;
fredc0f420372012-04-12 00:02:00 -070032import android.content.BroadcastReceiver;
33import android.content.ComponentName;
34import android.content.ContentResolver;
35import android.content.Context;
36import android.content.Intent;
37import android.content.IntentFilter;
38import android.content.ServiceConnection;
Svetoslav Ganovac69be52016-06-29 17:31:44 -070039import android.content.pm.ApplicationInfo;
Matthew Xie32ab77b2013-05-08 19:26:57 -070040import android.content.pm.PackageManager;
Benjamin Franze8b98922014-11-12 15:57:54 +000041import android.content.pm.UserInfo;
Wei Wange4a744b2015-06-11 17:50:29 -070042import android.database.ContentObserver;
Zhihai Xu40874a02012-10-08 17:57:03 -070043import android.os.Binder;
Svetoslav Ganovac69be52016-06-29 17:31:44 -070044import android.os.Build;
Lenka Trochtova63d5e4a72016-12-02 12:19:39 +010045import android.os.Bundle;
fredc0f420372012-04-12 00:02:00 -070046import android.os.Handler;
fredc0f420372012-04-12 00:02:00 -070047import android.os.IBinder;
Zhihai Xu40874a02012-10-08 17:57:03 -070048import android.os.Looper;
fredc0f420372012-04-12 00:02:00 -070049import android.os.Message;
Zhihai Xu40874a02012-10-08 17:57:03 -070050import android.os.Process;
fredcd6883532012-04-25 17:46:13 -070051import android.os.RemoteCallbackList;
fredc0f420372012-04-12 00:02:00 -070052import android.os.RemoteException;
Zhihai Xu40874a02012-10-08 17:57:03 -070053import android.os.SystemClock;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070054import android.os.UserHandle;
Benjamin Franze8b98922014-11-12 15:57:54 +000055import android.os.UserManager;
Lenka Trochtova63d5e4a72016-12-02 12:19:39 +010056import android.os.UserManagerInternal;
57import android.os.UserManagerInternal.UserRestrictionsListener;
fredc0f420372012-04-12 00:02:00 -070058import android.provider.Settings;
Wei Wang67d84162015-04-26 17:04:29 -070059import android.provider.Settings.SettingNotFoundException;
Jeff Sharkey67609c72016-03-05 14:29:13 -070060import android.util.Slog;
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -070061import java.util.concurrent.locks.ReentrantReadWriteLock;
Mike Lockwood726d4de2014-10-28 14:06:28 -070062
63import java.io.FileDescriptor;
64import java.io.PrintWriter;
Marie Janssen2977c3e2016-11-09 12:01:24 -080065import java.util.concurrent.ConcurrentHashMap;
Benjamin Franze8b98922014-11-12 15:57:54 +000066import java.util.HashMap;
67import java.util.Map;
Miao Chou658bf2f2015-06-26 17:14:35 -070068
fredc0f420372012-04-12 00:02:00 -070069class BluetoothManagerService extends IBluetoothManager.Stub {
70 private static final String TAG = "BluetoothManagerService";
Pavlin Radoslavov41401112016-06-27 15:25:18 -070071 private static final boolean DBG = true;
fredc0f420372012-04-12 00:02:00 -070072
fredc0f420372012-04-12 00:02:00 -070073 private static final String BLUETOOTH_ADMIN_PERM = android.Manifest.permission.BLUETOOTH_ADMIN;
74 private static final String BLUETOOTH_PERM = android.Manifest.permission.BLUETOOTH;
fredc0f420372012-04-12 00:02:00 -070075 private static final String ACTION_SERVICE_STATE_CHANGED="com.android.bluetooth.btservice.action.STATE_CHANGED";
76 private static final String EXTRA_ACTION="action";
Zhihai Xud31c3222012-10-31 16:08:57 -070077 private static final String SECURE_SETTINGS_BLUETOOTH_ADDR_VALID="bluetooth_addr_valid";
fredc0f420372012-04-12 00:02:00 -070078 private static final String SECURE_SETTINGS_BLUETOOTH_ADDRESS="bluetooth_address";
79 private static final String SECURE_SETTINGS_BLUETOOTH_NAME="bluetooth_name";
fredc0f420372012-04-12 00:02:00 -070080 private static final int TIMEOUT_BIND_MS = 3000; //Maximum msec to wait for a bind
81 private static final int TIMEOUT_SAVE_MS = 500; //Maximum msec to wait for a save
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +053082 //Maximum msec to wait for service restart
83 private static final int SERVICE_RESTART_TIME_MS = 200;
Zhihai Xudd9d17d2013-01-08 17:05:58 -080084 //Maximum msec to wait for restart due to error
85 private static final int ERROR_RESTART_TIME_MS = 3000;
Zhihai Xu40874a02012-10-08 17:57:03 -070086 //Maximum msec to delay MESSAGE_USER_SWITCHED
87 private static final int USER_SWITCHED_TIME_MS = 200;
Benjamin Franze8b98922014-11-12 15:57:54 +000088 // Delay for the addProxy function in msec
89 private static final int ADD_PROXY_DELAY_MS = 100;
fredc0f420372012-04-12 00:02:00 -070090
91 private static final int MESSAGE_ENABLE = 1;
92 private static final int MESSAGE_DISABLE = 2;
fredc649fe492012-04-19 01:07:18 -070093 private static final int MESSAGE_REGISTER_ADAPTER = 20;
94 private static final int MESSAGE_UNREGISTER_ADAPTER = 21;
95 private static final int MESSAGE_REGISTER_STATE_CHANGE_CALLBACK = 30;
96 private static final int MESSAGE_UNREGISTER_STATE_CHANGE_CALLBACK = 31;
97 private static final int MESSAGE_BLUETOOTH_SERVICE_CONNECTED = 40;
98 private static final int MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED = 41;
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +053099 private static final int MESSAGE_RESTART_BLUETOOTH_SERVICE = 42;
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -0700100 private static final int MESSAGE_BLUETOOTH_STATE_CHANGE = 60;
101 private static final int MESSAGE_TIMEOUT_BIND = 100;
102 private static final int MESSAGE_TIMEOUT_UNBIND = 101;
Ajay Panicker4bb48302016-03-31 14:14:27 -0700103 private static final int MESSAGE_GET_NAME_AND_ADDRESS = 200;
Zhihai Xu40874a02012-10-08 17:57:03 -0700104 private static final int MESSAGE_USER_SWITCHED = 300;
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -0700105 private static final int MESSAGE_USER_UNLOCKED = 301;
Benjamin Franze8b98922014-11-12 15:57:54 +0000106 private static final int MESSAGE_ADD_PROXY_DELAYED = 400;
107 private static final int MESSAGE_BIND_PROFILE_SERVICE = 401;
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 Ganovac69be52016-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 Trochtova63d5e4a72016-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) {
191 try {
192 disable(null, true);
193 } catch (RemoteException e) {
194 Slog.w(TAG, "Exception when disabling Bluetooth from UserRestrictionsListener",
195 e);
196 }
197 }
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 Janssen9fa24912016-10-18 10:04:24 -0700232 Slog.d(TAG, "Airplane Mode change - current state: " + 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 Janssena80d7452016-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 Ganovac69be52016-06-29 17:31:44 -0700270
Svet Ganov77df6f32016-08-17 11:46:34 -0700271 mPermissionReviewRequired = context.getResources().getBoolean(
Svetoslav Ganovac69be52016-06-29 17:31:44 -0700272 com.android.internal.R.bool.config_permissionReviewRequired);
273
fredc0f420372012-04-12 00:02:00 -0700274 mBluetooth = null;
Marie Janssen9db28eb2016-01-12 16:05:15 -0800275 mBluetoothBinder = null;
Nitin Arorad055adb2015-03-02 15:03:51 -0800276 mBluetoothGatt = null;
fredc0f420372012-04-12 00:02:00 -0700277 mBinding = false;
278 mUnbinding = false;
Zhihai Xu40874a02012-10-08 17:57:03 -0700279 mEnable = false;
280 mState = BluetoothAdapter.STATE_OFF;
Zhihai Xu401202b2012-12-03 11:36:21 -0800281 mQuietEnableExternal = false;
282 mEnableExternal = false;
fredc0f420372012-04-12 00:02:00 -0700283 mAddress = null;
284 mName = null;
Zhihai Xudd9d17d2013-01-08 17:05:58 -0800285 mErrorRecoveryRetryCounter = 0;
fredc0f420372012-04-12 00:02:00 -0700286 mContentResolver = context.getContentResolver();
Wei Wange4a744b2015-06-11 17:50:29 -0700287 // Observe BLE scan only mode settings change.
288 registerForBleScanModeChange();
fredcd6883532012-04-25 17:46:13 -0700289 mCallbacks = new RemoteCallbackList<IBluetoothManagerCallback>();
290 mStateChangeCallbacks = new RemoteCallbackList<IBluetoothStateChangeCallback>();
Miao Chou658bf2f2015-06-26 17:14:35 -0700291 IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_LOCAL_NAME_CHANGED);
Matthew Xie6fde3092012-07-11 17:10:07 -0700292 registerForAirplaneMode(filter);
Dianne Hackbornd83a0962014-05-02 16:28:33 -0700293 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
Matthew Xie6fde3092012-07-11 17:10:07 -0700294 mContext.registerReceiver(mReceiver, filter);
fredc0f420372012-04-12 00:02:00 -0700295 loadStoredNameAndAddress();
Zhihai Xu401202b2012-12-03 11:36:21 -0800296 if (isBluetoothPersistedStateOn()) {
Marie Janssen9fa24912016-10-18 10:04:24 -0700297 if (DBG) Slog.d(TAG, "Startup: Bluetooth persisted state is ON.");
Zhihai Xu401202b2012-12-03 11:36:21 -0800298 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() {
Marie Janssen9fa24912016-10-18 10:04:24 -0700324 int state = Settings.Global.getInt(mContentResolver,
325 Settings.Global.BLUETOOTH_ON, -1);
326 if (DBG) Slog.d(TAG, "Bluetooth persisted state: " + state);
327 return state != BLUETOOTH_OFF;
Zhihai Xu401202b2012-12-03 11:36:21 -0800328 }
329
330 /**
331 * Returns true if the Bluetooth saved state is BLUETOOTH_ON_BLUETOOTH
332 */
333 private final boolean isBluetoothPersistedStateOnBluetooth() {
334 return Settings.Global.getInt(mContentResolver,
Andre Eisenbach8c184312016-09-06 18:03:10 -0700335 Settings.Global.BLUETOOTH_ON, BLUETOOTH_ON_BLUETOOTH) == BLUETOOTH_ON_BLUETOOTH;
fredc649fe492012-04-19 01:07:18 -0700336 }
337
338 /**
339 * Save the Bluetooth on/off state
340 *
341 */
Zhihai Xu401202b2012-12-03 11:36:21 -0800342 private void persistBluetoothSetting(int value) {
Marie Janssen9fa24912016-10-18 10:04:24 -0700343 if (DBG) Slog.d(TAG, "Persisting Bluetooth Setting: " + value);
Jeff Brownbf6f6f92012-09-25 15:03:20 -0700344 Settings.Global.putInt(mContext.getContentResolver(),
345 Settings.Global.BLUETOOTH_ON,
Zhihai Xu401202b2012-12-03 11:36:21 -0800346 value);
fredc649fe492012-04-19 01:07:18 -0700347 }
348
349 /**
350 * Returns true if the Bluetooth Adapter's name and address is
351 * locally cached
352 * @return
353 */
fredc0f420372012-04-12 00:02:00 -0700354 private boolean isNameAndAddressSet() {
355 return mName !=null && mAddress!= null && mName.length()>0 && mAddress.length()>0;
356 }
357
fredc649fe492012-04-19 01:07:18 -0700358 /**
359 * Retrieve the Bluetooth Adapter's name and address and save it in
360 * in the local cache
361 */
fredc0f420372012-04-12 00:02:00 -0700362 private void loadStoredNameAndAddress() {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700363 if (DBG) Slog.d(TAG, "Loading stored name and address");
Zhihai Xud31c3222012-10-31 16:08:57 -0700364 if (mContext.getResources().getBoolean
365 (com.android.internal.R.bool.config_bluetooth_address_validation) &&
366 Settings.Secure.getInt(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDR_VALID, 0) == 0) {
367 // if the valid flag is not set, don't load the address and name
Jeff Sharkey67609c72016-03-05 14:29:13 -0700368 if (DBG) Slog.d(TAG, "invalid bluetooth name and address stored");
Zhihai Xud31c3222012-10-31 16:08:57 -0700369 return;
370 }
fredc0f420372012-04-12 00:02:00 -0700371 mName = Settings.Secure.getString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_NAME);
372 mAddress = Settings.Secure.getString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDRESS);
Jeff Sharkey67609c72016-03-05 14:29:13 -0700373 if (DBG) Slog.d(TAG, "Stored bluetooth Name=" + mName + ",Address=" + mAddress);
fredc0f420372012-04-12 00:02:00 -0700374 }
375
fredc649fe492012-04-19 01:07:18 -0700376 /**
377 * Save the Bluetooth name and address in the persistent store.
378 * Only non-null values will be saved.
379 * @param name
380 * @param address
381 */
fredc0f420372012-04-12 00:02:00 -0700382 private void storeNameAndAddress(String name, String address) {
383 if (name != null) {
384 Settings.Secure.putString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_NAME, name);
fredc0f420372012-04-12 00:02:00 -0700385 mName = name;
Jeff Sharkey67609c72016-03-05 14:29:13 -0700386 if (DBG) Slog.d(TAG,"Stored Bluetooth name: " +
fredc649fe492012-04-19 01:07:18 -0700387 Settings.Secure.getString(mContentResolver,SECURE_SETTINGS_BLUETOOTH_NAME));
fredc0f420372012-04-12 00:02:00 -0700388 }
389
390 if (address != null) {
391 Settings.Secure.putString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDRESS, address);
fredc0f420372012-04-12 00:02:00 -0700392 mAddress=address;
Jeff Sharkey67609c72016-03-05 14:29:13 -0700393 if (DBG) Slog.d(TAG,"Stored Bluetoothaddress: " +
fredc649fe492012-04-19 01:07:18 -0700394 Settings.Secure.getString(mContentResolver,SECURE_SETTINGS_BLUETOOTH_ADDRESS));
fredc0f420372012-04-12 00:02:00 -0700395 }
Zhihai Xud31c3222012-10-31 16:08:57 -0700396
397 if ((name != null) && (address != null)) {
398 Settings.Secure.putInt(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDR_VALID, 1);
399 }
fredc0f420372012-04-12 00:02:00 -0700400 }
401
402 public IBluetooth registerAdapter(IBluetoothManagerCallback callback){
Natalie Silvanovich55db6462014-05-01 16:12:23 -0700403 if (callback == null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700404 Slog.w(TAG, "Callback is null in registerAdapter");
Natalie Silvanovich55db6462014-05-01 16:12:23 -0700405 return null;
406 }
fredc0f420372012-04-12 00:02:00 -0700407 Message msg = mHandler.obtainMessage(MESSAGE_REGISTER_ADAPTER);
408 msg.obj = callback;
409 mHandler.sendMessage(msg);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700410
411 return mBluetooth;
fredc0f420372012-04-12 00:02:00 -0700412 }
413
414 public void unregisterAdapter(IBluetoothManagerCallback callback) {
Natalie Silvanovich55db6462014-05-01 16:12:23 -0700415 if (callback == null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700416 Slog.w(TAG, "Callback is null in unregisterAdapter");
Natalie Silvanovich55db6462014-05-01 16:12:23 -0700417 return;
418 }
fredc0f420372012-04-12 00:02:00 -0700419 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
420 "Need BLUETOOTH permission");
421 Message msg = mHandler.obtainMessage(MESSAGE_UNREGISTER_ADAPTER);
422 msg.obj = callback;
423 mHandler.sendMessage(msg);
424 }
425
426 public void registerStateChangeCallback(IBluetoothStateChangeCallback callback) {
427 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
428 "Need BLUETOOTH permission");
429 Message msg = mHandler.obtainMessage(MESSAGE_REGISTER_STATE_CHANGE_CALLBACK);
430 msg.obj = callback;
431 mHandler.sendMessage(msg);
432 }
433
434 public void unregisterStateChangeCallback(IBluetoothStateChangeCallback callback) {
435 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
436 "Need BLUETOOTH permission");
437 Message msg = mHandler.obtainMessage(MESSAGE_UNREGISTER_STATE_CHANGE_CALLBACK);
438 msg.obj = callback;
439 mHandler.sendMessage(msg);
440 }
441
442 public boolean isEnabled() {
Zhihai Xu6eb76522012-11-29 15:41:04 -0800443 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
444 (!checkIfCallerIsForegroundUser())) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700445 Slog.w(TAG,"isEnabled(): not allowed for non-active and non system user");
Zhihai Xu40874a02012-10-08 17:57:03 -0700446 return false;
447 }
448
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700449 try {
450 mBluetoothLock.readLock().lock();
451 if (mBluetooth != null) return mBluetooth.isEnabled();
452 } catch (RemoteException e) {
453 Slog.e(TAG, "isEnabled()", e);
454 } finally {
455 mBluetoothLock.readLock().unlock();
fredc0f420372012-04-12 00:02:00 -0700456 }
457 return false;
458 }
459
Christine Hallstrom995c90a2016-05-25 15:49:08 -0700460 public int getState() {
461 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
462 (!checkIfCallerIsForegroundUser())) {
463 Slog.w(TAG, "getState(): not allowed for non-active and non system user");
464 return BluetoothAdapter.STATE_OFF;
465 }
466
467 try {
468 mBluetoothLock.readLock().lock();
469 if (mBluetooth != null) return mBluetooth.getState();
470 } catch (RemoteException e) {
471 Slog.e(TAG, "getState()", e);
472 } finally {
473 mBluetoothLock.readLock().unlock();
474 }
475 return BluetoothAdapter.STATE_OFF;
476 }
477
Nitin Arorad055adb2015-03-02 15:03:51 -0800478 class ClientDeathRecipient implements IBinder.DeathRecipient {
479 public void binderDied() {
Marie Janssena80d7452016-10-25 10:47:51 -0700480 if (DBG) Slog.d(TAG, "Binder is dead - unregister Ble App");
Marie Janssen2977c3e2016-11-09 12:01:24 -0800481 if (isBleAppPresent()) {
482 // Nothing to do, another app is here.
483 return;
484 }
485 if (DBG) Slog.d(TAG, "Disabling LE only mode after application crash");
486 try {
487 mBluetoothLock.readLock().lock();
488 if (mBluetooth != null &&
489 mBluetooth.getState() == BluetoothAdapter.STATE_BLE_ON) {
490 mEnable = false;
491 mBluetooth.onBrEdrDown();
Nitin Arorad055adb2015-03-02 15:03:51 -0800492 }
Marie Janssen2977c3e2016-11-09 12:01:24 -0800493 } catch (RemoteException e) {
494 Slog.e(TAG,"Unable to call onBrEdrDown", e);
495 } finally {
496 mBluetoothLock.readLock().unlock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800497 }
498 }
499 }
500
501 /** Internal death rec list */
Marie Janssen2977c3e2016-11-09 12:01:24 -0800502 Map<IBinder, ClientDeathRecipient> mBleApps = new ConcurrentHashMap<IBinder, ClientDeathRecipient>();
Nitin Arorad055adb2015-03-02 15:03:51 -0800503
Wei Wang67d84162015-04-26 17:04:29 -0700504 @Override
505 public boolean isBleScanAlwaysAvailable() {
Marie Janssena80d7452016-10-25 10:47:51 -0700506 if (isAirplaneModeOn() && !mEnable) {
507 return false;
508 }
Wei Wang67d84162015-04-26 17:04:29 -0700509 try {
510 return (Settings.Global.getInt(mContentResolver,
511 Settings.Global.BLE_SCAN_ALWAYS_AVAILABLE)) != 0;
512 } catch (SettingNotFoundException e) {
513 }
514 return false;
515 }
516
Wei Wange4a744b2015-06-11 17:50:29 -0700517 // Monitor change of BLE scan only mode settings.
518 private void registerForBleScanModeChange() {
519 ContentObserver contentObserver = new ContentObserver(null) {
520 @Override
521 public void onChange(boolean selfChange) {
Marie Janssen2977c3e2016-11-09 12:01:24 -0800522 if (isBleScanAlwaysAvailable()) {
523 // Nothing to do
524 return;
525 }
526 // BLE scan is not available.
527 disableBleScanMode();
528 clearBleApps();
529 try {
530 mBluetoothLock.readLock().lock();
531 if (mBluetooth != null) mBluetooth.onBrEdrDown();
532 } catch (RemoteException e) {
533 Slog.e(TAG, "error when disabling bluetooth", e);
534 } finally {
535 mBluetoothLock.readLock().unlock();
Wei Wange4a744b2015-06-11 17:50:29 -0700536 }
537 }
538 };
539
540 mContentResolver.registerContentObserver(
541 Settings.Global.getUriFor(Settings.Global.BLE_SCAN_ALWAYS_AVAILABLE),
542 false, contentObserver);
543 }
544
545 // Disable ble scan only mode.
546 private void disableBleScanMode() {
547 try {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700548 mBluetoothLock.writeLock().lock();
Wei Wange4a744b2015-06-11 17:50:29 -0700549 if (mBluetooth != null && (mBluetooth.getState() != BluetoothAdapter.STATE_ON)) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700550 if (DBG) Slog.d(TAG, "Reseting the mEnable flag for clean disable");
Wei Wange4a744b2015-06-11 17:50:29 -0700551 mEnable = false;
552 }
553 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700554 Slog.e(TAG, "getState()", e);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700555 } finally {
556 mBluetoothLock.writeLock().unlock();
Wei Wange4a744b2015-06-11 17:50:29 -0700557 }
558 }
559
Nitin Arorad055adb2015-03-02 15:03:51 -0800560 public int updateBleAppCount(IBinder token, boolean enable) {
561 if (enable) {
562 ClientDeathRecipient r = mBleApps.get(token);
563 if (r == null) {
564 ClientDeathRecipient deathRec = new ClientDeathRecipient();
565 try {
566 token.linkToDeath(deathRec, 0);
567 } catch (RemoteException ex) {
568 throw new IllegalArgumentException("Wake lock is already dead.");
569 }
570 mBleApps.put(token, deathRec);
Jeff Sharkey67609c72016-03-05 14:29:13 -0700571 if (DBG) Slog.d(TAG, "Registered for death Notification");
Nitin Arorad055adb2015-03-02 15:03:51 -0800572 }
573
574 } else {
575 ClientDeathRecipient r = mBleApps.get(token);
576 if (r != null) {
Wei Wange4a744b2015-06-11 17:50:29 -0700577 // Unregister death recipient as the app goes away.
578 token.unlinkToDeath(r, 0);
Nitin Arorad055adb2015-03-02 15:03:51 -0800579 mBleApps.remove(token);
Jeff Sharkey67609c72016-03-05 14:29:13 -0700580 if (DBG) Slog.d(TAG, "Unregistered for death Notification");
Nitin Arorad055adb2015-03-02 15:03:51 -0800581 }
582 }
Marie Janssen2977c3e2016-11-09 12:01:24 -0800583 int appCount = mBleApps.size();
584 if (DBG) Slog.d(TAG, appCount + " registered Ble Apps");
585 if (appCount == 0 && mEnable) {
Wei Wange4a744b2015-06-11 17:50:29 -0700586 disableBleScanMode();
Nitin Arorad055adb2015-03-02 15:03:51 -0800587 }
Marie Janssen2977c3e2016-11-09 12:01:24 -0800588 return appCount;
Nitin Arorad055adb2015-03-02 15:03:51 -0800589 }
590
Wei Wange4a744b2015-06-11 17:50:29 -0700591 // Clear all apps using BLE scan only mode.
592 private void clearBleApps() {
Marie Janssen2977c3e2016-11-09 12:01:24 -0800593 mBleApps.clear();
Wei Wange4a744b2015-06-11 17:50:29 -0700594 }
595
Nitin Arorad055adb2015-03-02 15:03:51 -0800596 /** @hide*/
597 public boolean isBleAppPresent() {
Marie Janssen2977c3e2016-11-09 12:01:24 -0800598 if (DBG) Slog.d(TAG, "isBleAppPresent() count: " + mBleApps.size());
599 return mBleApps.size() > 0;
Nitin Arorad055adb2015-03-02 15:03:51 -0800600 }
601
602 /**
603 * Action taken when GattService is turned off
604 */
605 private void onBluetoothGattServiceUp() {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700606 if (DBG) Slog.d(TAG,"BluetoothGatt Service is Up");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700607 try {
608 mBluetoothLock.readLock().lock();
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700609 if (isBleAppPresent() == false && mBluetooth != null
610 && mBluetooth.getState() == BluetoothAdapter.STATE_BLE_ON) {
Nitin Arorad055adb2015-03-02 15:03:51 -0800611 mBluetooth.onLeServiceUp();
612
613 // waive WRITE_SECURE_SETTINGS permission check
614 long callingIdentity = Binder.clearCallingIdentity();
615 persistBluetoothSetting(BLUETOOTH_ON_BLUETOOTH);
616 Binder.restoreCallingIdentity(callingIdentity);
617 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700618 } catch (RemoteException e) {
619 Slog.e(TAG,"Unable to call onServiceUp", e);
620 } finally {
621 mBluetoothLock.readLock().unlock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800622 }
623 }
624
625 /**
626 * Inform BluetoothAdapter instances that BREDR part is down
627 * and turn off all service and stack if no LE app needs it
628 */
629 private void sendBrEdrDownCallback() {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700630 if (DBG) Slog.d(TAG,"Calling sendBrEdrDownCallback callbacks");
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700631
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700632 if (mBluetooth == null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700633 Slog.w(TAG, "Bluetooth handle is null");
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700634 return;
635 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800636
637 if (isBleAppPresent() == false) {
638 try {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700639 mBluetoothLock.readLock().lock();
640 if (mBluetooth != null) mBluetooth.onBrEdrDown();
641 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700642 Slog.e(TAG, "Call to onBrEdrDown() failed.", e);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700643 } finally {
644 mBluetoothLock.readLock().unlock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800645 }
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700646 } else {
647 // Need to stay at BLE ON. Disconnect all Gatt connections
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700648 try {
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700649 mBluetoothGatt.unregAll();
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700650 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700651 Slog.e(TAG, "Unable to disconnect all apps.", e);
Nitin Arorad055adb2015-03-02 15:03:51 -0800652 }
653 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800654 }
655
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700656 public boolean enableNoAutoConnect()
657 {
Lenka Trochtova63d5e4a72016-12-02 12:19:39 +0100658 if (isBluetoothDisallowed()) {
659 if (DBG) {
660 Slog.d(TAG, "enableNoAutoConnect(): not enabling - bluetooth disallowed");
661 }
662 return false;
663 }
664
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700665 mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
666 "Need BLUETOOTH ADMIN permission");
Zhihai Xu40874a02012-10-08 17:57:03 -0700667
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700668 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700669 Slog.d(TAG,"enableNoAutoConnect(): mBluetooth =" + mBluetooth +
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700670 " mBinding = " + mBinding);
671 }
Martijn Coenen8385c5a2012-11-29 10:14:16 -0800672 int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
673
674 if (callingAppId != Process.NFC_UID) {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700675 throw new SecurityException("no permission to enable Bluetooth quietly");
676 }
Martijn Coenen8385c5a2012-11-29 10:14:16 -0800677
Zhihai Xu401202b2012-12-03 11:36:21 -0800678 synchronized(mReceiver) {
679 mQuietEnableExternal = true;
680 mEnableExternal = true;
681 sendEnableMsg(true);
682 }
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700683 return true;
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700684 }
Ajay Panicker4bb48302016-03-31 14:14:27 -0700685
Svetoslav Ganovac69be52016-06-29 17:31:44 -0700686 public boolean enable(String packageName) throws RemoteException {
687 final int callingUid = Binder.getCallingUid();
688 final boolean callerSystem = UserHandle.getAppId(callingUid) == Process.SYSTEM_UID;
689
Lenka Trochtova63d5e4a72016-12-02 12:19:39 +0100690 if (isBluetoothDisallowed()) {
691 if (DBG) {
692 Slog.d(TAG,"enable(): not enabling - bluetooth disallowed");
693 }
694 return false;
695 }
696
Svetoslav Ganovac69be52016-06-29 17:31:44 -0700697 if (!callerSystem) {
698 if (!checkIfCallerIsForegroundUser()) {
699 Slog.w(TAG, "enable(): not allowed for non-active and non system user");
700 return false;
701 }
702
703 mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
704 "Need BLUETOOTH ADMIN permission");
705
706 if (!isEnabled() && mPermissionReviewRequired
707 && startConsentUiIfNeeded(packageName, callingUid,
708 BluetoothAdapter.ACTION_REQUEST_ENABLE)) {
709 return false;
710 }
fredcf2458862012-04-16 15:18:27 -0700711 }
712
Zhihai Xu401202b2012-12-03 11:36:21 -0800713 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700714 Slog.d(TAG,"enable(): mBluetooth =" + mBluetooth +
Sanket Agarwal090bf552016-04-21 14:10:55 -0700715 " mBinding = " + mBinding + " mState = " + mState);
716 }
Zhihai Xu401202b2012-12-03 11:36:21 -0800717
718 synchronized(mReceiver) {
719 mQuietEnableExternal = false;
720 mEnableExternal = true;
721 // waive WRITE_SECURE_SETTINGS permission check
Zhihai Xu401202b2012-12-03 11:36:21 -0800722 sendEnableMsg(false);
723 }
Jeff Sharkey67609c72016-03-05 14:29:13 -0700724 if (DBG) Slog.d(TAG, "enable returning");
Zhihai Xu401202b2012-12-03 11:36:21 -0800725 return true;
fredc0f420372012-04-12 00:02:00 -0700726 }
727
Svetoslav Ganovac69be52016-06-29 17:31:44 -0700728 public boolean disable(String packageName, boolean persist) throws RemoteException {
729 final int callingUid = Binder.getCallingUid();
730 final boolean callerSystem = UserHandle.getAppId(callingUid) == Process.SYSTEM_UID;
Zhihai Xu40874a02012-10-08 17:57:03 -0700731
Svetoslav Ganovac69be52016-06-29 17:31:44 -0700732 if (!callerSystem) {
733 if (!checkIfCallerIsForegroundUser()) {
734 Slog.w(TAG, "disable(): not allowed for non-active and non system user");
735 return false;
736 }
737
738 mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
739 "Need BLUETOOTH ADMIN permission");
740
741 if (isEnabled() && mPermissionReviewRequired
742 && startConsentUiIfNeeded(packageName, callingUid,
743 BluetoothAdapter.ACTION_REQUEST_DISABLE)) {
744 return false;
745 }
Zhihai Xu40874a02012-10-08 17:57:03 -0700746 }
747
fredcf2458862012-04-16 15:18:27 -0700748 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700749 Slog.d(TAG,"disable(): mBluetooth = " + mBluetooth +
Matthew Xiecdce0b92012-07-12 19:06:15 -0700750 " mBinding = " + mBinding);
751 }
fredcf2458862012-04-16 15:18:27 -0700752
Zhihai Xu401202b2012-12-03 11:36:21 -0800753 synchronized(mReceiver) {
754 if (persist) {
755 // waive WRITE_SECURE_SETTINGS permission check
756 long callingIdentity = Binder.clearCallingIdentity();
757 persistBluetoothSetting(BLUETOOTH_OFF);
758 Binder.restoreCallingIdentity(callingIdentity);
759 }
760 mEnableExternal = false;
761 sendDisableMsg();
762 }
fredc0f420372012-04-12 00:02:00 -0700763 return true;
764 }
765
Svetoslav Ganovac69be52016-06-29 17:31:44 -0700766 private boolean startConsentUiIfNeeded(String packageName,
767 int callingUid, String intentAction) throws RemoteException {
768 try {
769 // Validate the package only if we are going to use it
770 ApplicationInfo applicationInfo = mContext.getPackageManager()
771 .getApplicationInfoAsUser(packageName,
772 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
773 UserHandle.getUserId(callingUid));
774 if (applicationInfo.uid != callingUid) {
775 throw new SecurityException("Package " + callingUid
776 + " not in uid " + callingUid);
777 }
778
779 // Legacy apps in permission review mode trigger a user prompt
780 if (applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
781 Intent intent = new Intent(intentAction);
Svet Ganov3a037122016-09-01 16:32:13 -0700782 intent.putExtra(Intent.EXTRA_PACKAGE_NAME, packageName);
Svet Ganov77df6f32016-08-17 11:46:34 -0700783 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
784 | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
785 try {
786 mContext.startActivity(intent);
787 } catch (ActivityNotFoundException e) {
788 // Shouldn't happen
789 Slog.e(TAG, "Intent to handle action " + intentAction + " missing");
790 return false;
791 }
Svetoslav Ganovac69be52016-06-29 17:31:44 -0700792 return true;
793 }
794 } catch (PackageManager.NameNotFoundException e) {
795 throw new RemoteException(e.getMessage());
796 }
797 return false;
798 }
799
fredc649fe492012-04-19 01:07:18 -0700800 public void unbindAndFinish() {
fredcf2458862012-04-16 15:18:27 -0700801 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700802 Slog.d(TAG,"unbindAndFinish(): " + mBluetooth +
Matthew Xiecdce0b92012-07-12 19:06:15 -0700803 " mBinding = " + mBinding);
fredcf2458862012-04-16 15:18:27 -0700804 }
805
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700806 try {
807 mBluetoothLock.writeLock().lock();
fredc0f420372012-04-12 00:02:00 -0700808 if (mUnbinding) return;
809 mUnbinding = true;
Pavlin Radoslavove47ec142016-06-01 22:25:18 -0700810 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
Pavlin Radoslavov74f60c02016-09-21 17:28:11 -0700811 mHandler.removeMessages(MESSAGE_BIND_PROFILE_SERVICE);
Zhihai Xu40874a02012-10-08 17:57:03 -0700812 if (mBluetooth != null) {
Andre Eisenbach305fdab2015-11-11 21:43:26 -0800813 //Unregister callback object
814 try {
815 mBluetooth.unregisterCallback(mBluetoothCallback);
816 } catch (RemoteException re) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700817 Slog.e(TAG, "Unable to unregister BluetoothCallback",re);
fredcbf072a72012-05-09 16:52:50 -0700818 }
Andre Eisenbach305fdab2015-11-11 21:43:26 -0800819
Jeff Sharkey67609c72016-03-05 14:29:13 -0700820 if (DBG) Slog.d(TAG, "Sending unbind request.");
Marie Janssen9db28eb2016-01-12 16:05:15 -0800821 mBluetoothBinder = null;
fredcd6883532012-04-25 17:46:13 -0700822 mBluetooth = null;
823 //Unbind
fredc0f420372012-04-12 00:02:00 -0700824 mContext.unbindService(mConnection);
fredcd6883532012-04-25 17:46:13 -0700825 mUnbinding = false;
Zhihai Xu40874a02012-10-08 17:57:03 -0700826 mBinding = false;
fredcf2458862012-04-16 15:18:27 -0700827 } else {
828 mUnbinding=false;
fredc0f420372012-04-12 00:02:00 -0700829 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800830 mBluetoothGatt = null;
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700831 } finally {
832 mBluetoothLock.writeLock().unlock();
fredc0f420372012-04-12 00:02:00 -0700833 }
834 }
835
Matthew Xieddf7e472013-03-01 18:41:02 -0800836 public IBluetoothGatt getBluetoothGatt() {
837 // sync protection
838 return mBluetoothGatt;
839 }
840
Benjamin Franze8b98922014-11-12 15:57:54 +0000841 @Override
842 public boolean bindBluetoothProfileService(int bluetoothProfile,
843 IBluetoothProfileServiceConnection proxy) {
844 if (!mEnable) {
845 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700846 Slog.d(TAG, "Trying to bind to profile: " + bluetoothProfile +
Benjamin Franze8b98922014-11-12 15:57:54 +0000847 ", while Bluetooth was disabled");
848 }
849 return false;
850 }
851 synchronized (mProfileServices) {
852 ProfileServiceConnections psc = mProfileServices.get(new Integer(bluetoothProfile));
853 if (psc == null) {
854 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700855 Slog.d(TAG, "Creating new ProfileServiceConnections object for"
Benjamin Franze8b98922014-11-12 15:57:54 +0000856 + " profile: " + bluetoothProfile);
857 }
Benjamin Franz5b614592014-12-09 18:58:45 +0000858
859 if (bluetoothProfile != BluetoothProfile.HEADSET) return false;
860
861 Intent intent = new Intent(IBluetoothHeadset.class.getName());
Benjamin Franze8b98922014-11-12 15:57:54 +0000862 psc = new ProfileServiceConnections(intent);
Benjamin Franz5b614592014-12-09 18:58:45 +0000863 if (!psc.bindService()) return false;
864
Benjamin Franze8b98922014-11-12 15:57:54 +0000865 mProfileServices.put(new Integer(bluetoothProfile), psc);
Benjamin Franze8b98922014-11-12 15:57:54 +0000866 }
867 }
868
869 // Introducing a delay to give the client app time to prepare
870 Message addProxyMsg = mHandler.obtainMessage(MESSAGE_ADD_PROXY_DELAYED);
871 addProxyMsg.arg1 = bluetoothProfile;
872 addProxyMsg.obj = proxy;
873 mHandler.sendMessageDelayed(addProxyMsg, ADD_PROXY_DELAY_MS);
874 return true;
875 }
876
877 @Override
878 public void unbindBluetoothProfileService(int bluetoothProfile,
879 IBluetoothProfileServiceConnection proxy) {
880 synchronized (mProfileServices) {
881 ProfileServiceConnections psc = mProfileServices.get(new Integer(bluetoothProfile));
882 if (psc == null) {
883 return;
884 }
885 psc.removeProxy(proxy);
886 }
887 }
888
889 private void unbindAllBluetoothProfileServices() {
890 synchronized (mProfileServices) {
891 for (Integer i : mProfileServices.keySet()) {
892 ProfileServiceConnections psc = mProfileServices.get(i);
Benjamin Franz5b614592014-12-09 18:58:45 +0000893 try {
894 mContext.unbindService(psc);
895 } catch (IllegalArgumentException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700896 Slog.e(TAG, "Unable to unbind service with intent: " + psc.mIntent, e);
Benjamin Franz5b614592014-12-09 18:58:45 +0000897 }
Benjamin Franze8b98922014-11-12 15:57:54 +0000898 psc.removeAllProxies();
899 }
900 mProfileServices.clear();
901 }
902 }
903
904 /**
Miao Chou658bf2f2015-06-26 17:14:35 -0700905 * Send enable message and set adapter name and address. Called when the boot phase becomes
906 * PHASE_SYSTEM_SERVICES_READY.
907 */
908 public void handleOnBootPhase() {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700909 if (DBG) Slog.d(TAG, "Bluetooth boot completed");
Lenka Trochtova63d5e4a72016-12-02 12:19:39 +0100910 UserManagerInternal userManagerInternal =
911 LocalServices.getService(UserManagerInternal.class);
912 userManagerInternal.addUserRestrictionsListener(mUserRestrictionsListener);
913 if (isBluetoothDisallowed()) {
914 return;
915 }
Miao Chou658bf2f2015-06-26 17:14:35 -0700916 if (mEnableExternal && isBluetoothPersistedStateOnBluetooth()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700917 if (DBG) Slog.d(TAG, "Auto-enabling Bluetooth.");
Miao Chou658bf2f2015-06-26 17:14:35 -0700918 sendEnableMsg(mQuietEnableExternal);
Ajay Panickerbf796d82016-03-11 13:47:20 -0800919 } else if (!isNameAndAddressSet()) {
920 if (DBG) Slog.d(TAG, "Getting adapter name and address");
Ajay Panicker4bb48302016-03-31 14:14:27 -0700921 Message getMsg = mHandler.obtainMessage(MESSAGE_GET_NAME_AND_ADDRESS);
922 mHandler.sendMessage(getMsg);
Miao Chou658bf2f2015-06-26 17:14:35 -0700923 }
Miao Chou658bf2f2015-06-26 17:14:35 -0700924 }
925
926 /**
927 * Called when switching to a different foreground user.
928 */
929 public void handleOnSwitchUser(int userHandle) {
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -0700930 if (DBG) Slog.d(TAG, "User " + userHandle + " switched");
931 mHandler.obtainMessage(MESSAGE_USER_SWITCHED, userHandle, 0).sendToTarget();
932 }
933
934 /**
935 * Called when user is unlocked.
936 */
937 public void handleOnUnlockUser(int userHandle) {
938 if (DBG) Slog.d(TAG, "User " + userHandle + " unlocked");
939 mHandler.obtainMessage(MESSAGE_USER_UNLOCKED, userHandle, 0).sendToTarget();
Miao Chou658bf2f2015-06-26 17:14:35 -0700940 }
941
942 /**
Benjamin Franze8b98922014-11-12 15:57:54 +0000943 * This class manages the clients connected to a given ProfileService
944 * and maintains the connection with that service.
945 */
946 final private class ProfileServiceConnections implements ServiceConnection,
947 IBinder.DeathRecipient {
948 final RemoteCallbackList<IBluetoothProfileServiceConnection> mProxies =
949 new RemoteCallbackList <IBluetoothProfileServiceConnection>();
950 IBinder mService;
951 ComponentName mClassName;
952 Intent mIntent;
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700953 boolean mInvokingProxyCallbacks = false;
Benjamin Franze8b98922014-11-12 15:57:54 +0000954
955 ProfileServiceConnections(Intent intent) {
956 mService = null;
957 mClassName = null;
958 mIntent = intent;
959 }
960
Benjamin Franz5b614592014-12-09 18:58:45 +0000961 private boolean bindService() {
962 if (mIntent != null && mService == null &&
963 doBind(mIntent, this, 0, UserHandle.CURRENT_OR_SELF)) {
Benjamin Franze8b98922014-11-12 15:57:54 +0000964 Message msg = mHandler.obtainMessage(MESSAGE_BIND_PROFILE_SERVICE);
965 msg.obj = this;
966 mHandler.sendMessageDelayed(msg, TIMEOUT_BIND_MS);
Benjamin Franz5b614592014-12-09 18:58:45 +0000967 return true;
Benjamin Franze8b98922014-11-12 15:57:54 +0000968 }
Jeff Sharkey67609c72016-03-05 14:29:13 -0700969 Slog.w(TAG, "Unable to bind with intent: " + mIntent);
Benjamin Franz5b614592014-12-09 18:58:45 +0000970 return false;
Benjamin Franze8b98922014-11-12 15:57:54 +0000971 }
972
973 private void addProxy(IBluetoothProfileServiceConnection proxy) {
974 mProxies.register(proxy);
975 if (mService != null) {
976 try{
977 proxy.onServiceConnected(mClassName, mService);
978 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700979 Slog.e(TAG, "Unable to connect to proxy", e);
Benjamin Franze8b98922014-11-12 15:57:54 +0000980 }
981 } else {
982 if (!mHandler.hasMessages(MESSAGE_BIND_PROFILE_SERVICE, this)) {
983 Message msg = mHandler.obtainMessage(MESSAGE_BIND_PROFILE_SERVICE);
984 msg.obj = this;
985 mHandler.sendMessage(msg);
986 }
987 }
988 }
989
990 private void removeProxy(IBluetoothProfileServiceConnection proxy) {
991 if (proxy != null) {
992 if (mProxies.unregister(proxy)) {
993 try {
994 proxy.onServiceDisconnected(mClassName);
995 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700996 Slog.e(TAG, "Unable to disconnect proxy", e);
Benjamin Franze8b98922014-11-12 15:57:54 +0000997 }
998 }
999 } else {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001000 Slog.w(TAG, "Trying to remove a null proxy");
Benjamin Franze8b98922014-11-12 15:57:54 +00001001 }
1002 }
1003
1004 private void removeAllProxies() {
1005 onServiceDisconnected(mClassName);
1006 mProxies.kill();
1007 }
1008
1009 @Override
1010 public void onServiceConnected(ComponentName className, IBinder service) {
1011 // remove timeout message
1012 mHandler.removeMessages(MESSAGE_BIND_PROFILE_SERVICE, this);
1013 mService = service;
1014 mClassName = className;
1015 try {
1016 mService.linkToDeath(this, 0);
1017 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001018 Slog.e(TAG, "Unable to linkToDeath", e);
Benjamin Franze8b98922014-11-12 15:57:54 +00001019 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001020
1021 if (mInvokingProxyCallbacks) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001022 Slog.e(TAG, "Proxy callbacks already in progress.");
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001023 return;
Benjamin Franze8b98922014-11-12 15:57:54 +00001024 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001025 mInvokingProxyCallbacks = true;
1026
1027 final int n = mProxies.beginBroadcast();
1028 try {
1029 for (int i = 0; i < n; i++) {
1030 try {
1031 mProxies.getBroadcastItem(i).onServiceConnected(className, service);
1032 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001033 Slog.e(TAG, "Unable to connect to proxy", e);
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001034 }
1035 }
1036 } finally {
1037 mProxies.finishBroadcast();
1038 mInvokingProxyCallbacks = false;
1039 }
Benjamin Franze8b98922014-11-12 15:57:54 +00001040 }
1041
1042 @Override
1043 public void onServiceDisconnected(ComponentName className) {
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001044 if (mService == null) return;
Benjamin Franze8b98922014-11-12 15:57:54 +00001045 mService.unlinkToDeath(this, 0);
1046 mService = null;
1047 mClassName = null;
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001048
1049 if (mInvokingProxyCallbacks) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001050 Slog.e(TAG, "Proxy callbacks already in progress.");
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001051 return;
Benjamin Franze8b98922014-11-12 15:57:54 +00001052 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001053 mInvokingProxyCallbacks = true;
1054
1055 final int n = mProxies.beginBroadcast();
1056 try {
1057 for (int i = 0; i < n; i++) {
1058 try {
1059 mProxies.getBroadcastItem(i).onServiceDisconnected(className);
1060 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001061 Slog.e(TAG, "Unable to disconnect from proxy", e);
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001062 }
1063 }
1064 } finally {
1065 mProxies.finishBroadcast();
1066 mInvokingProxyCallbacks = false;
1067 }
Benjamin Franze8b98922014-11-12 15:57:54 +00001068 }
1069
1070 @Override
1071 public void binderDied() {
1072 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001073 Slog.w(TAG, "Profile service for profile: " + mClassName
Benjamin Franze8b98922014-11-12 15:57:54 +00001074 + " died.");
1075 }
1076 onServiceDisconnected(mClassName);
1077 // Trigger rebind
1078 Message msg = mHandler.obtainMessage(MESSAGE_BIND_PROFILE_SERVICE);
1079 msg.obj = this;
1080 mHandler.sendMessageDelayed(msg, TIMEOUT_BIND_MS);
1081 }
1082 }
1083
fredcbf072a72012-05-09 16:52:50 -07001084 private void sendBluetoothStateCallback(boolean isUp) {
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001085 try {
1086 int n = mStateChangeCallbacks.beginBroadcast();
Jeff Sharkey67609c72016-03-05 14:29:13 -07001087 if (DBG) Slog.d(TAG,"Broadcasting onBluetoothStateChange("+isUp+") to " + n + " receivers.");
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001088 for (int i=0; i <n;i++) {
1089 try {
1090 mStateChangeCallbacks.getBroadcastItem(i).onBluetoothStateChange(isUp);
1091 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001092 Slog.e(TAG, "Unable to call onBluetoothStateChange() on callback #" + i , e);
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001093 }
fredcbf072a72012-05-09 16:52:50 -07001094 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001095 } finally {
1096 mStateChangeCallbacks.finishBroadcast();
fredcbf072a72012-05-09 16:52:50 -07001097 }
fredcbf072a72012-05-09 16:52:50 -07001098 }
1099
1100 /**
Zhihai Xu40874a02012-10-08 17:57:03 -07001101 * Inform BluetoothAdapter instances that Adapter service is up
1102 */
1103 private void sendBluetoothServiceUpCallback() {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001104 if (DBG) Slog.d(TAG,"Calling onBluetoothServiceUp callbacks");
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001105 try {
1106 int n = mCallbacks.beginBroadcast();
Jeff Sharkey67609c72016-03-05 14:29:13 -07001107 Slog.d(TAG,"Broadcasting onBluetoothServiceUp() to " + n + " receivers.");
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001108 for (int i=0; i <n;i++) {
1109 try {
1110 mCallbacks.getBroadcastItem(i).onBluetoothServiceUp(mBluetooth);
1111 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001112 Slog.e(TAG, "Unable to call onBluetoothServiceUp() on callback #" + i, e);
Zhihai Xu40874a02012-10-08 17:57:03 -07001113 }
1114 }
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001115 } finally {
1116 mCallbacks.finishBroadcast();
Zhihai Xu40874a02012-10-08 17:57:03 -07001117 }
1118 }
1119 /**
fredcbf072a72012-05-09 16:52:50 -07001120 * Inform BluetoothAdapter instances that Adapter service is down
1121 */
1122 private void sendBluetoothServiceDownCallback() {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001123 if (DBG) Slog.d(TAG,"Calling onBluetoothServiceDown callbacks");
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001124 try {
1125 int n = mCallbacks.beginBroadcast();
Jeff Sharkey67609c72016-03-05 14:29:13 -07001126 Slog.d(TAG,"Broadcasting onBluetoothServiceDown() to " + n + " receivers.");
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001127 for (int i=0; i <n;i++) {
1128 try {
1129 mCallbacks.getBroadcastItem(i).onBluetoothServiceDown();
1130 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001131 Slog.e(TAG, "Unable to call onBluetoothServiceDown() on callback #" + i, e);
fredcd6883532012-04-25 17:46:13 -07001132 }
1133 }
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001134 } finally {
1135 mCallbacks.finishBroadcast();
fredcd6883532012-04-25 17:46:13 -07001136 }
1137 }
Svet Ganov408abf72015-05-12 19:13:36 -07001138
fredc0f420372012-04-12 00:02:00 -07001139 public String getAddress() {
Matthew Xieaf5ddbf2012-12-04 10:47:43 -08001140 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
Svet Ganov408abf72015-05-12 19:13:36 -07001141 "Need BLUETOOTH permission");
Zhihai Xu40874a02012-10-08 17:57:03 -07001142
Zhihai Xu6eb76522012-11-29 15:41:04 -08001143 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
Svet Ganov408abf72015-05-12 19:13:36 -07001144 (!checkIfCallerIsForegroundUser())) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001145 Slog.w(TAG,"getAddress(): not allowed for non-active and non system user");
Zhihai Xu6eb76522012-11-29 15:41:04 -08001146 return null;
Zhihai Xu40874a02012-10-08 17:57:03 -07001147 }
1148
Svet Ganov408abf72015-05-12 19:13:36 -07001149 if (mContext.checkCallingOrSelfPermission(Manifest.permission.LOCAL_MAC_ADDRESS)
1150 != PackageManager.PERMISSION_GRANTED) {
1151 return BluetoothAdapter.DEFAULT_MAC_ADDRESS;
1152 }
1153
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001154 try {
1155 mBluetoothLock.readLock().lock();
1156 if (mBluetooth != null) return mBluetooth.getAddress();
1157 } catch (RemoteException e) {
1158 Slog.e(TAG, "getAddress(): Unable to retrieve address remotely. Returning cached address", e);
1159 } finally {
1160 mBluetoothLock.readLock().unlock();
fredc116d1d462012-04-20 14:47:08 -07001161 }
Ajay Panickerbf796d82016-03-11 13:47:20 -08001162
Matthew Xiecdce0b92012-07-12 19:06:15 -07001163 // mAddress is accessed from outside.
1164 // It is alright without a lock. Here, bluetooth is off, no other thread is
1165 // changing mAddress
fredc0f420372012-04-12 00:02:00 -07001166 return mAddress;
1167 }
fredc649fe492012-04-19 01:07:18 -07001168
fredc0f420372012-04-12 00:02:00 -07001169 public String getName() {
Matthew Xieaf5ddbf2012-12-04 10:47:43 -08001170 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
1171 "Need BLUETOOTH permission");
Zhihai Xu40874a02012-10-08 17:57:03 -07001172
Zhihai Xu6eb76522012-11-29 15:41:04 -08001173 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
1174 (!checkIfCallerIsForegroundUser())) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001175 Slog.w(TAG,"getName(): not allowed for non-active and non system user");
Zhihai Xu6eb76522012-11-29 15:41:04 -08001176 return null;
Zhihai Xu40874a02012-10-08 17:57:03 -07001177 }
1178
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001179 try {
1180 mBluetoothLock.readLock().lock();
1181 if (mBluetooth != null) return mBluetooth.getName();
1182 } catch (RemoteException e) {
1183 Slog.e(TAG, "getName(): Unable to retrieve name remotely. Returning cached name", e);
1184 } finally {
1185 mBluetoothLock.readLock().unlock();
fredc116d1d462012-04-20 14:47:08 -07001186 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001187
Matthew Xiecdce0b92012-07-12 19:06:15 -07001188 // mName is accessed from outside.
1189 // It alright without a lock. Here, bluetooth is off, no other thread is
1190 // changing mName
fredc0f420372012-04-12 00:02:00 -07001191 return mName;
1192 }
1193
fredc0f420372012-04-12 00:02:00 -07001194 private class BluetoothServiceConnection implements ServiceConnection {
fredc0f420372012-04-12 00:02:00 -07001195 public void onServiceConnected(ComponentName className, IBinder service) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001196 if (DBG) Slog.d(TAG, "BluetoothServiceConnection: " + className.getClassName());
fredc0f420372012-04-12 00:02:00 -07001197 Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_SERVICE_CONNECTED);
Matthew Xieddf7e472013-03-01 18:41:02 -08001198 // TBD if (className.getClassName().equals(IBluetooth.class.getName())) {
1199 if (className.getClassName().equals("com.android.bluetooth.btservice.AdapterService")) {
1200 msg.arg1 = SERVICE_IBLUETOOTH;
1201 // } else if (className.getClassName().equals(IBluetoothGatt.class.getName())) {
1202 } else if (className.getClassName().equals("com.android.bluetooth.gatt.GattService")) {
1203 msg.arg1 = SERVICE_IBLUETOOTHGATT;
1204 } else {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001205 Slog.e(TAG, "Unknown service connected: " + className.getClassName());
Matthew Xieddf7e472013-03-01 18:41:02 -08001206 return;
1207 }
fredc0f420372012-04-12 00:02:00 -07001208 msg.obj = service;
1209 mHandler.sendMessage(msg);
1210 }
1211
1212 public void onServiceDisconnected(ComponentName className) {
fredc0f420372012-04-12 00:02:00 -07001213 // Called if we unexpected disconnected.
Jeff Sharkey67609c72016-03-05 14:29:13 -07001214 if (DBG) Slog.d(TAG, "BluetoothServiceConnection, disconnected: " +
Matthew Xieddf7e472013-03-01 18:41:02 -08001215 className.getClassName());
fredc0f420372012-04-12 00:02:00 -07001216 Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED);
Matthew Xieddf7e472013-03-01 18:41:02 -08001217 if (className.getClassName().equals("com.android.bluetooth.btservice.AdapterService")) {
1218 msg.arg1 = SERVICE_IBLUETOOTH;
1219 } else if (className.getClassName().equals("com.android.bluetooth.gatt.GattService")) {
1220 msg.arg1 = SERVICE_IBLUETOOTHGATT;
1221 } else {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001222 Slog.e(TAG, "Unknown service disconnected: " + className.getClassName());
Matthew Xieddf7e472013-03-01 18:41:02 -08001223 return;
1224 }
fredc0f420372012-04-12 00:02:00 -07001225 mHandler.sendMessage(msg);
1226 }
1227 }
1228
1229 private BluetoothServiceConnection mConnection = new BluetoothServiceConnection();
1230
Zhihai Xu40874a02012-10-08 17:57:03 -07001231 private class BluetoothHandler extends Handler {
Ajay Panicker4bb48302016-03-31 14:14:27 -07001232 boolean mGetNameAddressOnly = false;
1233
Zhihai Xu40874a02012-10-08 17:57:03 -07001234 public BluetoothHandler(Looper looper) {
1235 super(looper);
1236 }
1237
fredc0f420372012-04-12 00:02:00 -07001238 @Override
1239 public void handleMessage(Message msg) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001240 if (DBG) Slog.d (TAG, "Message: " + msg.what);
fredc0f420372012-04-12 00:02:00 -07001241 switch (msg.what) {
Ajay Panicker4bb48302016-03-31 14:14:27 -07001242 case MESSAGE_GET_NAME_AND_ADDRESS:
1243 if (DBG) Slog.d(TAG, "MESSAGE_GET_NAME_AND_ADDRESS");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001244 try {
1245 mBluetoothLock.writeLock().lock();
Ajay Panicker4bb48302016-03-31 14:14:27 -07001246 if ((mBluetooth == null) && (!mBinding)) {
1247 if (DBG) Slog.d(TAG, "Binding to service to get name and address");
1248 mGetNameAddressOnly = true;
1249 Message timeoutMsg = mHandler.obtainMessage(MESSAGE_TIMEOUT_BIND);
1250 mHandler.sendMessageDelayed(timeoutMsg, TIMEOUT_BIND_MS);
1251 Intent i = new Intent(IBluetooth.class.getName());
1252 if (!doBind(i, mConnection,
1253 Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT,
1254 UserHandle.CURRENT)) {
1255 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
1256 } else {
1257 mBinding = true;
1258 }
1259 } else if (mBluetooth != null) {
1260 try {
1261 storeNameAndAddress(mBluetooth.getName(),
1262 mBluetooth.getAddress());
1263 } catch (RemoteException re) {
1264 Slog.e(TAG, "Unable to grab names", re);
1265 }
1266 if (mGetNameAddressOnly && !mEnable) {
1267 unbindAndFinish();
1268 }
1269 mGetNameAddressOnly = false;
1270 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001271 } finally {
1272 mBluetoothLock.writeLock().unlock();
Ajay Panicker4bb48302016-03-31 14:14:27 -07001273 }
1274 break;
1275
Matthew Xiecdce0b92012-07-12 19:06:15 -07001276 case MESSAGE_ENABLE:
fredcf2458862012-04-16 15:18:27 -07001277 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001278 Slog.d(TAG, "MESSAGE_ENABLE: mBluetooth = " + mBluetooth);
fredc649fe492012-04-19 01:07:18 -07001279 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001280 mHandler.removeMessages(MESSAGE_RESTART_BLUETOOTH_SERVICE);
1281 mEnable = true;
Calvin Ona0b91d72016-06-15 17:58:23 -07001282
1283 // Use service interface to get the exact state
1284 try {
1285 mBluetoothLock.readLock().lock();
1286 if (mBluetooth != null) {
1287 int state = mBluetooth.getState();
1288 if (state == BluetoothAdapter.STATE_BLE_ON) {
1289 Slog.w(TAG, "BT is in BLE_ON State");
1290 mBluetooth.onLeServiceUp();
1291 break;
1292 }
1293 }
1294 } catch (RemoteException e) {
1295 Slog.e(TAG, "", e);
1296 } finally {
1297 mBluetoothLock.readLock().unlock();
1298 }
1299
1300 mQuietEnable = (msg.arg1 == 1);
Pavlin Radoslavove47ec142016-06-01 22:25:18 -07001301 if (mBluetooth == null) {
Calvin Ona0b91d72016-06-15 17:58:23 -07001302 handleEnable(mQuietEnable);
Pavlin Radoslavove47ec142016-06-01 22:25:18 -07001303 } else {
1304 //
1305 // We need to wait until transitioned to STATE_OFF and
1306 // the previous Bluetooth process has exited. The
1307 // waiting period has three components:
1308 // (a) Wait until the local state is STATE_OFF. This
1309 // is accomplished by "waitForOnOff(false, true)".
1310 // (b) Wait until the STATE_OFF state is updated to
1311 // all components.
1312 // (c) Wait until the Bluetooth process exits, and
1313 // ActivityManager detects it.
1314 // The waiting for (b) and (c) is accomplished by
1315 // delaying the MESSAGE_RESTART_BLUETOOTH_SERVICE
1316 // message. On slower devices, that delay needs to be
1317 // on the order of (2 * SERVICE_RESTART_TIME_MS).
1318 //
1319 waitForOnOff(false, true);
Pavlin Radoslavove47ec142016-06-01 22:25:18 -07001320 Message restartMsg = mHandler.obtainMessage(
1321 MESSAGE_RESTART_BLUETOOTH_SERVICE);
1322 mHandler.sendMessageDelayed(restartMsg,
1323 2 * SERVICE_RESTART_TIME_MS);
1324 }
fredc649fe492012-04-19 01:07:18 -07001325 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001326
fredc0f420372012-04-12 00:02:00 -07001327 case MESSAGE_DISABLE:
Zhihai Xu40874a02012-10-08 17:57:03 -07001328 mHandler.removeMessages(MESSAGE_RESTART_BLUETOOTH_SERVICE);
1329 if (mEnable && mBluetooth != null) {
1330 waitForOnOff(true, false);
1331 mEnable = false;
Zhihai Xu401202b2012-12-03 11:36:21 -08001332 handleDisable();
Zhihai Xu40874a02012-10-08 17:57:03 -07001333 waitForOnOff(false, false);
1334 } else {
1335 mEnable = false;
Zhihai Xu401202b2012-12-03 11:36:21 -08001336 handleDisable();
Zhihai Xu40874a02012-10-08 17:57:03 -07001337 }
fredc0f420372012-04-12 00:02:00 -07001338 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001339
fredc0f420372012-04-12 00:02:00 -07001340 case MESSAGE_REGISTER_ADAPTER:
1341 {
1342 IBluetoothManagerCallback callback = (IBluetoothManagerCallback) msg.obj;
fredcd6883532012-04-25 17:46:13 -07001343 boolean added = mCallbacks.register(callback);
Jeff Sharkey67609c72016-03-05 14:29:13 -07001344 Slog.d(TAG,"Added callback: " + (callback == null? "null": callback) +":" +added );
fredc0f420372012-04-12 00:02:00 -07001345 }
1346 break;
1347 case MESSAGE_UNREGISTER_ADAPTER:
1348 {
1349 IBluetoothManagerCallback callback = (IBluetoothManagerCallback) msg.obj;
fredcd6883532012-04-25 17:46:13 -07001350 boolean removed = mCallbacks.unregister(callback);
Jeff Sharkey67609c72016-03-05 14:29:13 -07001351 Slog.d(TAG,"Removed callback: " + (callback == null? "null": callback) +":" + removed);
fredc0f420372012-04-12 00:02:00 -07001352 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001353 }
fredc0f420372012-04-12 00:02:00 -07001354 case MESSAGE_REGISTER_STATE_CHANGE_CALLBACK:
1355 {
1356 IBluetoothStateChangeCallback callback = (IBluetoothStateChangeCallback) msg.obj;
Matthew Xie9b693992013-10-10 11:21:40 -07001357 if (callback != null) {
1358 mStateChangeCallbacks.register(callback);
1359 }
fredc0f420372012-04-12 00:02:00 -07001360 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001361 }
fredc0f420372012-04-12 00:02:00 -07001362 case MESSAGE_UNREGISTER_STATE_CHANGE_CALLBACK:
1363 {
1364 IBluetoothStateChangeCallback callback = (IBluetoothStateChangeCallback) msg.obj;
Matthew Xie9b693992013-10-10 11:21:40 -07001365 if (callback != null) {
1366 mStateChangeCallbacks.unregister(callback);
1367 }
fredc0f420372012-04-12 00:02:00 -07001368 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001369 }
Benjamin Franze8b98922014-11-12 15:57:54 +00001370 case MESSAGE_ADD_PROXY_DELAYED:
1371 {
1372 ProfileServiceConnections psc = mProfileServices.get(
1373 new Integer(msg.arg1));
1374 if (psc == null) {
1375 break;
1376 }
1377 IBluetoothProfileServiceConnection proxy =
1378 (IBluetoothProfileServiceConnection) msg.obj;
1379 psc.addProxy(proxy);
1380 break;
1381 }
1382 case MESSAGE_BIND_PROFILE_SERVICE:
1383 {
1384 ProfileServiceConnections psc = (ProfileServiceConnections) msg.obj;
1385 removeMessages(MESSAGE_BIND_PROFILE_SERVICE, msg.obj);
1386 if (psc == null) {
1387 break;
1388 }
1389 psc.bindService();
1390 break;
1391 }
fredc0f420372012-04-12 00:02:00 -07001392 case MESSAGE_BLUETOOTH_SERVICE_CONNECTED:
1393 {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001394 if (DBG) Slog.d(TAG,"MESSAGE_BLUETOOTH_SERVICE_CONNECTED: " + msg.arg1);
fredc0f420372012-04-12 00:02:00 -07001395
1396 IBinder service = (IBinder) msg.obj;
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001397 try {
1398 mBluetoothLock.writeLock().lock();
Matthew Xieddf7e472013-03-01 18:41:02 -08001399 if (msg.arg1 == SERVICE_IBLUETOOTHGATT) {
Jeff Sharkey0a17db12016-11-04 11:23:46 -06001400 mBluetoothGatt = IBluetoothGatt.Stub
1401 .asInterface(Binder.allowBlocking(service));
Nitin Arorad055adb2015-03-02 15:03:51 -08001402 onBluetoothGattServiceUp();
Matthew Xieddf7e472013-03-01 18:41:02 -08001403 break;
1404 } // else must be SERVICE_IBLUETOOTH
1405
1406 //Remove timeout
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001407 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
Matthew Xieddf7e472013-03-01 18:41:02 -08001408
fredc0f420372012-04-12 00:02:00 -07001409 mBinding = false;
Marie Janssen9db28eb2016-01-12 16:05:15 -08001410 mBluetoothBinder = service;
Jeff Sharkey0a17db12016-11-04 11:23:46 -06001411 mBluetooth = IBluetooth.Stub.asInterface(Binder.allowBlocking(service));
fredc0f420372012-04-12 00:02:00 -07001412
Ajay Panicker4bb48302016-03-31 14:14:27 -07001413 if (!isNameAndAddressSet()) {
1414 Message getMsg = mHandler.obtainMessage(MESSAGE_GET_NAME_AND_ADDRESS);
1415 mHandler.sendMessage(getMsg);
1416 if (mGetNameAddressOnly) return;
1417 }
1418
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001419 try {
1420 boolean enableHciSnoopLog = (Settings.Secure.getInt(mContentResolver,
1421 Settings.Secure.BLUETOOTH_HCI_LOG, 0) == 1);
1422 if (!mBluetooth.configHciSnoopLog(enableHciSnoopLog)) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001423 Slog.e(TAG,"IBluetooth.configHciSnoopLog return false");
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001424 }
1425 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001426 Slog.e(TAG,"Unable to call configHciSnoopLog", e);
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001427 }
1428
Matthew Xiecdce0b92012-07-12 19:06:15 -07001429 //Register callback object
fredcbf072a72012-05-09 16:52:50 -07001430 try {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001431 mBluetooth.registerCallback(mBluetoothCallback);
1432 } catch (RemoteException re) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001433 Slog.e(TAG, "Unable to register BluetoothCallback",re);
fredcbf072a72012-05-09 16:52:50 -07001434 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001435 //Inform BluetoothAdapter instances that service is up
Zhihai Xu40874a02012-10-08 17:57:03 -07001436 sendBluetoothServiceUpCallback();
1437
Matthew Xiecdce0b92012-07-12 19:06:15 -07001438 //Do enable request
1439 try {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001440 if (mQuietEnable == false) {
1441 if(!mBluetooth.enable()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001442 Slog.e(TAG,"IBluetooth.enable() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001443 }
1444 }
1445 else
1446 {
1447 if(!mBluetooth.enableNoAutoConnect()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001448 Slog.e(TAG,"IBluetooth.enableNoAutoConnect() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001449 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001450 }
1451 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001452 Slog.e(TAG,"Unable to call enable()",e);
Matthew Xiecdce0b92012-07-12 19:06:15 -07001453 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001454 } finally {
1455 mBluetoothLock.writeLock().unlock();
Freda8c6df02012-07-11 10:25:23 -07001456 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001457
1458 if (!mEnable) {
1459 waitForOnOff(true, false);
Zhihai Xu401202b2012-12-03 11:36:21 -08001460 handleDisable();
Zhihai Xu40874a02012-10-08 17:57:03 -07001461 waitForOnOff(false, false);
1462 }
fredc649fe492012-04-19 01:07:18 -07001463 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001464 }
fredc649fe492012-04-19 01:07:18 -07001465 case MESSAGE_TIMEOUT_BIND: {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001466 Slog.e(TAG, "MESSAGE_TIMEOUT_BIND");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001467 mBluetoothLock.writeLock().lock();
1468 mBinding = false;
1469 mBluetoothLock.writeLock().unlock();
1470
fredc649fe492012-04-19 01:07:18 -07001471 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001472 }
fredcbf072a72012-05-09 16:52:50 -07001473 case MESSAGE_BLUETOOTH_STATE_CHANGE:
fredc0f420372012-04-12 00:02:00 -07001474 {
fredcbf072a72012-05-09 16:52:50 -07001475 int prevState = msg.arg1;
1476 int newState = msg.arg2;
Marie Janssen9fa24912016-10-18 10:04:24 -07001477 if (DBG) Slog.d(TAG, "MESSAGE_BLUETOOTH_STATE_CHANGE: prevState = " + prevState + ", newState =" + newState);
Zhihai Xu40874a02012-10-08 17:57:03 -07001478 mState = newState;
1479 bluetoothStateChangeHandler(prevState, newState);
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001480 // handle error state transition case from TURNING_ON to OFF
1481 // unbind and rebind bluetooth service and enable bluetooth
Nitin Arorad055adb2015-03-02 15:03:51 -08001482 if ((prevState == BluetoothAdapter.STATE_BLE_TURNING_ON) &&
Calvin Ona0b91d72016-06-15 17:58:23 -07001483 (newState == BluetoothAdapter.STATE_OFF) &&
1484 (mBluetooth != null) && mEnable) {
Marie Janssen2977c3e2016-11-09 12:01:24 -08001485 recoverBluetoothServiceFromError(false);
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001486 }
Nitin Arorad055adb2015-03-02 15:03:51 -08001487 if ((prevState == BluetoothAdapter.STATE_TURNING_ON) &&
Calvin Ona0b91d72016-06-15 17:58:23 -07001488 (newState == BluetoothAdapter.STATE_BLE_ON) &&
1489 (mBluetooth != null) && mEnable) {
Marie Janssen2977c3e2016-11-09 12:01:24 -08001490 recoverBluetoothServiceFromError(true);
Nitin Arorad055adb2015-03-02 15:03:51 -08001491 }
Calvin Ona0b91d72016-06-15 17:58:23 -07001492 // If we tried to enable BT while BT was in the process of shutting down,
1493 // wait for the BT process to fully tear down and then force a restart
1494 // here. This is a bit of a hack (b/29363429).
1495 if ((prevState == BluetoothAdapter.STATE_BLE_TURNING_OFF) &&
1496 (newState == BluetoothAdapter.STATE_OFF)) {
1497 if (mEnable) {
1498 Slog.d(TAG, "Entering STATE_OFF but mEnabled is true; restarting.");
1499 waitForOnOff(false, true);
1500 Message restartMsg = mHandler.obtainMessage(
1501 MESSAGE_RESTART_BLUETOOTH_SERVICE);
1502 mHandler.sendMessageDelayed(restartMsg, 2 * SERVICE_RESTART_TIME_MS);
1503 }
1504 }
Nitin Arorad055adb2015-03-02 15:03:51 -08001505 if (newState == BluetoothAdapter.STATE_ON ||
Calvin Ona0b91d72016-06-15 17:58:23 -07001506 newState == BluetoothAdapter.STATE_BLE_ON) {
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001507 // bluetooth is working, reset the counter
1508 if (mErrorRecoveryRetryCounter != 0) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001509 Slog.w(TAG, "bluetooth is recovered from error");
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001510 mErrorRecoveryRetryCounter = 0;
1511 }
1512 }
fredc649fe492012-04-19 01:07:18 -07001513 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001514 }
fredc0f420372012-04-12 00:02:00 -07001515 case MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED:
1516 {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001517 Slog.e(TAG, "MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED: " + msg.arg1);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001518 try {
1519 mBluetoothLock.writeLock().lock();
Matthew Xieddf7e472013-03-01 18:41:02 -08001520 if (msg.arg1 == SERVICE_IBLUETOOTH) {
1521 // if service is unbinded already, do nothing and return
1522 if (mBluetooth == null) break;
1523 mBluetooth = null;
1524 } else if (msg.arg1 == SERVICE_IBLUETOOTHGATT) {
1525 mBluetoothGatt = null;
1526 break;
1527 } else {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001528 Slog.e(TAG, "Bad msg.arg1: " + msg.arg1);
Matthew Xieddf7e472013-03-01 18:41:02 -08001529 break;
1530 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001531 } finally {
1532 mBluetoothLock.writeLock().unlock();
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301533 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001534
1535 if (mEnable) {
1536 mEnable = false;
1537 // Send a Bluetooth Restart message
1538 Message restartMsg = mHandler.obtainMessage(
1539 MESSAGE_RESTART_BLUETOOTH_SERVICE);
1540 mHandler.sendMessageDelayed(restartMsg,
1541 SERVICE_RESTART_TIME_MS);
1542 }
1543
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001544 sendBluetoothServiceDownCallback();
Zhihai Xu40874a02012-10-08 17:57:03 -07001545
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001546 // Send BT state broadcast to update
1547 // the BT icon correctly
1548 if ((mState == BluetoothAdapter.STATE_TURNING_ON) ||
Calvin Ona0b91d72016-06-15 17:58:23 -07001549 (mState == BluetoothAdapter.STATE_ON)) {
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001550 bluetoothStateChangeHandler(BluetoothAdapter.STATE_ON,
1551 BluetoothAdapter.STATE_TURNING_OFF);
1552 mState = BluetoothAdapter.STATE_TURNING_OFF;
Zhihai Xu40874a02012-10-08 17:57:03 -07001553 }
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001554 if (mState == BluetoothAdapter.STATE_TURNING_OFF) {
1555 bluetoothStateChangeHandler(BluetoothAdapter.STATE_TURNING_OFF,
1556 BluetoothAdapter.STATE_OFF);
1557 }
1558
1559 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
1560 mState = BluetoothAdapter.STATE_OFF;
fredc649fe492012-04-19 01:07:18 -07001561 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001562 }
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301563 case MESSAGE_RESTART_BLUETOOTH_SERVICE:
1564 {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001565 Slog.d(TAG, "MESSAGE_RESTART_BLUETOOTH_SERVICE:"
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301566 +" Restart IBluetooth service");
1567 /* Enable without persisting the setting as
1568 it doesnt change when IBluetooth
1569 service restarts */
Zhihai Xu40874a02012-10-08 17:57:03 -07001570 mEnable = true;
Zhihai Xu401202b2012-12-03 11:36:21 -08001571 handleEnable(mQuietEnable);
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301572 break;
1573 }
1574
fredc0f420372012-04-12 00:02:00 -07001575 case MESSAGE_TIMEOUT_UNBIND:
1576 {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001577 Slog.e(TAG, "MESSAGE_TIMEOUT_UNBIND");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001578 mBluetoothLock.writeLock().lock();
1579 mUnbinding = false;
1580 mBluetoothLock.writeLock().unlock();
fredc649fe492012-04-19 01:07:18 -07001581 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001582 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001583
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001584 case MESSAGE_USER_SWITCHED: {
1585 if (DBG) Slog.d(TAG, "MESSAGE_USER_SWITCHED");
Zhihai Xu40874a02012-10-08 17:57:03 -07001586 mHandler.removeMessages(MESSAGE_USER_SWITCHED);
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001587
Zhihai Xu40874a02012-10-08 17:57:03 -07001588 /* disable and enable BT when detect a user switch */
1589 if (mEnable && mBluetooth != null) {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001590 try {
1591 mBluetoothLock.readLock().lock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001592 if (mBluetooth != null) {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001593 mBluetooth.unregisterCallback(mBluetoothCallback);
Zhihai Xu40874a02012-10-08 17:57:03 -07001594 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001595 } catch (RemoteException re) {
1596 Slog.e(TAG, "Unable to unregister", re);
1597 } finally {
1598 mBluetoothLock.readLock().unlock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001599 }
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001600
1601 if (mState == BluetoothAdapter.STATE_TURNING_OFF) {
1602 // MESSAGE_USER_SWITCHED happened right after MESSAGE_ENABLE
1603 bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_OFF);
1604 mState = BluetoothAdapter.STATE_OFF;
1605 }
1606 if (mState == BluetoothAdapter.STATE_OFF) {
1607 bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_TURNING_ON);
1608 mState = BluetoothAdapter.STATE_TURNING_ON;
1609 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001610
1611 waitForOnOff(true, false);
1612
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001613 if (mState == BluetoothAdapter.STATE_TURNING_ON) {
1614 bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_ON);
1615 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001616
Benjamin Franze8b98922014-11-12 15:57:54 +00001617 unbindAllBluetoothProfileServices();
Zhihai Xu40874a02012-10-08 17:57:03 -07001618 // disable
Zhihai Xu401202b2012-12-03 11:36:21 -08001619 handleDisable();
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001620 // Pbap service need receive STATE_TURNING_OFF intent to close
1621 bluetoothStateChangeHandler(BluetoothAdapter.STATE_ON,
1622 BluetoothAdapter.STATE_TURNING_OFF);
Zhihai Xu40874a02012-10-08 17:57:03 -07001623
Pavlin Radoslavov41401112016-06-27 15:25:18 -07001624 boolean didDisableTimeout = !waitForOnOff(false, true);
Zhihai Xu40874a02012-10-08 17:57:03 -07001625
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001626 bluetoothStateChangeHandler(BluetoothAdapter.STATE_TURNING_OFF,
Zhihai Xu40874a02012-10-08 17:57:03 -07001627 BluetoothAdapter.STATE_OFF);
Zhihai Xu40874a02012-10-08 17:57:03 -07001628 sendBluetoothServiceDownCallback();
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001629
Pavlin Radoslavove957a8a2016-05-24 15:28:41 -07001630 try {
1631 mBluetoothLock.writeLock().lock();
1632 if (mBluetooth != null) {
1633 mBluetooth = null;
1634 // Unbind
1635 mContext.unbindService(mConnection);
1636 }
1637 mBluetoothGatt = null;
1638 } finally {
1639 mBluetoothLock.writeLock().unlock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001640 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001641
Pavlin Radoslavov41401112016-06-27 15:25:18 -07001642 //
1643 // If disabling Bluetooth times out, wait for an
1644 // additional amount of time to ensure the process is
1645 // shut down completely before attempting to restart.
1646 //
1647 if (didDisableTimeout) {
1648 SystemClock.sleep(3000);
1649 } else {
1650 SystemClock.sleep(100);
1651 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001652
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001653 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
1654 mState = BluetoothAdapter.STATE_OFF;
Zhihai Xu40874a02012-10-08 17:57:03 -07001655 // enable
Zhihai Xu401202b2012-12-03 11:36:21 -08001656 handleEnable(mQuietEnable);
John Spurlock8a985d22014-02-25 09:40:05 -05001657 } else if (mBinding || mBluetooth != null) {
Zhihai Xu40874a02012-10-08 17:57:03 -07001658 Message userMsg = mHandler.obtainMessage(MESSAGE_USER_SWITCHED);
1659 userMsg.arg2 = 1 + msg.arg2;
1660 // if user is switched when service is being binding
1661 // delay sending MESSAGE_USER_SWITCHED
1662 mHandler.sendMessageDelayed(userMsg, USER_SWITCHED_TIME_MS);
1663 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001664 Slog.d(TAG, "delay MESSAGE_USER_SWITCHED " + userMsg.arg2);
Zhihai Xu40874a02012-10-08 17:57:03 -07001665 }
John Spurlock8a985d22014-02-25 09:40:05 -05001666 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001667 break;
1668 }
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001669 case MESSAGE_USER_UNLOCKED: {
1670 if (DBG) Slog.d(TAG, "MESSAGE_USER_UNLOCKED");
1671 mHandler.removeMessages(MESSAGE_USER_SWITCHED);
1672
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001673 if (mEnable && !mBinding && (mBluetooth == null)) {
1674 // We should be connected, but we gave up for some
1675 // reason; maybe the Bluetooth service wasn't encryption
1676 // aware, so try binding again.
1677 if (DBG) Slog.d(TAG, "Enabled but not bound; retrying after unlock");
1678 handleEnable(mQuietEnable);
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001679 }
1680 }
fredc0f420372012-04-12 00:02:00 -07001681 }
1682 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001683 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001684
Zhihai Xu401202b2012-12-03 11:36:21 -08001685 private void handleEnable(boolean quietMode) {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001686 mQuietEnable = quietMode;
1687
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001688 try {
1689 mBluetoothLock.writeLock().lock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001690 if ((mBluetooth == null) && (!mBinding)) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001691 //Start bind timeout and bind
1692 Message timeoutMsg=mHandler.obtainMessage(MESSAGE_TIMEOUT_BIND);
1693 mHandler.sendMessageDelayed(timeoutMsg,TIMEOUT_BIND_MS);
Matthew Xiecdce0b92012-07-12 19:06:15 -07001694 Intent i = new Intent(IBluetooth.class.getName());
Dianne Hackbornce09f5a2014-10-10 15:03:13 -07001695 if (!doBind(i, mConnection,Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT,
1696 UserHandle.CURRENT)) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001697 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
Zhihai Xu40874a02012-10-08 17:57:03 -07001698 } else {
1699 mBinding = true;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001700 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001701 } else if (mBluetooth != null) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001702 //Enable bluetooth
1703 try {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001704 if (!mQuietEnable) {
1705 if(!mBluetooth.enable()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001706 Slog.e(TAG,"IBluetooth.enable() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001707 }
1708 }
1709 else {
1710 if(!mBluetooth.enableNoAutoConnect()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001711 Slog.e(TAG,"IBluetooth.enableNoAutoConnect() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001712 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001713 }
1714 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001715 Slog.e(TAG,"Unable to call enable()",e);
Matthew Xiecdce0b92012-07-12 19:06:15 -07001716 }
1717 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001718 } finally {
1719 mBluetoothLock.writeLock().unlock();
Matthew Xiecdce0b92012-07-12 19:06:15 -07001720 }
1721 }
1722
Dianne Hackborn221ea892013-08-04 16:50:16 -07001723 boolean doBind(Intent intent, ServiceConnection conn, int flags, UserHandle user) {
1724 ComponentName comp = intent.resolveSystemService(mContext.getPackageManager(), 0);
1725 intent.setComponent(comp);
1726 if (comp == null || !mContext.bindServiceAsUser(intent, conn, flags, user)) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001727 Slog.e(TAG, "Fail to bind to: " + intent);
Dianne Hackborn221ea892013-08-04 16:50:16 -07001728 return false;
1729 }
1730 return true;
1731 }
1732
Zhihai Xu401202b2012-12-03 11:36:21 -08001733 private void handleDisable() {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001734 try {
1735 mBluetoothLock.readLock().lock();
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001736 if (mBluetooth != null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001737 if (DBG) Slog.d(TAG,"Sending off request.");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001738 if (!mBluetooth.disable()) {
1739 Slog.e(TAG,"IBluetooth.disable() returned false");
Matthew Xiecdce0b92012-07-12 19:06:15 -07001740 }
1741 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001742 } catch (RemoteException e) {
1743 Slog.e(TAG,"Unable to call disable()",e);
1744 } finally {
1745 mBluetoothLock.readLock().unlock();
Matthew Xiecdce0b92012-07-12 19:06:15 -07001746 }
1747 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001748
1749 private boolean checkIfCallerIsForegroundUser() {
1750 int foregroundUser;
1751 int callingUser = UserHandle.getCallingUserId();
Martijn Coenen8385c5a2012-11-29 10:14:16 -08001752 int callingUid = Binder.getCallingUid();
Zhihai Xu40874a02012-10-08 17:57:03 -07001753 long callingIdentity = Binder.clearCallingIdentity();
Benjamin Franze8b98922014-11-12 15:57:54 +00001754 UserManager um = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
1755 UserInfo ui = um.getProfileParent(callingUser);
1756 int parentUser = (ui != null) ? ui.id : UserHandle.USER_NULL;
Martijn Coenen8385c5a2012-11-29 10:14:16 -08001757 int callingAppId = UserHandle.getAppId(callingUid);
Zhihai Xu40874a02012-10-08 17:57:03 -07001758 boolean valid = false;
1759 try {
1760 foregroundUser = ActivityManager.getCurrentUser();
Martijn Coenen8385c5a2012-11-29 10:14:16 -08001761 valid = (callingUser == foregroundUser) ||
Benjamin Franze8b98922014-11-12 15:57:54 +00001762 parentUser == foregroundUser ||
Adrian Roosbd9a9a52014-08-18 15:31:57 +02001763 callingAppId == Process.NFC_UID ||
1764 callingAppId == mSystemUiUid;
Zhihai Xu40874a02012-10-08 17:57:03 -07001765 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001766 Slog.d(TAG, "checkIfCallerIsForegroundUser: valid=" + valid
Zhihai Xu40874a02012-10-08 17:57:03 -07001767 + " callingUser=" + callingUser
Benjamin Franze8b98922014-11-12 15:57:54 +00001768 + " parentUser=" + parentUser
Zhihai Xu40874a02012-10-08 17:57:03 -07001769 + " foregroundUser=" + foregroundUser);
1770 }
1771 } finally {
1772 Binder.restoreCallingIdentity(callingIdentity);
1773 }
1774 return valid;
1775 }
1776
Nitin Arorad055adb2015-03-02 15:03:51 -08001777 private void sendBleStateChanged(int prevState, int newState) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001778 if (DBG) Slog.d(TAG,"BLE State Change Intent: " + prevState + " -> " + newState);
Nitin Arorad055adb2015-03-02 15:03:51 -08001779 // Send broadcast message to everyone else
1780 Intent intent = new Intent(BluetoothAdapter.ACTION_BLE_STATE_CHANGED);
1781 intent.putExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE, prevState);
1782 intent.putExtra(BluetoothAdapter.EXTRA_STATE, newState);
1783 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1784 mContext.sendBroadcastAsUser(intent, UserHandle.ALL, BLUETOOTH_PERM);
1785 }
1786
Zhihai Xu40874a02012-10-08 17:57:03 -07001787 private void bluetoothStateChangeHandler(int prevState, int newState) {
Nitin Arorad055adb2015-03-02 15:03:51 -08001788 boolean isStandardBroadcast = true;
Marie Janssen9fa24912016-10-18 10:04:24 -07001789 if (DBG) Slog.d(TAG, "bluetoothStateChangeHandler: " + prevState + " -> " + newState);
Zhihai Xu40874a02012-10-08 17:57:03 -07001790 if (prevState != newState) {
1791 //Notify all proxy objects first of adapter state change
Calvin Ona0b91d72016-06-15 17:58:23 -07001792 if (newState == BluetoothAdapter.STATE_BLE_ON ||
1793 newState == BluetoothAdapter.STATE_OFF) {
Nitin Arorad055adb2015-03-02 15:03:51 -08001794 boolean intermediate_off = (prevState == BluetoothAdapter.STATE_TURNING_OFF
1795 && newState == BluetoothAdapter.STATE_BLE_ON);
Zhihai Xu40874a02012-10-08 17:57:03 -07001796
Nitin Arorad055adb2015-03-02 15:03:51 -08001797 if (newState == BluetoothAdapter.STATE_OFF) {
1798 // If Bluetooth is off, send service down event to proxy objects, and unbind
Jeff Sharkey67609c72016-03-05 14:29:13 -07001799 if (DBG) Slog.d(TAG, "Bluetooth is complete turn off");
Pavlin Radoslavove47ec142016-06-01 22:25:18 -07001800 sendBluetoothServiceDownCallback();
1801 unbindAndFinish();
1802 sendBleStateChanged(prevState, newState);
1803 // Don't broadcast as it has already been broadcast before
1804 isStandardBroadcast = false;
Nitin Arorad055adb2015-03-02 15:03:51 -08001805
1806 } else if (!intermediate_off) {
1807 // connect to GattService
Jeff Sharkey67609c72016-03-05 14:29:13 -07001808 if (DBG) Slog.d(TAG, "Bluetooth is in LE only mode");
Nitin Arorad055adb2015-03-02 15:03:51 -08001809 if (mBluetoothGatt != null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001810 if (DBG) Slog.d(TAG, "Calling BluetoothGattServiceUp");
Nitin Arorad055adb2015-03-02 15:03:51 -08001811 onBluetoothGattServiceUp();
1812 } else {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001813 if (DBG) Slog.d(TAG, "Binding Bluetooth GATT service");
Nitin Arorad055adb2015-03-02 15:03:51 -08001814 if (mContext.getPackageManager().hasSystemFeature(
1815 PackageManager.FEATURE_BLUETOOTH_LE)) {
1816 Intent i = new Intent(IBluetoothGatt.class.getName());
1817 doBind(i, mConnection, Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT, UserHandle.CURRENT);
1818 }
1819 }
1820 sendBleStateChanged(prevState, newState);
1821 //Don't broadcase this as std intent
1822 isStandardBroadcast = false;
1823
1824 } else if (intermediate_off){
Jeff Sharkey67609c72016-03-05 14:29:13 -07001825 if (DBG) Slog.d(TAG, "Intermediate off, back to LE only mode");
Nitin Arorad055adb2015-03-02 15:03:51 -08001826 // For LE only mode, broadcast as is
1827 sendBleStateChanged(prevState, newState);
1828 sendBluetoothStateCallback(false); // BT is OFF for general users
1829 // Broadcast as STATE_OFF
1830 newState = BluetoothAdapter.STATE_OFF;
1831 sendBrEdrDownCallback();
Zhihai Xu40874a02012-10-08 17:57:03 -07001832 }
Nitin Arorad055adb2015-03-02 15:03:51 -08001833 } else if (newState == BluetoothAdapter.STATE_ON) {
1834 boolean isUp = (newState==BluetoothAdapter.STATE_ON);
1835 sendBluetoothStateCallback(isUp);
1836 sendBleStateChanged(prevState, newState);
1837
Calvin Ona0b91d72016-06-15 17:58:23 -07001838 } else if (newState == BluetoothAdapter.STATE_BLE_TURNING_ON ||
1839 newState == BluetoothAdapter.STATE_BLE_TURNING_OFF ) {
Nitin Arorad055adb2015-03-02 15:03:51 -08001840 sendBleStateChanged(prevState, newState);
1841 isStandardBroadcast = false;
1842
Calvin Ona0b91d72016-06-15 17:58:23 -07001843 } else if (newState == BluetoothAdapter.STATE_TURNING_ON ||
1844 newState == BluetoothAdapter.STATE_TURNING_OFF) {
Nitin Arorad055adb2015-03-02 15:03:51 -08001845 sendBleStateChanged(prevState, newState);
Zhihai Xu40874a02012-10-08 17:57:03 -07001846 }
1847
Nitin Arorad055adb2015-03-02 15:03:51 -08001848 if (isStandardBroadcast) {
1849 if (prevState == BluetoothAdapter.STATE_BLE_ON) {
1850 // Show prevState of BLE_ON as OFF to standard users
1851 prevState = BluetoothAdapter.STATE_OFF;
1852 }
1853 Intent intent = new Intent(BluetoothAdapter.ACTION_STATE_CHANGED);
1854 intent.putExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE, prevState);
1855 intent.putExtra(BluetoothAdapter.EXTRA_STATE, newState);
1856 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1857 mContext.sendBroadcastAsUser(intent, UserHandle.ALL, BLUETOOTH_PERM);
1858 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001859 }
1860 }
1861
1862 /**
1863 * if on is true, wait for state become ON
1864 * if off is true, wait for state become OFF
1865 * if both on and off are false, wait for state not ON
1866 */
1867 private boolean waitForOnOff(boolean on, boolean off) {
1868 int i = 0;
1869 while (i < 10) {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001870 try {
1871 mBluetoothLock.readLock().lock();
1872 if (mBluetooth == null) break;
1873 if (on) {
1874 if (mBluetooth.getState() == BluetoothAdapter.STATE_ON) return true;
1875 } else if (off) {
1876 if (mBluetooth.getState() == BluetoothAdapter.STATE_OFF) return true;
1877 } else {
1878 if (mBluetooth.getState() != BluetoothAdapter.STATE_ON) return true;
Zhihai Xu40874a02012-10-08 17:57:03 -07001879 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001880 } catch (RemoteException e) {
1881 Slog.e(TAG, "getState()", e);
1882 break;
1883 } finally {
1884 mBluetoothLock.readLock().unlock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001885 }
1886 if (on || off) {
1887 SystemClock.sleep(300);
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07001888 } else {
Zhihai Xu40874a02012-10-08 17:57:03 -07001889 SystemClock.sleep(50);
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07001890 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001891 i++;
1892 }
Jeff Sharkey67609c72016-03-05 14:29:13 -07001893 Slog.e(TAG,"waitForOnOff time out");
Zhihai Xu40874a02012-10-08 17:57:03 -07001894 return false;
1895 }
Zhihai Xu681ae7f2012-11-12 15:14:18 -08001896
Zhihai Xu401202b2012-12-03 11:36:21 -08001897 private void sendDisableMsg() {
1898 mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_DISABLE));
1899 }
1900
1901 private void sendEnableMsg(boolean quietMode) {
1902 mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_ENABLE,
1903 quietMode ? 1 : 0, 0));
1904 }
1905
Marie Janssen2977c3e2016-11-09 12:01:24 -08001906 private void recoverBluetoothServiceFromError(boolean clearBle) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001907 Slog.e(TAG,"recoverBluetoothServiceFromError");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001908 try {
1909 mBluetoothLock.readLock().lock();
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001910 if (mBluetooth != null) {
1911 //Unregister callback object
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001912 mBluetooth.unregisterCallback(mBluetoothCallback);
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001913 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001914 } catch (RemoteException re) {
1915 Slog.e(TAG, "Unable to unregister", re);
1916 } finally {
1917 mBluetoothLock.readLock().unlock();
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001918 }
1919
1920 SystemClock.sleep(500);
1921
1922 // disable
1923 handleDisable();
1924
1925 waitForOnOff(false, true);
1926
1927 sendBluetoothServiceDownCallback();
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001928
Pavlin Radoslavove957a8a2016-05-24 15:28:41 -07001929 try {
1930 mBluetoothLock.writeLock().lock();
1931 if (mBluetooth != null) {
1932 mBluetooth = null;
1933 // Unbind
1934 mContext.unbindService(mConnection);
1935 }
1936 mBluetoothGatt = null;
1937 } finally {
1938 mBluetoothLock.writeLock().unlock();
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001939 }
1940
1941 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
1942 mState = BluetoothAdapter.STATE_OFF;
1943
Marie Janssen2977c3e2016-11-09 12:01:24 -08001944 if (clearBle) {
1945 clearBleApps();
1946 }
1947
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001948 mEnable = false;
1949
1950 if (mErrorRecoveryRetryCounter++ < MAX_ERROR_RESTART_RETRIES) {
1951 // Send a Bluetooth Restart message to reenable bluetooth
1952 Message restartMsg = mHandler.obtainMessage(
1953 MESSAGE_RESTART_BLUETOOTH_SERVICE);
1954 mHandler.sendMessageDelayed(restartMsg, ERROR_RESTART_TIME_MS);
1955 } else {
1956 // todo: notify user to power down and power up phone to make bluetooth work.
1957 }
1958 }
Mike Lockwood726d4de2014-10-28 14:06:28 -07001959
Lenka Trochtova63d5e4a72016-12-02 12:19:39 +01001960 private boolean isBluetoothDisallowed() {
1961 long callingIdentity = Binder.clearCallingIdentity();
1962 try {
1963 return mContext.getSystemService(UserManager.class)
1964 .hasUserRestriction(UserManager.DISALLOW_BLUETOOTH, UserHandle.SYSTEM);
1965 } finally {
1966 Binder.restoreCallingIdentity(callingIdentity);
1967 }
1968 }
1969
Mike Lockwood726d4de2014-10-28 14:06:28 -07001970 @Override
Pavlin Radoslavov6e8faff2016-02-23 11:54:37 -08001971 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1972 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DUMP, TAG);
1973 String errorMsg = null;
1974 if (mBluetoothBinder == null) {
1975 errorMsg = "Bluetooth Service not connected";
1976 } else {
1977 try {
1978 mBluetoothBinder.dump(fd, args);
1979 } catch (RemoteException re) {
1980 errorMsg = "RemoteException while calling Bluetooth Service";
1981 }
Mike Lockwood726d4de2014-10-28 14:06:28 -07001982 }
Pavlin Radoslavov6e8faff2016-02-23 11:54:37 -08001983 if (errorMsg != null) {
1984 // Silently return if we are extracting metrics in Protobuf format
1985 if ((args.length > 0) && args[0].startsWith("--proto"))
1986 return;
1987 writer.println(errorMsg);
1988 }
Mike Lockwood726d4de2014-10-28 14:06:28 -07001989 }
fredc0f420372012-04-12 00:02:00 -07001990}