blob: 36ef3e9f0433a244ca82b0d029faee950de0df41 [file] [log] [blame]
fredc0f420372012-04-12 00:02:00 -07001/*
Zhihai Xufa0fd392012-10-23 17:31:56 -07002 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
fredc0f420372012-04-12 00:02:00 -070015 */
16
17package com.android.server;
18
Svet Ganov408abf72015-05-12 19:13:36 -070019import android.Manifest;
Zhihai Xu40874a02012-10-08 17:57:03 -070020import android.app.ActivityManager;
fredc0f420372012-04-12 00:02:00 -070021import android.bluetooth.BluetoothAdapter;
Benjamin Franze8b98922014-11-12 15:57:54 +000022import android.bluetooth.BluetoothProfile;
fredc0f420372012-04-12 00:02:00 -070023import android.bluetooth.IBluetooth;
fredcbf072a72012-05-09 16:52:50 -070024import android.bluetooth.IBluetoothCallback;
Wei Wange4a744b2015-06-11 17:50:29 -070025import android.bluetooth.IBluetoothGatt;
Benjamin Franze8b98922014-11-12 15:57:54 +000026import android.bluetooth.IBluetoothHeadset;
fredc0f420372012-04-12 00:02:00 -070027import android.bluetooth.IBluetoothManager;
28import android.bluetooth.IBluetoothManagerCallback;
Benjamin Franze8b98922014-11-12 15:57:54 +000029import android.bluetooth.IBluetoothProfileServiceConnection;
fredc0f420372012-04-12 00:02:00 -070030import android.bluetooth.IBluetoothStateChangeCallback;
fredc0f420372012-04-12 00:02:00 -070031import android.content.BroadcastReceiver;
32import android.content.ComponentName;
33import android.content.ContentResolver;
34import android.content.Context;
35import android.content.Intent;
36import android.content.IntentFilter;
37import android.content.ServiceConnection;
Svetoslav Ganovc2ac5bd2016-06-29 17:31:44 -070038import android.content.pm.ApplicationInfo;
Matthew Xie32ab77b2013-05-08 19:26:57 -070039import android.content.pm.PackageManager;
Benjamin Franze8b98922014-11-12 15:57:54 +000040import android.content.pm.UserInfo;
Wei Wange4a744b2015-06-11 17:50:29 -070041import android.database.ContentObserver;
Zhihai Xu40874a02012-10-08 17:57:03 -070042import android.os.Binder;
Lenka Trochtova13a05192016-12-02 12:19:39 +010043import android.os.Bundle;
Svetoslav Ganovc2ac5bd2016-06-29 17:31:44 -070044import android.os.Build;
fredc0f420372012-04-12 00:02:00 -070045import android.os.Handler;
fredc0f420372012-04-12 00:02:00 -070046import android.os.IBinder;
Zhihai Xu40874a02012-10-08 17:57:03 -070047import android.os.Looper;
fredc0f420372012-04-12 00:02:00 -070048import android.os.Message;
Zhihai Xu40874a02012-10-08 17:57:03 -070049import android.os.Process;
fredcd6883532012-04-25 17:46:13 -070050import android.os.RemoteCallbackList;
fredc0f420372012-04-12 00:02:00 -070051import android.os.RemoteException;
Zhihai Xu40874a02012-10-08 17:57:03 -070052import android.os.SystemClock;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070053import android.os.UserHandle;
Benjamin Franze8b98922014-11-12 15:57:54 +000054import android.os.UserManager;
Lenka Trochtova13a05192016-12-02 12:19:39 +010055import android.os.UserManagerInternal;
56import android.os.UserManagerInternal.UserRestrictionsListener;
fredc0f420372012-04-12 00:02:00 -070057import android.provider.Settings;
Wei Wang67d84162015-04-26 17:04:29 -070058import android.provider.Settings.SettingNotFoundException;
Jeff Sharkey67609c72016-03-05 14:29:13 -070059import android.util.Slog;
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -070060import java.util.concurrent.locks.ReentrantReadWriteLock;
Mike Lockwood726d4de2014-10-28 14:06:28 -070061
62import java.io.FileDescriptor;
63import java.io.PrintWriter;
Marie Janssen2977c3e2016-11-09 12:01:24 -080064import java.util.concurrent.ConcurrentHashMap;
Benjamin Franze8b98922014-11-12 15:57:54 +000065import java.util.HashMap;
66import java.util.Map;
Miao Chou658bf2f2015-06-26 17:14:35 -070067
fredc0f420372012-04-12 00:02:00 -070068class BluetoothManagerService extends IBluetoothManager.Stub {
69 private static final String TAG = "BluetoothManagerService";
Pavlin Radoslavov41401112016-06-27 15:25:18 -070070 private static final boolean DBG = true;
fredc0f420372012-04-12 00:02:00 -070071
fredc0f420372012-04-12 00:02:00 -070072 private static final String BLUETOOTH_ADMIN_PERM = android.Manifest.permission.BLUETOOTH_ADMIN;
73 private static final String BLUETOOTH_PERM = android.Manifest.permission.BLUETOOTH;
fredc0f420372012-04-12 00:02:00 -070074 private static final String ACTION_SERVICE_STATE_CHANGED="com.android.bluetooth.btservice.action.STATE_CHANGED";
75 private static final String EXTRA_ACTION="action";
Zhihai Xud31c3222012-10-31 16:08:57 -070076 private static final String SECURE_SETTINGS_BLUETOOTH_ADDR_VALID="bluetooth_addr_valid";
fredc0f420372012-04-12 00:02:00 -070077 private static final String SECURE_SETTINGS_BLUETOOTH_ADDRESS="bluetooth_address";
78 private static final String SECURE_SETTINGS_BLUETOOTH_NAME="bluetooth_name";
fredc0f420372012-04-12 00:02:00 -070079 private static final int TIMEOUT_BIND_MS = 3000; //Maximum msec to wait for a bind
80 private static final int TIMEOUT_SAVE_MS = 500; //Maximum msec to wait for a save
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +053081 //Maximum msec to wait for service restart
82 private static final int SERVICE_RESTART_TIME_MS = 200;
Zhihai Xudd9d17d2013-01-08 17:05:58 -080083 //Maximum msec to wait for restart due to error
84 private static final int ERROR_RESTART_TIME_MS = 3000;
Zhihai Xu40874a02012-10-08 17:57:03 -070085 //Maximum msec to delay MESSAGE_USER_SWITCHED
86 private static final int USER_SWITCHED_TIME_MS = 200;
Benjamin Franze8b98922014-11-12 15:57:54 +000087 // Delay for the addProxy function in msec
88 private static final int ADD_PROXY_DELAY_MS = 100;
fredc0f420372012-04-12 00:02:00 -070089
90 private static final int MESSAGE_ENABLE = 1;
91 private static final int MESSAGE_DISABLE = 2;
fredc649fe492012-04-19 01:07:18 -070092 private static final int MESSAGE_REGISTER_ADAPTER = 20;
93 private static final int MESSAGE_UNREGISTER_ADAPTER = 21;
94 private static final int MESSAGE_REGISTER_STATE_CHANGE_CALLBACK = 30;
95 private static final int MESSAGE_UNREGISTER_STATE_CHANGE_CALLBACK = 31;
96 private static final int MESSAGE_BLUETOOTH_SERVICE_CONNECTED = 40;
97 private static final int MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED = 41;
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +053098 private static final int MESSAGE_RESTART_BLUETOOTH_SERVICE = 42;
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -070099 private static final int MESSAGE_BLUETOOTH_STATE_CHANGE = 60;
100 private static final int MESSAGE_TIMEOUT_BIND = 100;
101 private static final int MESSAGE_TIMEOUT_UNBIND = 101;
Ajay Panicker4bb48302016-03-31 14:14:27 -0700102 private static final int MESSAGE_GET_NAME_AND_ADDRESS = 200;
Zhihai Xu40874a02012-10-08 17:57:03 -0700103 private static final int MESSAGE_USER_SWITCHED = 300;
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -0700104 private static final int MESSAGE_USER_UNLOCKED = 301;
Benjamin Franze8b98922014-11-12 15:57:54 +0000105 private static final int MESSAGE_ADD_PROXY_DELAYED = 400;
106 private static final int MESSAGE_BIND_PROFILE_SERVICE = 401;
Marie Janssencb21ad72016-12-13 10:51:02 -0800107
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -0700108 private static final int MAX_SAVE_RETRIES = 3;
109 private static final int MAX_ERROR_RESTART_RETRIES = 6;
Zhihai Xudd9d17d2013-01-08 17:05:58 -0800110
Zhihai Xu401202b2012-12-03 11:36:21 -0800111 // Bluetooth persisted setting is off
112 private static final int BLUETOOTH_OFF=0;
113 // Bluetooth persisted setting is on
114 // and Airplane mode won't affect Bluetooth state at start up
115 private static final int BLUETOOTH_ON_BLUETOOTH=1;
116 // Bluetooth persisted setting is on
117 // but Airplane mode will affect Bluetooth state at start up
118 // and Airplane mode will have higher priority.
119 private static final int BLUETOOTH_ON_AIRPLANE=2;
fredc0f420372012-04-12 00:02:00 -0700120
Matthew Xieddf7e472013-03-01 18:41:02 -0800121 private static final int SERVICE_IBLUETOOTH = 1;
122 private static final int SERVICE_IBLUETOOTHGATT = 2;
123
fredc0f420372012-04-12 00:02:00 -0700124 private final Context mContext;
Matthew Xiecdce0b92012-07-12 19:06:15 -0700125
126 // Locks are not provided for mName and mAddress.
127 // They are accessed in handler or broadcast receiver, same thread context.
fredc0f420372012-04-12 00:02:00 -0700128 private String mAddress;
129 private String mName;
Matthew Xie6fde3092012-07-11 17:10:07 -0700130 private final ContentResolver mContentResolver;
131 private final RemoteCallbackList<IBluetoothManagerCallback> mCallbacks;
132 private final RemoteCallbackList<IBluetoothStateChangeCallback> mStateChangeCallbacks;
Marie Janssen9db28eb2016-01-12 16:05:15 -0800133 private IBinder mBluetoothBinder;
fredc649fe492012-04-19 01:07:18 -0700134 private IBluetooth mBluetooth;
Matthew Xieddf7e472013-03-01 18:41:02 -0800135 private IBluetoothGatt mBluetoothGatt;
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700136 private final ReentrantReadWriteLock mBluetoothLock =
137 new ReentrantReadWriteLock();
fredc649fe492012-04-19 01:07:18 -0700138 private boolean mBinding;
139 private boolean mUnbinding;
Zhihai Xu401202b2012-12-03 11:36:21 -0800140 // used inside handler thread
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700141 private boolean mQuietEnable = false;
Zhihai Xu401202b2012-12-03 11:36:21 -0800142 // configuarion from external IBinder call which is used to
143 // synchronize with broadcast receiver.
144 private boolean mQuietEnableExternal;
145 // configuarion from external IBinder call which is used to
146 // synchronize with broadcast receiver.
147 private boolean mEnableExternal;
148 // used inside handler thread
Zhihai Xu40874a02012-10-08 17:57:03 -0700149 private boolean mEnable;
150 private int mState;
Zhihai Xu40874a02012-10-08 17:57:03 -0700151 private final BluetoothHandler mHandler;
Zhihai Xudd9d17d2013-01-08 17:05:58 -0800152 private int mErrorRecoveryRetryCounter;
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200153 private final int mSystemUiUid;
fredc0f420372012-04-12 00:02:00 -0700154
Benjamin Franze8b98922014-11-12 15:57:54 +0000155 // Save a ProfileServiceConnections object for each of the bound
156 // bluetooth profile services
157 private final Map <Integer, ProfileServiceConnections> mProfileServices =
158 new HashMap <Integer, ProfileServiceConnections>();
159
Svetoslav Ganovc2ac5bd2016-06-29 17:31:44 -0700160 private final boolean mPermissionReviewRequired;
161
fredc649fe492012-04-19 01:07:18 -0700162 private void registerForAirplaneMode(IntentFilter filter) {
163 final ContentResolver resolver = mContext.getContentResolver();
Christopher Tatec09cdce2012-09-10 16:50:14 -0700164 final String airplaneModeRadios = Settings.Global.getString(resolver,
165 Settings.Global.AIRPLANE_MODE_RADIOS);
166 final String toggleableRadios = Settings.Global.getString(resolver,
167 Settings.Global.AIRPLANE_MODE_TOGGLEABLE_RADIOS);
fredc649fe492012-04-19 01:07:18 -0700168 boolean mIsAirplaneSensitive = airplaneModeRadios == null ? true :
Christopher Tatec09cdce2012-09-10 16:50:14 -0700169 airplaneModeRadios.contains(Settings.Global.RADIO_BLUETOOTH);
fredc649fe492012-04-19 01:07:18 -0700170 if (mIsAirplaneSensitive) {
171 filter.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED);
172 }
173 }
174
fredcbf072a72012-05-09 16:52:50 -0700175 private final IBluetoothCallback mBluetoothCallback = new IBluetoothCallback.Stub() {
176 @Override
177 public void onBluetoothStateChange(int prevState, int newState) throws RemoteException {
178 Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_STATE_CHANGE,prevState,newState);
179 mHandler.sendMessage(msg);
180 }
181 };
182
Lenka Trochtova13a05192016-12-02 12:19:39 +0100183 private final UserRestrictionsListener mUserRestrictionsListener =
184 new UserRestrictionsListener() {
185 @Override
186 public void onUserRestrictionsChanged(int userId, Bundle newRestrictions,
187 Bundle prevRestrictions) {
188 final boolean bluetoothDisallowed =
189 newRestrictions.getBoolean(UserManager.DISALLOW_BLUETOOTH);
190 if ((mEnable || mEnableExternal) && bluetoothDisallowed) {
Svetoslav Ganovc2ac5bd2016-06-29 17:31:44 -0700191 try {
192 disable("android.os.UserManagerInternal", true);
193 } catch (RemoteException e) {
194 // Shouldn't happen: startConsentUiIfNeeded not called
195 // when from system.
196 }
Lenka Trochtova13a05192016-12-02 12:19:39 +0100197 }
198 }
199 };
200
fredcbf072a72012-05-09 16:52:50 -0700201 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
fredc0f420372012-04-12 00:02:00 -0700202 @Override
203 public void onReceive(Context context, Intent intent) {
204 String action = intent.getAction();
fredcbf072a72012-05-09 16:52:50 -0700205 if (BluetoothAdapter.ACTION_LOCAL_NAME_CHANGED.equals(action)) {
fredc0f420372012-04-12 00:02:00 -0700206 String newName = intent.getStringExtra(BluetoothAdapter.EXTRA_LOCAL_NAME);
Jeff Sharkey67609c72016-03-05 14:29:13 -0700207 if (DBG) Slog.d(TAG, "Bluetooth Adapter name changed to " + newName);
fredc0f420372012-04-12 00:02:00 -0700208 if (newName != null) {
209 storeNameAndAddress(newName, null);
210 }
fredc649fe492012-04-19 01:07:18 -0700211 } else if (Intent.ACTION_AIRPLANE_MODE_CHANGED.equals(action)) {
Zhihai Xu401202b2012-12-03 11:36:21 -0800212 synchronized(mReceiver) {
213 if (isBluetoothPersistedStateOn()) {
214 if (isAirplaneModeOn()) {
215 persistBluetoothSetting(BLUETOOTH_ON_AIRPLANE);
216 } else {
217 persistBluetoothSetting(BLUETOOTH_ON_BLUETOOTH);
218 }
219 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800220
221 int st = BluetoothAdapter.STATE_OFF;
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700222 try {
223 mBluetoothLock.readLock().lock();
224 if (mBluetooth != null) {
Nitin Arorad055adb2015-03-02 15:03:51 -0800225 st = mBluetooth.getState();
Nitin Arorad055adb2015-03-02 15:03:51 -0800226 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700227 } catch (RemoteException e) {
228 Slog.e(TAG, "Unable to call getState", e);
229 } finally {
230 mBluetoothLock.readLock().unlock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800231 }
Marie Janssencb21ad72016-12-13 10:51:02 -0800232 Slog.d(TAG, "State " + BluetoothAdapter.nameForState(st));
Nitin Arorad055adb2015-03-02 15:03:51 -0800233
Zhihai Xu401202b2012-12-03 11:36:21 -0800234 if (isAirplaneModeOn()) {
Nitin Arorad055adb2015-03-02 15:03:51 -0800235 // Clear registered LE apps to force shut-off
Marie Janssen2977c3e2016-11-09 12:01:24 -0800236 clearBleApps();
Nitin Arorad055adb2015-03-02 15:03:51 -0800237 if (st == BluetoothAdapter.STATE_BLE_ON) {
238 //if state is BLE_ON make sure you trigger disableBLE part
239 try {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700240 mBluetoothLock.readLock().lock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800241 if (mBluetooth != null) {
242 mBluetooth.onBrEdrDown();
Marie Janssen6a383a72016-10-25 10:47:51 -0700243 mEnable = false;
Nitin Arorad055adb2015-03-02 15:03:51 -0800244 mEnableExternal = false;
245 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700246 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700247 Slog.e(TAG,"Unable to call onBrEdrDown", e);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700248 } finally {
Pavlin Radoslavov7ee53be2016-06-09 12:58:07 -0700249 mBluetoothLock.readLock().unlock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800250 }
251 } else if (st == BluetoothAdapter.STATE_ON){
252 // disable without persisting the setting
Jeff Sharkey67609c72016-03-05 14:29:13 -0700253 Slog.d(TAG, "Calling disable");
Nitin Arorad055adb2015-03-02 15:03:51 -0800254 sendDisableMsg();
255 }
Zhihai Xu401202b2012-12-03 11:36:21 -0800256 } else if (mEnableExternal) {
257 // enable without persisting the setting
Jeff Sharkey67609c72016-03-05 14:29:13 -0700258 Slog.d(TAG, "Calling enable");
Zhihai Xu401202b2012-12-03 11:36:21 -0800259 sendEnableMsg(mQuietEnableExternal);
260 }
fredc649fe492012-04-19 01:07:18 -0700261 }
fredc0f420372012-04-12 00:02:00 -0700262 }
263 }
264 };
265
266 BluetoothManagerService(Context context) {
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700267 mHandler = new BluetoothHandler(IoThread.get().getLooper());
Zhihai Xu40874a02012-10-08 17:57:03 -0700268
fredc0f420372012-04-12 00:02:00 -0700269 mContext = context;
Svetoslav Ganovc2ac5bd2016-06-29 17:31:44 -0700270
271 mPermissionReviewRequired = Build.PERMISSIONS_REVIEW_REQUIRED
272 || context.getResources().getBoolean(
273 com.android.internal.R.bool.config_permissionReviewRequired);
274
fredc0f420372012-04-12 00:02:00 -0700275 mBluetooth = null;
Marie Janssen9db28eb2016-01-12 16:05:15 -0800276 mBluetoothBinder = null;
Nitin Arorad055adb2015-03-02 15:03:51 -0800277 mBluetoothGatt = null;
fredc0f420372012-04-12 00:02:00 -0700278 mBinding = false;
279 mUnbinding = false;
Zhihai Xu40874a02012-10-08 17:57:03 -0700280 mEnable = false;
281 mState = BluetoothAdapter.STATE_OFF;
Zhihai Xu401202b2012-12-03 11:36:21 -0800282 mQuietEnableExternal = false;
283 mEnableExternal = false;
fredc0f420372012-04-12 00:02:00 -0700284 mAddress = null;
285 mName = null;
Zhihai Xudd9d17d2013-01-08 17:05:58 -0800286 mErrorRecoveryRetryCounter = 0;
fredc0f420372012-04-12 00:02:00 -0700287 mContentResolver = context.getContentResolver();
Wei Wange4a744b2015-06-11 17:50:29 -0700288 // Observe BLE scan only mode settings change.
289 registerForBleScanModeChange();
fredcd6883532012-04-25 17:46:13 -0700290 mCallbacks = new RemoteCallbackList<IBluetoothManagerCallback>();
291 mStateChangeCallbacks = new RemoteCallbackList<IBluetoothStateChangeCallback>();
Miao Chou658bf2f2015-06-26 17:14:35 -0700292 IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_LOCAL_NAME_CHANGED);
Matthew Xie6fde3092012-07-11 17:10:07 -0700293 registerForAirplaneMode(filter);
Dianne Hackbornd83a0962014-05-02 16:28:33 -0700294 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
Matthew Xie6fde3092012-07-11 17:10:07 -0700295 mContext.registerReceiver(mReceiver, filter);
fredc0f420372012-04-12 00:02:00 -0700296 loadStoredNameAndAddress();
Zhihai Xu401202b2012-12-03 11:36:21 -0800297 if (isBluetoothPersistedStateOn()) {
298 mEnableExternal = true;
fredc0f420372012-04-12 00:02:00 -0700299 }
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200300
301 int sysUiUid = -1;
302 try {
Jeff Sharkeye06b4d12016-01-06 14:51:50 -0700303 sysUiUid = mContext.getPackageManager().getPackageUidAsUser("com.android.systemui",
Jeff Sharkeyc5967e92016-01-07 18:50:29 -0700304 PackageManager.MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM);
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200305 } catch (PackageManager.NameNotFoundException e) {
Joe LaPennaacddf2b2015-09-04 12:52:42 -0700306 // Some platforms, such as wearables do not have a system ui.
Jeff Sharkey67609c72016-03-05 14:29:13 -0700307 Slog.w(TAG, "Unable to resolve SystemUI's UID.", e);
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200308 }
309 mSystemUiUid = sysUiUid;
fredc0f420372012-04-12 00:02:00 -0700310 }
311
fredc649fe492012-04-19 01:07:18 -0700312 /**
313 * Returns true if airplane mode is currently on
314 */
315 private final boolean isAirplaneModeOn() {
Christopher Tatec09cdce2012-09-10 16:50:14 -0700316 return Settings.Global.getInt(mContext.getContentResolver(),
317 Settings.Global.AIRPLANE_MODE_ON, 0) == 1;
fredc649fe492012-04-19 01:07:18 -0700318 }
319
320 /**
321 * Returns true if the Bluetooth saved state is "on"
322 */
323 private final boolean isBluetoothPersistedStateOn() {
Jeff Brownbf6f6f92012-09-25 15:03:20 -0700324 return Settings.Global.getInt(mContentResolver,
Andre Eisenbach8c184312016-09-06 18:03:10 -0700325 Settings.Global.BLUETOOTH_ON, BLUETOOTH_ON_BLUETOOTH) != BLUETOOTH_OFF;
Zhihai Xu401202b2012-12-03 11:36:21 -0800326 }
327
328 /**
329 * Returns true if the Bluetooth saved state is BLUETOOTH_ON_BLUETOOTH
330 */
331 private final boolean isBluetoothPersistedStateOnBluetooth() {
332 return Settings.Global.getInt(mContentResolver,
Andre Eisenbach8c184312016-09-06 18:03:10 -0700333 Settings.Global.BLUETOOTH_ON, BLUETOOTH_ON_BLUETOOTH) == BLUETOOTH_ON_BLUETOOTH;
fredc649fe492012-04-19 01:07:18 -0700334 }
335
336 /**
337 * Save the Bluetooth on/off state
fredc649fe492012-04-19 01:07:18 -0700338 */
Zhihai Xu401202b2012-12-03 11:36:21 -0800339 private void persistBluetoothSetting(int value) {
Marie Janssened50bbc2016-12-15 13:51:30 -0800340 if (DBG) Slog.d(TAG, "Persisting Bluetooth Setting: " + value);
341 // waive WRITE_SECURE_SETTINGS permission check
342 long callingIdentity = Binder.clearCallingIdentity();
Jeff Brownbf6f6f92012-09-25 15:03:20 -0700343 Settings.Global.putInt(mContext.getContentResolver(),
344 Settings.Global.BLUETOOTH_ON,
Zhihai Xu401202b2012-12-03 11:36:21 -0800345 value);
Marie Janssened50bbc2016-12-15 13:51:30 -0800346 Binder.restoreCallingIdentity(callingIdentity);
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");
Marie Janssencb21ad72016-12-13 10:51:02 -0800429 if (callback == null) {
430 Slog.w(TAG, "registerStateChangeCallback: Callback is null!");
431 return;
432 }
fredc0f420372012-04-12 00:02:00 -0700433 Message msg = mHandler.obtainMessage(MESSAGE_REGISTER_STATE_CHANGE_CALLBACK);
434 msg.obj = callback;
435 mHandler.sendMessage(msg);
436 }
437
438 public void unregisterStateChangeCallback(IBluetoothStateChangeCallback callback) {
439 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
440 "Need BLUETOOTH permission");
Marie Janssencb21ad72016-12-13 10:51:02 -0800441 if (callback == null) {
442 Slog.w(TAG, "unregisterStateChangeCallback: Callback is null!");
443 return;
444 }
fredc0f420372012-04-12 00:02:00 -0700445 Message msg = mHandler.obtainMessage(MESSAGE_UNREGISTER_STATE_CHANGE_CALLBACK);
446 msg.obj = callback;
447 mHandler.sendMessage(msg);
448 }
449
450 public boolean isEnabled() {
Zhihai Xu6eb76522012-11-29 15:41:04 -0800451 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
452 (!checkIfCallerIsForegroundUser())) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700453 Slog.w(TAG,"isEnabled(): not allowed for non-active and non system user");
Zhihai Xu40874a02012-10-08 17:57:03 -0700454 return false;
455 }
456
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700457 try {
458 mBluetoothLock.readLock().lock();
459 if (mBluetooth != null) return mBluetooth.isEnabled();
460 } catch (RemoteException e) {
461 Slog.e(TAG, "isEnabled()", e);
462 } finally {
463 mBluetoothLock.readLock().unlock();
fredc0f420372012-04-12 00:02:00 -0700464 }
465 return false;
466 }
467
Christine Hallstrom995c90a2016-05-25 15:49:08 -0700468 public int getState() {
469 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
470 (!checkIfCallerIsForegroundUser())) {
Marie Janssencb21ad72016-12-13 10:51:02 -0800471 Slog.w(TAG, "getState(): report OFF for non-active and non system user");
Christine Hallstrom995c90a2016-05-25 15:49:08 -0700472 return BluetoothAdapter.STATE_OFF;
473 }
474
475 try {
476 mBluetoothLock.readLock().lock();
477 if (mBluetooth != null) return mBluetooth.getState();
478 } catch (RemoteException e) {
479 Slog.e(TAG, "getState()", e);
480 } finally {
481 mBluetoothLock.readLock().unlock();
482 }
483 return BluetoothAdapter.STATE_OFF;
484 }
485
Nitin Arorad055adb2015-03-02 15:03:51 -0800486 class ClientDeathRecipient implements IBinder.DeathRecipient {
487 public void binderDied() {
Marie Janssen6a383a72016-10-25 10:47:51 -0700488 if (DBG) Slog.d(TAG, "Binder is dead - unregister Ble App");
Marie Janssen2977c3e2016-11-09 12:01:24 -0800489 if (isBleAppPresent()) {
490 // Nothing to do, another app is here.
491 return;
492 }
493 if (DBG) Slog.d(TAG, "Disabling LE only mode after application crash");
494 try {
495 mBluetoothLock.readLock().lock();
496 if (mBluetooth != null &&
497 mBluetooth.getState() == BluetoothAdapter.STATE_BLE_ON) {
498 mEnable = false;
499 mBluetooth.onBrEdrDown();
Nitin Arorad055adb2015-03-02 15:03:51 -0800500 }
Marie Janssen2977c3e2016-11-09 12:01:24 -0800501 } catch (RemoteException e) {
502 Slog.e(TAG,"Unable to call onBrEdrDown", e);
503 } finally {
504 mBluetoothLock.readLock().unlock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800505 }
506 }
507 }
508
509 /** Internal death rec list */
Marie Janssen2977c3e2016-11-09 12:01:24 -0800510 Map<IBinder, ClientDeathRecipient> mBleApps = new ConcurrentHashMap<IBinder, ClientDeathRecipient>();
Nitin Arorad055adb2015-03-02 15:03:51 -0800511
Wei Wang67d84162015-04-26 17:04:29 -0700512 @Override
513 public boolean isBleScanAlwaysAvailable() {
Marie Janssen6a383a72016-10-25 10:47:51 -0700514 if (isAirplaneModeOn() && !mEnable) {
515 return false;
516 }
Wei Wang67d84162015-04-26 17:04:29 -0700517 try {
518 return (Settings.Global.getInt(mContentResolver,
519 Settings.Global.BLE_SCAN_ALWAYS_AVAILABLE)) != 0;
520 } catch (SettingNotFoundException e) {
521 }
522 return false;
523 }
524
Wei Wange4a744b2015-06-11 17:50:29 -0700525 // Monitor change of BLE scan only mode settings.
526 private void registerForBleScanModeChange() {
527 ContentObserver contentObserver = new ContentObserver(null) {
528 @Override
529 public void onChange(boolean selfChange) {
Marie Janssen2977c3e2016-11-09 12:01:24 -0800530 if (isBleScanAlwaysAvailable()) {
531 // Nothing to do
532 return;
533 }
534 // BLE scan is not available.
535 disableBleScanMode();
536 clearBleApps();
537 try {
538 mBluetoothLock.readLock().lock();
539 if (mBluetooth != null) mBluetooth.onBrEdrDown();
540 } catch (RemoteException e) {
541 Slog.e(TAG, "error when disabling bluetooth", e);
542 } finally {
543 mBluetoothLock.readLock().unlock();
Wei Wange4a744b2015-06-11 17:50:29 -0700544 }
545 }
546 };
547
548 mContentResolver.registerContentObserver(
549 Settings.Global.getUriFor(Settings.Global.BLE_SCAN_ALWAYS_AVAILABLE),
550 false, contentObserver);
551 }
552
553 // Disable ble scan only mode.
554 private void disableBleScanMode() {
555 try {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700556 mBluetoothLock.writeLock().lock();
Wei Wange4a744b2015-06-11 17:50:29 -0700557 if (mBluetooth != null && (mBluetooth.getState() != BluetoothAdapter.STATE_ON)) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700558 if (DBG) Slog.d(TAG, "Reseting the mEnable flag for clean disable");
Wei Wange4a744b2015-06-11 17:50:29 -0700559 mEnable = false;
560 }
561 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700562 Slog.e(TAG, "getState()", e);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700563 } finally {
564 mBluetoothLock.writeLock().unlock();
Wei Wange4a744b2015-06-11 17:50:29 -0700565 }
566 }
567
Nitin Arorad055adb2015-03-02 15:03:51 -0800568 public int updateBleAppCount(IBinder token, boolean enable) {
569 if (enable) {
570 ClientDeathRecipient r = mBleApps.get(token);
571 if (r == null) {
572 ClientDeathRecipient deathRec = new ClientDeathRecipient();
573 try {
574 token.linkToDeath(deathRec, 0);
575 } catch (RemoteException ex) {
576 throw new IllegalArgumentException("Wake lock is already dead.");
577 }
578 mBleApps.put(token, deathRec);
Jeff Sharkey67609c72016-03-05 14:29:13 -0700579 if (DBG) Slog.d(TAG, "Registered for death Notification");
Nitin Arorad055adb2015-03-02 15:03:51 -0800580 }
581
582 } else {
583 ClientDeathRecipient r = mBleApps.get(token);
584 if (r != null) {
Wei Wange4a744b2015-06-11 17:50:29 -0700585 // Unregister death recipient as the app goes away.
586 token.unlinkToDeath(r, 0);
Nitin Arorad055adb2015-03-02 15:03:51 -0800587 mBleApps.remove(token);
Jeff Sharkey67609c72016-03-05 14:29:13 -0700588 if (DBG) Slog.d(TAG, "Unregistered for death Notification");
Nitin Arorad055adb2015-03-02 15:03:51 -0800589 }
590 }
Marie Janssen2977c3e2016-11-09 12:01:24 -0800591 int appCount = mBleApps.size();
592 if (DBG) Slog.d(TAG, appCount + " registered Ble Apps");
593 if (appCount == 0 && mEnable) {
Wei Wange4a744b2015-06-11 17:50:29 -0700594 disableBleScanMode();
Nitin Arorad055adb2015-03-02 15:03:51 -0800595 }
Marie Janssen2977c3e2016-11-09 12:01:24 -0800596 return appCount;
Nitin Arorad055adb2015-03-02 15:03:51 -0800597 }
598
Wei Wange4a744b2015-06-11 17:50:29 -0700599 // Clear all apps using BLE scan only mode.
600 private void clearBleApps() {
Marie Janssen2977c3e2016-11-09 12:01:24 -0800601 mBleApps.clear();
Wei Wange4a744b2015-06-11 17:50:29 -0700602 }
603
Nitin Arorad055adb2015-03-02 15:03:51 -0800604 /** @hide*/
605 public boolean isBleAppPresent() {
Marie Janssen2977c3e2016-11-09 12:01:24 -0800606 if (DBG) Slog.d(TAG, "isBleAppPresent() count: " + mBleApps.size());
607 return mBleApps.size() > 0;
Nitin Arorad055adb2015-03-02 15:03:51 -0800608 }
609
610 /**
Marie Janssened50bbc2016-12-15 13:51:30 -0800611 * Action taken when GattService is turned on
Nitin Arorad055adb2015-03-02 15:03:51 -0800612 */
613 private void onBluetoothGattServiceUp() {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700614 if (DBG) Slog.d(TAG,"BluetoothGatt Service is Up");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700615 try {
616 mBluetoothLock.readLock().lock();
Marie Janssened50bbc2016-12-15 13:51:30 -0800617 if (mBluetooth == null) {
618 if (DBG) Slog.w(TAG, "onBluetoothServiceUp: mBluetooth is null!");
619 return;
620 }
621 int st = mBluetooth.getState();
622 if (st != BluetoothAdapter.STATE_BLE_ON) {
623 if (DBG) Slog.v(TAG, "onBluetoothServiceUp: state isn't BLE_ON: " +
624 BluetoothAdapter.nameForState(st));
625 return;
626 }
627 if (isBluetoothPersistedStateOnBluetooth() || !isBleAppPresent()) {
628 // This triggers transition to STATE_ON
Nitin Arorad055adb2015-03-02 15:03:51 -0800629 mBluetooth.onLeServiceUp();
Nitin Arorad055adb2015-03-02 15:03:51 -0800630 persistBluetoothSetting(BLUETOOTH_ON_BLUETOOTH);
Nitin Arorad055adb2015-03-02 15:03:51 -0800631 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700632 } catch (RemoteException e) {
633 Slog.e(TAG,"Unable to call onServiceUp", e);
634 } finally {
635 mBluetoothLock.readLock().unlock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800636 }
637 }
638
639 /**
640 * Inform BluetoothAdapter instances that BREDR part is down
641 * and turn off all service and stack if no LE app needs it
642 */
643 private void sendBrEdrDownCallback() {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700644 if (DBG) Slog.d(TAG,"Calling sendBrEdrDownCallback callbacks");
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700645
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700646 if (mBluetooth == null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700647 Slog.w(TAG, "Bluetooth handle is null");
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700648 return;
649 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800650
651 if (isBleAppPresent() == false) {
652 try {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700653 mBluetoothLock.readLock().lock();
654 if (mBluetooth != null) mBluetooth.onBrEdrDown();
655 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700656 Slog.e(TAG, "Call to onBrEdrDown() failed.", e);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700657 } finally {
658 mBluetoothLock.readLock().unlock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800659 }
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700660 } else {
661 // Need to stay at BLE ON. Disconnect all Gatt connections
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700662 try {
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700663 mBluetoothGatt.unregAll();
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700664 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700665 Slog.e(TAG, "Unable to disconnect all apps.", e);
Nitin Arorad055adb2015-03-02 15:03:51 -0800666 }
667 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800668 }
669
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700670 public boolean enableNoAutoConnect()
671 {
Lenka Trochtova13a05192016-12-02 12:19:39 +0100672 if (isBluetoothDisallowed()) {
673 if (DBG) {
674 Slog.d(TAG, "enableNoAutoConnect(): not enabling - bluetooth disallowed");
675 }
676 return false;
677 }
678
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700679 mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
680 "Need BLUETOOTH ADMIN permission");
Zhihai Xu40874a02012-10-08 17:57:03 -0700681
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700682 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700683 Slog.d(TAG,"enableNoAutoConnect(): mBluetooth =" + mBluetooth +
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700684 " mBinding = " + mBinding);
685 }
Martijn Coenen8385c5a2012-11-29 10:14:16 -0800686 int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
687
688 if (callingAppId != Process.NFC_UID) {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700689 throw new SecurityException("no permission to enable Bluetooth quietly");
690 }
Martijn Coenen8385c5a2012-11-29 10:14:16 -0800691
Zhihai Xu401202b2012-12-03 11:36:21 -0800692 synchronized(mReceiver) {
693 mQuietEnableExternal = true;
694 mEnableExternal = true;
695 sendEnableMsg(true);
696 }
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700697 return true;
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700698 }
Ajay Panicker4bb48302016-03-31 14:14:27 -0700699
Svetoslav Ganovc2ac5bd2016-06-29 17:31:44 -0700700 public boolean enable(String packageName) throws RemoteException {
Lenka Trochtova13a05192016-12-02 12:19:39 +0100701 if (isBluetoothDisallowed()) {
702 if (DBG) {
703 Slog.d(TAG,"enable(): not enabling - bluetooth disallowed");
704 }
705 return false;
706 }
707
Svetoslav Ganovc2ac5bd2016-06-29 17:31:44 -0700708 final int callingUid = Binder.getCallingUid();
709 final boolean callerSystem = UserHandle.getAppId(callingUid) == Process.SYSTEM_UID;
710
711 if (!callerSystem) {
712 if (!checkIfCallerIsForegroundUser()) {
713 Slog.w(TAG, "enable(): not allowed for non-active and non system user");
714 return false;
715 }
716
717 mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
718 "Need BLUETOOTH ADMIN permission");
719
Ivan Podogovafababd2016-12-05 16:46:52 +0000720 if (!isEnabled() && mPermissionReviewRequired) {
721 startConsentUi(packageName, callingUid, BluetoothAdapter.ACTION_REQUEST_ENABLE);
Svetoslav Ganovc2ac5bd2016-06-29 17:31:44 -0700722 return false;
723 }
fredcf2458862012-04-16 15:18:27 -0700724 }
725
Zhihai Xu401202b2012-12-03 11:36:21 -0800726 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700727 Slog.d(TAG,"enable(): mBluetooth =" + mBluetooth +
Marie Janssencb21ad72016-12-13 10:51:02 -0800728 " mBinding = " + mBinding + " mState = " +
729 BluetoothAdapter.nameForState(mState));
Sanket Agarwal090bf552016-04-21 14:10:55 -0700730 }
Zhihai Xu401202b2012-12-03 11:36:21 -0800731
732 synchronized(mReceiver) {
733 mQuietEnableExternal = false;
734 mEnableExternal = true;
735 // waive WRITE_SECURE_SETTINGS permission check
Zhihai Xu401202b2012-12-03 11:36:21 -0800736 sendEnableMsg(false);
737 }
Jeff Sharkey67609c72016-03-05 14:29:13 -0700738 if (DBG) Slog.d(TAG, "enable returning");
Zhihai Xu401202b2012-12-03 11:36:21 -0800739 return true;
fredc0f420372012-04-12 00:02:00 -0700740 }
741
Svetoslav Ganovc2ac5bd2016-06-29 17:31:44 -0700742 public boolean disable(String packageName, boolean persist) throws RemoteException {
743 final int callingUid = Binder.getCallingUid();
744 final boolean callerSystem = UserHandle.getAppId(callingUid) == Process.SYSTEM_UID;
Zhihai Xu40874a02012-10-08 17:57:03 -0700745
Svetoslav Ganovc2ac5bd2016-06-29 17:31:44 -0700746 if (!callerSystem) {
747 if (!checkIfCallerIsForegroundUser()) {
748 Slog.w(TAG, "disable(): not allowed for non-active and non system user");
749 return false;
750 }
751
752 mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
753 "Need BLUETOOTH ADMIN permission");
754
Ivan Podogovafababd2016-12-05 16:46:52 +0000755 if (isEnabled() && mPermissionReviewRequired) {
756 startConsentUi(packageName, callingUid, BluetoothAdapter.ACTION_REQUEST_DISABLE);
Svetoslav Ganovc2ac5bd2016-06-29 17:31:44 -0700757 return false;
758 }
Zhihai Xu40874a02012-10-08 17:57:03 -0700759 }
760
fredcf2458862012-04-16 15:18:27 -0700761 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700762 Slog.d(TAG,"disable(): mBluetooth = " + mBluetooth +
Matthew Xiecdce0b92012-07-12 19:06:15 -0700763 " mBinding = " + mBinding);
764 }
fredcf2458862012-04-16 15:18:27 -0700765
Zhihai Xu401202b2012-12-03 11:36:21 -0800766 synchronized(mReceiver) {
767 if (persist) {
Zhihai Xu401202b2012-12-03 11:36:21 -0800768 persistBluetoothSetting(BLUETOOTH_OFF);
Zhihai Xu401202b2012-12-03 11:36:21 -0800769 }
770 mEnableExternal = false;
771 sendDisableMsg();
772 }
fredc0f420372012-04-12 00:02:00 -0700773 return true;
774 }
775
Ivan Podogovafababd2016-12-05 16:46:52 +0000776 private void startConsentUi(String packageName, int callingUid, String intentAction)
777 throws RemoteException {
Svetoslav Ganovc2ac5bd2016-06-29 17:31:44 -0700778 try {
779 // Validate the package only if we are going to use it
780 ApplicationInfo applicationInfo = mContext.getPackageManager()
781 .getApplicationInfoAsUser(packageName,
782 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
783 UserHandle.getUserId(callingUid));
784 if (applicationInfo.uid != callingUid) {
785 throw new SecurityException("Package " + callingUid
786 + " not in uid " + callingUid);
787 }
788
Ivan Podogovafababd2016-12-05 16:46:52 +0000789 // Permission review mode, trigger a user prompt
790 Intent intent = new Intent(intentAction);
791 mContext.startActivity(intent);
Svetoslav Ganovc2ac5bd2016-06-29 17:31:44 -0700792 } catch (PackageManager.NameNotFoundException e) {
793 throw new RemoteException(e.getMessage());
794 }
Svetoslav Ganovc2ac5bd2016-06-29 17:31:44 -0700795 }
796
fredc649fe492012-04-19 01:07:18 -0700797 public void unbindAndFinish() {
fredcf2458862012-04-16 15:18:27 -0700798 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700799 Slog.d(TAG,"unbindAndFinish(): " + mBluetooth +
Marie Janssencb21ad72016-12-13 10:51:02 -0800800 " mBinding = " + mBinding + " mUnbinding = " + mUnbinding);
fredcf2458862012-04-16 15:18:27 -0700801 }
802
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700803 try {
804 mBluetoothLock.writeLock().lock();
fredc0f420372012-04-12 00:02:00 -0700805 if (mUnbinding) return;
806 mUnbinding = true;
Pavlin Radoslavove47ec142016-06-01 22:25:18 -0700807 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
Pavlin Radoslavov74f60c02016-09-21 17:28:11 -0700808 mHandler.removeMessages(MESSAGE_BIND_PROFILE_SERVICE);
Zhihai Xu40874a02012-10-08 17:57:03 -0700809 if (mBluetooth != null) {
Andre Eisenbach305fdab2015-11-11 21:43:26 -0800810 //Unregister callback object
811 try {
812 mBluetooth.unregisterCallback(mBluetoothCallback);
813 } catch (RemoteException re) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700814 Slog.e(TAG, "Unable to unregister BluetoothCallback",re);
fredcbf072a72012-05-09 16:52:50 -0700815 }
Marie Janssen9db28eb2016-01-12 16:05:15 -0800816 mBluetoothBinder = null;
fredcd6883532012-04-25 17:46:13 -0700817 mBluetooth = null;
fredc0f420372012-04-12 00:02:00 -0700818 mContext.unbindService(mConnection);
fredcd6883532012-04-25 17:46:13 -0700819 mUnbinding = false;
Zhihai Xu40874a02012-10-08 17:57:03 -0700820 mBinding = false;
fredcf2458862012-04-16 15:18:27 -0700821 } else {
Marie Janssencb21ad72016-12-13 10:51:02 -0800822 mUnbinding = false;
fredc0f420372012-04-12 00:02:00 -0700823 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800824 mBluetoothGatt = null;
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700825 } finally {
826 mBluetoothLock.writeLock().unlock();
fredc0f420372012-04-12 00:02:00 -0700827 }
828 }
829
Matthew Xieddf7e472013-03-01 18:41:02 -0800830 public IBluetoothGatt getBluetoothGatt() {
831 // sync protection
832 return mBluetoothGatt;
833 }
834
Benjamin Franze8b98922014-11-12 15:57:54 +0000835 @Override
836 public boolean bindBluetoothProfileService(int bluetoothProfile,
837 IBluetoothProfileServiceConnection proxy) {
838 if (!mEnable) {
839 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700840 Slog.d(TAG, "Trying to bind to profile: " + bluetoothProfile +
Benjamin Franze8b98922014-11-12 15:57:54 +0000841 ", while Bluetooth was disabled");
842 }
843 return false;
844 }
845 synchronized (mProfileServices) {
846 ProfileServiceConnections psc = mProfileServices.get(new Integer(bluetoothProfile));
847 if (psc == null) {
848 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700849 Slog.d(TAG, "Creating new ProfileServiceConnections object for"
Benjamin Franze8b98922014-11-12 15:57:54 +0000850 + " profile: " + bluetoothProfile);
851 }
Benjamin Franz5b614592014-12-09 18:58:45 +0000852
853 if (bluetoothProfile != BluetoothProfile.HEADSET) return false;
854
855 Intent intent = new Intent(IBluetoothHeadset.class.getName());
Benjamin Franze8b98922014-11-12 15:57:54 +0000856 psc = new ProfileServiceConnections(intent);
Benjamin Franz5b614592014-12-09 18:58:45 +0000857 if (!psc.bindService()) return false;
858
Benjamin Franze8b98922014-11-12 15:57:54 +0000859 mProfileServices.put(new Integer(bluetoothProfile), psc);
Benjamin Franze8b98922014-11-12 15:57:54 +0000860 }
861 }
862
863 // Introducing a delay to give the client app time to prepare
864 Message addProxyMsg = mHandler.obtainMessage(MESSAGE_ADD_PROXY_DELAYED);
865 addProxyMsg.arg1 = bluetoothProfile;
866 addProxyMsg.obj = proxy;
867 mHandler.sendMessageDelayed(addProxyMsg, ADD_PROXY_DELAY_MS);
868 return true;
869 }
870
871 @Override
872 public void unbindBluetoothProfileService(int bluetoothProfile,
873 IBluetoothProfileServiceConnection proxy) {
874 synchronized (mProfileServices) {
875 ProfileServiceConnections psc = mProfileServices.get(new Integer(bluetoothProfile));
876 if (psc == null) {
877 return;
878 }
879 psc.removeProxy(proxy);
880 }
881 }
882
883 private void unbindAllBluetoothProfileServices() {
884 synchronized (mProfileServices) {
885 for (Integer i : mProfileServices.keySet()) {
886 ProfileServiceConnections psc = mProfileServices.get(i);
Benjamin Franz5b614592014-12-09 18:58:45 +0000887 try {
888 mContext.unbindService(psc);
889 } catch (IllegalArgumentException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700890 Slog.e(TAG, "Unable to unbind service with intent: " + psc.mIntent, e);
Benjamin Franz5b614592014-12-09 18:58:45 +0000891 }
Benjamin Franze8b98922014-11-12 15:57:54 +0000892 psc.removeAllProxies();
893 }
894 mProfileServices.clear();
895 }
896 }
897
898 /**
Miao Chou658bf2f2015-06-26 17:14:35 -0700899 * Send enable message and set adapter name and address. Called when the boot phase becomes
900 * PHASE_SYSTEM_SERVICES_READY.
901 */
902 public void handleOnBootPhase() {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700903 if (DBG) Slog.d(TAG, "Bluetooth boot completed");
Lenka Trochtova13a05192016-12-02 12:19:39 +0100904 UserManagerInternal userManagerInternal =
905 LocalServices.getService(UserManagerInternal.class);
906 userManagerInternal.addUserRestrictionsListener(mUserRestrictionsListener);
907 if (isBluetoothDisallowed()) {
908 return;
909 }
Miao Chou658bf2f2015-06-26 17:14:35 -0700910 if (mEnableExternal && isBluetoothPersistedStateOnBluetooth()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700911 if (DBG) Slog.d(TAG, "Auto-enabling Bluetooth.");
Miao Chou658bf2f2015-06-26 17:14:35 -0700912 sendEnableMsg(mQuietEnableExternal);
Ajay Panickerbf796d82016-03-11 13:47:20 -0800913 } else if (!isNameAndAddressSet()) {
914 if (DBG) Slog.d(TAG, "Getting adapter name and address");
Ajay Panicker4bb48302016-03-31 14:14:27 -0700915 Message getMsg = mHandler.obtainMessage(MESSAGE_GET_NAME_AND_ADDRESS);
916 mHandler.sendMessage(getMsg);
Miao Chou658bf2f2015-06-26 17:14:35 -0700917 }
Miao Chou658bf2f2015-06-26 17:14:35 -0700918 }
919
920 /**
921 * Called when switching to a different foreground user.
922 */
923 public void handleOnSwitchUser(int userHandle) {
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -0700924 if (DBG) Slog.d(TAG, "User " + userHandle + " switched");
925 mHandler.obtainMessage(MESSAGE_USER_SWITCHED, userHandle, 0).sendToTarget();
926 }
927
928 /**
929 * Called when user is unlocked.
930 */
931 public void handleOnUnlockUser(int userHandle) {
932 if (DBG) Slog.d(TAG, "User " + userHandle + " unlocked");
933 mHandler.obtainMessage(MESSAGE_USER_UNLOCKED, userHandle, 0).sendToTarget();
Miao Chou658bf2f2015-06-26 17:14:35 -0700934 }
935
936 /**
Benjamin Franze8b98922014-11-12 15:57:54 +0000937 * This class manages the clients connected to a given ProfileService
938 * and maintains the connection with that service.
939 */
940 final private class ProfileServiceConnections implements ServiceConnection,
941 IBinder.DeathRecipient {
942 final RemoteCallbackList<IBluetoothProfileServiceConnection> mProxies =
943 new RemoteCallbackList <IBluetoothProfileServiceConnection>();
944 IBinder mService;
945 ComponentName mClassName;
946 Intent mIntent;
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700947 boolean mInvokingProxyCallbacks = false;
Benjamin Franze8b98922014-11-12 15:57:54 +0000948
949 ProfileServiceConnections(Intent intent) {
950 mService = null;
951 mClassName = null;
952 mIntent = intent;
953 }
954
Benjamin Franz5b614592014-12-09 18:58:45 +0000955 private boolean bindService() {
956 if (mIntent != null && mService == null &&
957 doBind(mIntent, this, 0, UserHandle.CURRENT_OR_SELF)) {
Benjamin Franze8b98922014-11-12 15:57:54 +0000958 Message msg = mHandler.obtainMessage(MESSAGE_BIND_PROFILE_SERVICE);
959 msg.obj = this;
960 mHandler.sendMessageDelayed(msg, TIMEOUT_BIND_MS);
Benjamin Franz5b614592014-12-09 18:58:45 +0000961 return true;
Benjamin Franze8b98922014-11-12 15:57:54 +0000962 }
Jeff Sharkey67609c72016-03-05 14:29:13 -0700963 Slog.w(TAG, "Unable to bind with intent: " + mIntent);
Benjamin Franz5b614592014-12-09 18:58:45 +0000964 return false;
Benjamin Franze8b98922014-11-12 15:57:54 +0000965 }
966
967 private void addProxy(IBluetoothProfileServiceConnection proxy) {
968 mProxies.register(proxy);
969 if (mService != null) {
970 try{
971 proxy.onServiceConnected(mClassName, mService);
972 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700973 Slog.e(TAG, "Unable to connect to proxy", e);
Benjamin Franze8b98922014-11-12 15:57:54 +0000974 }
975 } else {
976 if (!mHandler.hasMessages(MESSAGE_BIND_PROFILE_SERVICE, this)) {
977 Message msg = mHandler.obtainMessage(MESSAGE_BIND_PROFILE_SERVICE);
978 msg.obj = this;
979 mHandler.sendMessage(msg);
980 }
981 }
982 }
983
984 private void removeProxy(IBluetoothProfileServiceConnection proxy) {
985 if (proxy != null) {
986 if (mProxies.unregister(proxy)) {
987 try {
988 proxy.onServiceDisconnected(mClassName);
989 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700990 Slog.e(TAG, "Unable to disconnect proxy", e);
Benjamin Franze8b98922014-11-12 15:57:54 +0000991 }
992 }
993 } else {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700994 Slog.w(TAG, "Trying to remove a null proxy");
Benjamin Franze8b98922014-11-12 15:57:54 +0000995 }
996 }
997
998 private void removeAllProxies() {
999 onServiceDisconnected(mClassName);
1000 mProxies.kill();
1001 }
1002
1003 @Override
1004 public void onServiceConnected(ComponentName className, IBinder service) {
1005 // remove timeout message
1006 mHandler.removeMessages(MESSAGE_BIND_PROFILE_SERVICE, this);
1007 mService = service;
1008 mClassName = className;
1009 try {
1010 mService.linkToDeath(this, 0);
1011 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001012 Slog.e(TAG, "Unable to linkToDeath", e);
Benjamin Franze8b98922014-11-12 15:57:54 +00001013 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001014
1015 if (mInvokingProxyCallbacks) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001016 Slog.e(TAG, "Proxy callbacks already in progress.");
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001017 return;
Benjamin Franze8b98922014-11-12 15:57:54 +00001018 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001019 mInvokingProxyCallbacks = true;
1020
1021 final int n = mProxies.beginBroadcast();
1022 try {
1023 for (int i = 0; i < n; i++) {
1024 try {
1025 mProxies.getBroadcastItem(i).onServiceConnected(className, service);
1026 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001027 Slog.e(TAG, "Unable to connect to proxy", e);
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001028 }
1029 }
1030 } finally {
1031 mProxies.finishBroadcast();
1032 mInvokingProxyCallbacks = false;
1033 }
Benjamin Franze8b98922014-11-12 15:57:54 +00001034 }
1035
1036 @Override
1037 public void onServiceDisconnected(ComponentName className) {
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001038 if (mService == null) return;
Benjamin Franze8b98922014-11-12 15:57:54 +00001039 mService.unlinkToDeath(this, 0);
1040 mService = null;
1041 mClassName = null;
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001042
1043 if (mInvokingProxyCallbacks) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001044 Slog.e(TAG, "Proxy callbacks already in progress.");
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001045 return;
Benjamin Franze8b98922014-11-12 15:57:54 +00001046 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001047 mInvokingProxyCallbacks = true;
1048
1049 final int n = mProxies.beginBroadcast();
1050 try {
1051 for (int i = 0; i < n; i++) {
1052 try {
1053 mProxies.getBroadcastItem(i).onServiceDisconnected(className);
1054 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001055 Slog.e(TAG, "Unable to disconnect from proxy", e);
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001056 }
1057 }
1058 } finally {
1059 mProxies.finishBroadcast();
1060 mInvokingProxyCallbacks = false;
1061 }
Benjamin Franze8b98922014-11-12 15:57:54 +00001062 }
1063
1064 @Override
1065 public void binderDied() {
1066 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001067 Slog.w(TAG, "Profile service for profile: " + mClassName
Benjamin Franze8b98922014-11-12 15:57:54 +00001068 + " died.");
1069 }
1070 onServiceDisconnected(mClassName);
1071 // Trigger rebind
1072 Message msg = mHandler.obtainMessage(MESSAGE_BIND_PROFILE_SERVICE);
1073 msg.obj = this;
1074 mHandler.sendMessageDelayed(msg, TIMEOUT_BIND_MS);
1075 }
1076 }
1077
fredcbf072a72012-05-09 16:52:50 -07001078 private void sendBluetoothStateCallback(boolean isUp) {
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001079 try {
1080 int n = mStateChangeCallbacks.beginBroadcast();
Jeff Sharkey67609c72016-03-05 14:29:13 -07001081 if (DBG) Slog.d(TAG,"Broadcasting onBluetoothStateChange("+isUp+") to " + n + " receivers.");
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001082 for (int i=0; i <n;i++) {
1083 try {
1084 mStateChangeCallbacks.getBroadcastItem(i).onBluetoothStateChange(isUp);
1085 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001086 Slog.e(TAG, "Unable to call onBluetoothStateChange() on callback #" + i , e);
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001087 }
fredcbf072a72012-05-09 16:52:50 -07001088 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001089 } finally {
1090 mStateChangeCallbacks.finishBroadcast();
fredcbf072a72012-05-09 16:52:50 -07001091 }
fredcbf072a72012-05-09 16:52:50 -07001092 }
1093
1094 /**
Zhihai Xu40874a02012-10-08 17:57:03 -07001095 * Inform BluetoothAdapter instances that Adapter service is up
1096 */
1097 private void sendBluetoothServiceUpCallback() {
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001098 try {
1099 int n = mCallbacks.beginBroadcast();
Jeff Sharkey67609c72016-03-05 14:29:13 -07001100 Slog.d(TAG,"Broadcasting onBluetoothServiceUp() to " + n + " receivers.");
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001101 for (int i=0; i <n;i++) {
1102 try {
1103 mCallbacks.getBroadcastItem(i).onBluetoothServiceUp(mBluetooth);
1104 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001105 Slog.e(TAG, "Unable to call onBluetoothServiceUp() on callback #" + i, e);
Zhihai Xu40874a02012-10-08 17:57:03 -07001106 }
1107 }
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001108 } finally {
1109 mCallbacks.finishBroadcast();
Zhihai Xu40874a02012-10-08 17:57:03 -07001110 }
1111 }
1112 /**
fredcbf072a72012-05-09 16:52:50 -07001113 * Inform BluetoothAdapter instances that Adapter service is down
1114 */
1115 private void sendBluetoothServiceDownCallback() {
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001116 try {
1117 int n = mCallbacks.beginBroadcast();
Jeff Sharkey67609c72016-03-05 14:29:13 -07001118 Slog.d(TAG,"Broadcasting onBluetoothServiceDown() to " + n + " receivers.");
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001119 for (int i=0; i <n;i++) {
1120 try {
1121 mCallbacks.getBroadcastItem(i).onBluetoothServiceDown();
1122 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001123 Slog.e(TAG, "Unable to call onBluetoothServiceDown() on callback #" + i, e);
fredcd6883532012-04-25 17:46:13 -07001124 }
1125 }
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001126 } finally {
1127 mCallbacks.finishBroadcast();
fredcd6883532012-04-25 17:46:13 -07001128 }
1129 }
Svet Ganov408abf72015-05-12 19:13:36 -07001130
fredc0f420372012-04-12 00:02:00 -07001131 public String getAddress() {
Matthew Xieaf5ddbf2012-12-04 10:47:43 -08001132 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
Svet Ganov408abf72015-05-12 19:13:36 -07001133 "Need BLUETOOTH permission");
Zhihai Xu40874a02012-10-08 17:57:03 -07001134
Zhihai Xu6eb76522012-11-29 15:41:04 -08001135 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
Svet Ganov408abf72015-05-12 19:13:36 -07001136 (!checkIfCallerIsForegroundUser())) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001137 Slog.w(TAG,"getAddress(): not allowed for non-active and non system user");
Zhihai Xu6eb76522012-11-29 15:41:04 -08001138 return null;
Zhihai Xu40874a02012-10-08 17:57:03 -07001139 }
1140
Svet Ganov408abf72015-05-12 19:13:36 -07001141 if (mContext.checkCallingOrSelfPermission(Manifest.permission.LOCAL_MAC_ADDRESS)
1142 != PackageManager.PERMISSION_GRANTED) {
1143 return BluetoothAdapter.DEFAULT_MAC_ADDRESS;
1144 }
1145
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001146 try {
1147 mBluetoothLock.readLock().lock();
1148 if (mBluetooth != null) return mBluetooth.getAddress();
1149 } catch (RemoteException e) {
1150 Slog.e(TAG, "getAddress(): Unable to retrieve address remotely. Returning cached address", e);
1151 } finally {
1152 mBluetoothLock.readLock().unlock();
fredc116d1d462012-04-20 14:47:08 -07001153 }
Ajay Panickerbf796d82016-03-11 13:47:20 -08001154
Matthew Xiecdce0b92012-07-12 19:06:15 -07001155 // mAddress is accessed from outside.
1156 // It is alright without a lock. Here, bluetooth is off, no other thread is
1157 // changing mAddress
fredc0f420372012-04-12 00:02:00 -07001158 return mAddress;
1159 }
fredc649fe492012-04-19 01:07:18 -07001160
fredc0f420372012-04-12 00:02:00 -07001161 public String getName() {
Matthew Xieaf5ddbf2012-12-04 10:47:43 -08001162 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
1163 "Need BLUETOOTH permission");
Zhihai Xu40874a02012-10-08 17:57:03 -07001164
Zhihai Xu6eb76522012-11-29 15:41:04 -08001165 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
1166 (!checkIfCallerIsForegroundUser())) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001167 Slog.w(TAG,"getName(): not allowed for non-active and non system user");
Zhihai Xu6eb76522012-11-29 15:41:04 -08001168 return null;
Zhihai Xu40874a02012-10-08 17:57:03 -07001169 }
1170
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001171 try {
1172 mBluetoothLock.readLock().lock();
1173 if (mBluetooth != null) return mBluetooth.getName();
1174 } catch (RemoteException e) {
1175 Slog.e(TAG, "getName(): Unable to retrieve name remotely. Returning cached name", e);
1176 } finally {
1177 mBluetoothLock.readLock().unlock();
fredc116d1d462012-04-20 14:47:08 -07001178 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001179
Matthew Xiecdce0b92012-07-12 19:06:15 -07001180 // mName is accessed from outside.
1181 // It alright without a lock. Here, bluetooth is off, no other thread is
1182 // changing mName
fredc0f420372012-04-12 00:02:00 -07001183 return mName;
1184 }
1185
fredc0f420372012-04-12 00:02:00 -07001186 private class BluetoothServiceConnection implements ServiceConnection {
Marie Janssencb21ad72016-12-13 10:51:02 -08001187 public void onServiceConnected(ComponentName componentName, IBinder service) {
1188 String name = componentName.getClassName();
1189 if (DBG) Slog.d(TAG, "BluetoothServiceConnection: " + name);
fredc0f420372012-04-12 00:02:00 -07001190 Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_SERVICE_CONNECTED);
Marie Janssencb21ad72016-12-13 10:51:02 -08001191 if (name.equals("com.android.bluetooth.btservice.AdapterService")) {
Matthew Xieddf7e472013-03-01 18:41:02 -08001192 msg.arg1 = SERVICE_IBLUETOOTH;
Marie Janssencb21ad72016-12-13 10:51:02 -08001193 } else if (name.equals("com.android.bluetooth.gatt.GattService")) {
Matthew Xieddf7e472013-03-01 18:41:02 -08001194 msg.arg1 = SERVICE_IBLUETOOTHGATT;
1195 } else {
Marie Janssencb21ad72016-12-13 10:51:02 -08001196 Slog.e(TAG, "Unknown service connected: " + name);
Matthew Xieddf7e472013-03-01 18:41:02 -08001197 return;
1198 }
fredc0f420372012-04-12 00:02:00 -07001199 msg.obj = service;
1200 mHandler.sendMessage(msg);
1201 }
1202
Marie Janssencb21ad72016-12-13 10:51:02 -08001203 public void onServiceDisconnected(ComponentName componentName) {
1204 // Called if we unexpectedly disconnect.
1205 String name = componentName.getClassName();
1206 if (DBG) Slog.d(TAG, "BluetoothServiceConnection, disconnected: " + name);
fredc0f420372012-04-12 00:02:00 -07001207 Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED);
Marie Janssencb21ad72016-12-13 10:51:02 -08001208 if (name.equals("com.android.bluetooth.btservice.AdapterService")) {
Matthew Xieddf7e472013-03-01 18:41:02 -08001209 msg.arg1 = SERVICE_IBLUETOOTH;
Marie Janssencb21ad72016-12-13 10:51:02 -08001210 } else if (name.equals("com.android.bluetooth.gatt.GattService")) {
Matthew Xieddf7e472013-03-01 18:41:02 -08001211 msg.arg1 = SERVICE_IBLUETOOTHGATT;
1212 } else {
Marie Janssencb21ad72016-12-13 10:51:02 -08001213 Slog.e(TAG, "Unknown service disconnected: " + name);
Matthew Xieddf7e472013-03-01 18:41:02 -08001214 return;
1215 }
fredc0f420372012-04-12 00:02:00 -07001216 mHandler.sendMessage(msg);
1217 }
1218 }
1219
1220 private BluetoothServiceConnection mConnection = new BluetoothServiceConnection();
1221
Zhihai Xu40874a02012-10-08 17:57:03 -07001222 private class BluetoothHandler extends Handler {
Ajay Panicker4bb48302016-03-31 14:14:27 -07001223 boolean mGetNameAddressOnly = false;
1224
Zhihai Xu40874a02012-10-08 17:57:03 -07001225 public BluetoothHandler(Looper looper) {
1226 super(looper);
1227 }
1228
fredc0f420372012-04-12 00:02:00 -07001229 @Override
1230 public void handleMessage(Message msg) {
fredc0f420372012-04-12 00:02:00 -07001231 switch (msg.what) {
Ajay Panicker4bb48302016-03-31 14:14:27 -07001232 case MESSAGE_GET_NAME_AND_ADDRESS:
1233 if (DBG) Slog.d(TAG, "MESSAGE_GET_NAME_AND_ADDRESS");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001234 try {
1235 mBluetoothLock.writeLock().lock();
Ajay Panicker4bb48302016-03-31 14:14:27 -07001236 if ((mBluetooth == null) && (!mBinding)) {
1237 if (DBG) Slog.d(TAG, "Binding to service to get name and address");
1238 mGetNameAddressOnly = true;
1239 Message timeoutMsg = mHandler.obtainMessage(MESSAGE_TIMEOUT_BIND);
1240 mHandler.sendMessageDelayed(timeoutMsg, TIMEOUT_BIND_MS);
1241 Intent i = new Intent(IBluetooth.class.getName());
1242 if (!doBind(i, mConnection,
1243 Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT,
1244 UserHandle.CURRENT)) {
1245 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
1246 } else {
1247 mBinding = true;
1248 }
1249 } else if (mBluetooth != null) {
1250 try {
1251 storeNameAndAddress(mBluetooth.getName(),
1252 mBluetooth.getAddress());
1253 } catch (RemoteException re) {
1254 Slog.e(TAG, "Unable to grab names", re);
1255 }
1256 if (mGetNameAddressOnly && !mEnable) {
1257 unbindAndFinish();
1258 }
1259 mGetNameAddressOnly = false;
1260 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001261 } finally {
1262 mBluetoothLock.writeLock().unlock();
Ajay Panicker4bb48302016-03-31 14:14:27 -07001263 }
1264 break;
1265
Matthew Xiecdce0b92012-07-12 19:06:15 -07001266 case MESSAGE_ENABLE:
fredcf2458862012-04-16 15:18:27 -07001267 if (DBG) {
Marie Janssencb21ad72016-12-13 10:51:02 -08001268 Slog.d(TAG, "MESSAGE_ENABLE(" + msg.arg1 + "): mBluetooth = " + mBluetooth);
fredc649fe492012-04-19 01:07:18 -07001269 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001270 mHandler.removeMessages(MESSAGE_RESTART_BLUETOOTH_SERVICE);
1271 mEnable = true;
Calvin Ona0b91d72016-06-15 17:58:23 -07001272
1273 // Use service interface to get the exact state
1274 try {
1275 mBluetoothLock.readLock().lock();
1276 if (mBluetooth != null) {
1277 int state = mBluetooth.getState();
1278 if (state == BluetoothAdapter.STATE_BLE_ON) {
Marie Janssene0bfa2e2016-12-20 11:21:12 -08001279 Slog.w(TAG, "BT Enable in BLE_ON State, going to ON");
Calvin Ona0b91d72016-06-15 17:58:23 -07001280 mBluetooth.onLeServiceUp();
Marie Janssene0bfa2e2016-12-20 11:21:12 -08001281 persistBluetoothSetting(BLUETOOTH_ON_BLUETOOTH);
Calvin Ona0b91d72016-06-15 17:58:23 -07001282 break;
1283 }
1284 }
1285 } catch (RemoteException e) {
1286 Slog.e(TAG, "", e);
1287 } finally {
1288 mBluetoothLock.readLock().unlock();
1289 }
1290
1291 mQuietEnable = (msg.arg1 == 1);
Pavlin Radoslavove47ec142016-06-01 22:25:18 -07001292 if (mBluetooth == null) {
Calvin Ona0b91d72016-06-15 17:58:23 -07001293 handleEnable(mQuietEnable);
Pavlin Radoslavove47ec142016-06-01 22:25:18 -07001294 } else {
1295 //
1296 // We need to wait until transitioned to STATE_OFF and
1297 // the previous Bluetooth process has exited. The
1298 // waiting period has three components:
1299 // (a) Wait until the local state is STATE_OFF. This
1300 // is accomplished by "waitForOnOff(false, true)".
1301 // (b) Wait until the STATE_OFF state is updated to
1302 // all components.
1303 // (c) Wait until the Bluetooth process exits, and
1304 // ActivityManager detects it.
1305 // The waiting for (b) and (c) is accomplished by
1306 // delaying the MESSAGE_RESTART_BLUETOOTH_SERVICE
1307 // message. On slower devices, that delay needs to be
1308 // on the order of (2 * SERVICE_RESTART_TIME_MS).
1309 //
1310 waitForOnOff(false, true);
Pavlin Radoslavove47ec142016-06-01 22:25:18 -07001311 Message restartMsg = mHandler.obtainMessage(
1312 MESSAGE_RESTART_BLUETOOTH_SERVICE);
1313 mHandler.sendMessageDelayed(restartMsg,
1314 2 * SERVICE_RESTART_TIME_MS);
1315 }
fredc649fe492012-04-19 01:07:18 -07001316 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001317
fredc0f420372012-04-12 00:02:00 -07001318 case MESSAGE_DISABLE:
Marie Janssencb21ad72016-12-13 10:51:02 -08001319 if (DBG) Slog.d(TAG, "MESSAGE_DISABLE: mBluetooth = " + mBluetooth);
Zhihai Xu40874a02012-10-08 17:57:03 -07001320 mHandler.removeMessages(MESSAGE_RESTART_BLUETOOTH_SERVICE);
1321 if (mEnable && mBluetooth != null) {
1322 waitForOnOff(true, false);
1323 mEnable = false;
Zhihai Xu401202b2012-12-03 11:36:21 -08001324 handleDisable();
Zhihai Xu40874a02012-10-08 17:57:03 -07001325 waitForOnOff(false, false);
1326 } else {
1327 mEnable = false;
Zhihai Xu401202b2012-12-03 11:36:21 -08001328 handleDisable();
Zhihai Xu40874a02012-10-08 17:57:03 -07001329 }
fredc0f420372012-04-12 00:02:00 -07001330 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001331
fredc0f420372012-04-12 00:02:00 -07001332 case MESSAGE_REGISTER_ADAPTER:
1333 {
1334 IBluetoothManagerCallback callback = (IBluetoothManagerCallback) msg.obj;
Marie Janssencb21ad72016-12-13 10:51:02 -08001335 mCallbacks.register(callback);
fredc0f420372012-04-12 00:02:00 -07001336 break;
Marie Janssencb21ad72016-12-13 10:51:02 -08001337 }
fredc0f420372012-04-12 00:02:00 -07001338 case MESSAGE_UNREGISTER_ADAPTER:
1339 {
1340 IBluetoothManagerCallback callback = (IBluetoothManagerCallback) msg.obj;
Marie Janssencb21ad72016-12-13 10:51:02 -08001341 mCallbacks.unregister(callback);
fredc0f420372012-04-12 00:02:00 -07001342 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001343 }
fredc0f420372012-04-12 00:02:00 -07001344 case MESSAGE_REGISTER_STATE_CHANGE_CALLBACK:
1345 {
1346 IBluetoothStateChangeCallback callback = (IBluetoothStateChangeCallback) msg.obj;
Marie Janssencb21ad72016-12-13 10:51:02 -08001347 mStateChangeCallbacks.register(callback);
fredc0f420372012-04-12 00:02:00 -07001348 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001349 }
fredc0f420372012-04-12 00:02:00 -07001350 case MESSAGE_UNREGISTER_STATE_CHANGE_CALLBACK:
1351 {
1352 IBluetoothStateChangeCallback callback = (IBluetoothStateChangeCallback) msg.obj;
Marie Janssencb21ad72016-12-13 10:51:02 -08001353 mStateChangeCallbacks.unregister(callback);
fredc0f420372012-04-12 00:02:00 -07001354 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001355 }
Benjamin Franze8b98922014-11-12 15:57:54 +00001356 case MESSAGE_ADD_PROXY_DELAYED:
1357 {
1358 ProfileServiceConnections psc = mProfileServices.get(
1359 new Integer(msg.arg1));
1360 if (psc == null) {
1361 break;
1362 }
1363 IBluetoothProfileServiceConnection proxy =
1364 (IBluetoothProfileServiceConnection) msg.obj;
1365 psc.addProxy(proxy);
1366 break;
1367 }
1368 case MESSAGE_BIND_PROFILE_SERVICE:
1369 {
1370 ProfileServiceConnections psc = (ProfileServiceConnections) msg.obj;
1371 removeMessages(MESSAGE_BIND_PROFILE_SERVICE, msg.obj);
1372 if (psc == null) {
1373 break;
1374 }
1375 psc.bindService();
1376 break;
1377 }
fredc0f420372012-04-12 00:02:00 -07001378 case MESSAGE_BLUETOOTH_SERVICE_CONNECTED:
1379 {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001380 if (DBG) Slog.d(TAG,"MESSAGE_BLUETOOTH_SERVICE_CONNECTED: " + msg.arg1);
fredc0f420372012-04-12 00:02:00 -07001381
1382 IBinder service = (IBinder) msg.obj;
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001383 try {
1384 mBluetoothLock.writeLock().lock();
Matthew Xieddf7e472013-03-01 18:41:02 -08001385 if (msg.arg1 == SERVICE_IBLUETOOTHGATT) {
1386 mBluetoothGatt = IBluetoothGatt.Stub.asInterface(service);
Nitin Arorad055adb2015-03-02 15:03:51 -08001387 onBluetoothGattServiceUp();
Matthew Xieddf7e472013-03-01 18:41:02 -08001388 break;
1389 } // else must be SERVICE_IBLUETOOTH
1390
1391 //Remove timeout
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001392 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
Matthew Xieddf7e472013-03-01 18:41:02 -08001393
fredc0f420372012-04-12 00:02:00 -07001394 mBinding = false;
Marie Janssen9db28eb2016-01-12 16:05:15 -08001395 mBluetoothBinder = service;
fredc0f420372012-04-12 00:02:00 -07001396 mBluetooth = IBluetooth.Stub.asInterface(service);
fredc0f420372012-04-12 00:02:00 -07001397
Ajay Panicker4bb48302016-03-31 14:14:27 -07001398 if (!isNameAndAddressSet()) {
1399 Message getMsg = mHandler.obtainMessage(MESSAGE_GET_NAME_AND_ADDRESS);
1400 mHandler.sendMessage(getMsg);
1401 if (mGetNameAddressOnly) return;
1402 }
1403
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001404 try {
1405 boolean enableHciSnoopLog = (Settings.Secure.getInt(mContentResolver,
1406 Settings.Secure.BLUETOOTH_HCI_LOG, 0) == 1);
1407 if (!mBluetooth.configHciSnoopLog(enableHciSnoopLog)) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001408 Slog.e(TAG,"IBluetooth.configHciSnoopLog return false");
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001409 }
1410 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001411 Slog.e(TAG,"Unable to call configHciSnoopLog", e);
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001412 }
1413
Matthew Xiecdce0b92012-07-12 19:06:15 -07001414 //Register callback object
fredcbf072a72012-05-09 16:52:50 -07001415 try {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001416 mBluetooth.registerCallback(mBluetoothCallback);
1417 } catch (RemoteException re) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001418 Slog.e(TAG, "Unable to register BluetoothCallback",re);
fredcbf072a72012-05-09 16:52:50 -07001419 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001420 //Inform BluetoothAdapter instances that service is up
Zhihai Xu40874a02012-10-08 17:57:03 -07001421 sendBluetoothServiceUpCallback();
1422
Matthew Xiecdce0b92012-07-12 19:06:15 -07001423 //Do enable request
1424 try {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001425 if (mQuietEnable == false) {
Marie Janssencb21ad72016-12-13 10:51:02 -08001426 if (!mBluetooth.enable()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001427 Slog.e(TAG,"IBluetooth.enable() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001428 }
Marie Janssencb21ad72016-12-13 10:51:02 -08001429 } else {
1430 if (!mBluetooth.enableNoAutoConnect()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001431 Slog.e(TAG,"IBluetooth.enableNoAutoConnect() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001432 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001433 }
1434 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001435 Slog.e(TAG,"Unable to call enable()",e);
Matthew Xiecdce0b92012-07-12 19:06:15 -07001436 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001437 } finally {
1438 mBluetoothLock.writeLock().unlock();
Freda8c6df02012-07-11 10:25:23 -07001439 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001440
1441 if (!mEnable) {
1442 waitForOnOff(true, false);
Zhihai Xu401202b2012-12-03 11:36:21 -08001443 handleDisable();
Zhihai Xu40874a02012-10-08 17:57:03 -07001444 waitForOnOff(false, false);
1445 }
fredc649fe492012-04-19 01:07:18 -07001446 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001447 }
fredcbf072a72012-05-09 16:52:50 -07001448 case MESSAGE_BLUETOOTH_STATE_CHANGE:
fredc0f420372012-04-12 00:02:00 -07001449 {
fredcbf072a72012-05-09 16:52:50 -07001450 int prevState = msg.arg1;
1451 int newState = msg.arg2;
Marie Janssencb21ad72016-12-13 10:51:02 -08001452 if (DBG) {
1453 Slog.d(TAG, "MESSAGE_BLUETOOTH_STATE_CHANGE: " + BluetoothAdapter.nameForState(prevState) + " > " +
1454 BluetoothAdapter.nameForState(newState));
1455 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001456 mState = newState;
1457 bluetoothStateChangeHandler(prevState, newState);
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001458 // handle error state transition case from TURNING_ON to OFF
1459 // unbind and rebind bluetooth service and enable bluetooth
Nitin Arorad055adb2015-03-02 15:03:51 -08001460 if ((prevState == BluetoothAdapter.STATE_BLE_TURNING_ON) &&
Calvin Ona0b91d72016-06-15 17:58:23 -07001461 (newState == BluetoothAdapter.STATE_OFF) &&
1462 (mBluetooth != null) && mEnable) {
Marie Janssen2977c3e2016-11-09 12:01:24 -08001463 recoverBluetoothServiceFromError(false);
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001464 }
Nitin Arorad055adb2015-03-02 15:03:51 -08001465 if ((prevState == BluetoothAdapter.STATE_TURNING_ON) &&
Calvin Ona0b91d72016-06-15 17:58:23 -07001466 (newState == BluetoothAdapter.STATE_BLE_ON) &&
1467 (mBluetooth != null) && mEnable) {
Marie Janssen2977c3e2016-11-09 12:01:24 -08001468 recoverBluetoothServiceFromError(true);
Nitin Arorad055adb2015-03-02 15:03:51 -08001469 }
Calvin Ona0b91d72016-06-15 17:58:23 -07001470 // If we tried to enable BT while BT was in the process of shutting down,
1471 // wait for the BT process to fully tear down and then force a restart
1472 // here. This is a bit of a hack (b/29363429).
1473 if ((prevState == BluetoothAdapter.STATE_BLE_TURNING_OFF) &&
1474 (newState == BluetoothAdapter.STATE_OFF)) {
1475 if (mEnable) {
1476 Slog.d(TAG, "Entering STATE_OFF but mEnabled is true; restarting.");
1477 waitForOnOff(false, true);
1478 Message restartMsg = mHandler.obtainMessage(
1479 MESSAGE_RESTART_BLUETOOTH_SERVICE);
1480 mHandler.sendMessageDelayed(restartMsg, 2 * SERVICE_RESTART_TIME_MS);
1481 }
1482 }
Nitin Arorad055adb2015-03-02 15:03:51 -08001483 if (newState == BluetoothAdapter.STATE_ON ||
Calvin Ona0b91d72016-06-15 17:58:23 -07001484 newState == BluetoothAdapter.STATE_BLE_ON) {
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001485 // bluetooth is working, reset the counter
1486 if (mErrorRecoveryRetryCounter != 0) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001487 Slog.w(TAG, "bluetooth is recovered from error");
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001488 mErrorRecoveryRetryCounter = 0;
1489 }
1490 }
fredc649fe492012-04-19 01:07:18 -07001491 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001492 }
fredc0f420372012-04-12 00:02:00 -07001493 case MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED:
1494 {
Marie Janssencb21ad72016-12-13 10:51:02 -08001495 Slog.e(TAG, "MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED(" + msg.arg1 + ")");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001496 try {
1497 mBluetoothLock.writeLock().lock();
Matthew Xieddf7e472013-03-01 18:41:02 -08001498 if (msg.arg1 == SERVICE_IBLUETOOTH) {
1499 // if service is unbinded already, do nothing and return
1500 if (mBluetooth == null) break;
1501 mBluetooth = null;
1502 } else if (msg.arg1 == SERVICE_IBLUETOOTHGATT) {
1503 mBluetoothGatt = null;
1504 break;
1505 } else {
Marie Janssencb21ad72016-12-13 10:51:02 -08001506 Slog.e(TAG, "Unknown argument for service disconnect!");
Matthew Xieddf7e472013-03-01 18:41:02 -08001507 break;
1508 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001509 } finally {
1510 mBluetoothLock.writeLock().unlock();
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301511 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001512
1513 if (mEnable) {
1514 mEnable = false;
1515 // Send a Bluetooth Restart message
1516 Message restartMsg = mHandler.obtainMessage(
1517 MESSAGE_RESTART_BLUETOOTH_SERVICE);
1518 mHandler.sendMessageDelayed(restartMsg,
1519 SERVICE_RESTART_TIME_MS);
1520 }
1521
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001522 sendBluetoothServiceDownCallback();
Zhihai Xu40874a02012-10-08 17:57:03 -07001523
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001524 // Send BT state broadcast to update
1525 // the BT icon correctly
1526 if ((mState == BluetoothAdapter.STATE_TURNING_ON) ||
Calvin Ona0b91d72016-06-15 17:58:23 -07001527 (mState == BluetoothAdapter.STATE_ON)) {
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001528 bluetoothStateChangeHandler(BluetoothAdapter.STATE_ON,
1529 BluetoothAdapter.STATE_TURNING_OFF);
1530 mState = BluetoothAdapter.STATE_TURNING_OFF;
Zhihai Xu40874a02012-10-08 17:57:03 -07001531 }
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001532 if (mState == BluetoothAdapter.STATE_TURNING_OFF) {
1533 bluetoothStateChangeHandler(BluetoothAdapter.STATE_TURNING_OFF,
1534 BluetoothAdapter.STATE_OFF);
1535 }
1536
1537 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
1538 mState = BluetoothAdapter.STATE_OFF;
fredc649fe492012-04-19 01:07:18 -07001539 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001540 }
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301541 case MESSAGE_RESTART_BLUETOOTH_SERVICE:
1542 {
Marie Janssencb21ad72016-12-13 10:51:02 -08001543 Slog.d(TAG, "MESSAGE_RESTART_BLUETOOTH_SERVICE");
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301544 /* Enable without persisting the setting as
1545 it doesnt change when IBluetooth
1546 service restarts */
Zhihai Xu40874a02012-10-08 17:57:03 -07001547 mEnable = true;
Zhihai Xu401202b2012-12-03 11:36:21 -08001548 handleEnable(mQuietEnable);
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301549 break;
1550 }
Marie Janssencb21ad72016-12-13 10:51:02 -08001551 case MESSAGE_TIMEOUT_BIND: {
1552 Slog.e(TAG, "MESSAGE_TIMEOUT_BIND");
1553 mBluetoothLock.writeLock().lock();
1554 mBinding = false;
1555 mBluetoothLock.writeLock().unlock();
1556 break;
1557 }
fredc0f420372012-04-12 00:02:00 -07001558 case MESSAGE_TIMEOUT_UNBIND:
1559 {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001560 Slog.e(TAG, "MESSAGE_TIMEOUT_UNBIND");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001561 mBluetoothLock.writeLock().lock();
1562 mUnbinding = false;
1563 mBluetoothLock.writeLock().unlock();
fredc649fe492012-04-19 01:07:18 -07001564 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001565 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001566
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001567 case MESSAGE_USER_SWITCHED: {
1568 if (DBG) Slog.d(TAG, "MESSAGE_USER_SWITCHED");
Zhihai Xu40874a02012-10-08 17:57:03 -07001569 mHandler.removeMessages(MESSAGE_USER_SWITCHED);
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001570
Zhihai Xu40874a02012-10-08 17:57:03 -07001571 /* disable and enable BT when detect a user switch */
1572 if (mEnable && mBluetooth != null) {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001573 try {
1574 mBluetoothLock.readLock().lock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001575 if (mBluetooth != null) {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001576 mBluetooth.unregisterCallback(mBluetoothCallback);
Zhihai Xu40874a02012-10-08 17:57:03 -07001577 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001578 } catch (RemoteException re) {
1579 Slog.e(TAG, "Unable to unregister", re);
1580 } finally {
1581 mBluetoothLock.readLock().unlock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001582 }
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001583
1584 if (mState == BluetoothAdapter.STATE_TURNING_OFF) {
1585 // MESSAGE_USER_SWITCHED happened right after MESSAGE_ENABLE
1586 bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_OFF);
1587 mState = BluetoothAdapter.STATE_OFF;
1588 }
1589 if (mState == BluetoothAdapter.STATE_OFF) {
1590 bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_TURNING_ON);
1591 mState = BluetoothAdapter.STATE_TURNING_ON;
1592 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001593
1594 waitForOnOff(true, false);
1595
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001596 if (mState == BluetoothAdapter.STATE_TURNING_ON) {
1597 bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_ON);
1598 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001599
Benjamin Franze8b98922014-11-12 15:57:54 +00001600 unbindAllBluetoothProfileServices();
Zhihai Xu40874a02012-10-08 17:57:03 -07001601 // disable
Zhihai Xu401202b2012-12-03 11:36:21 -08001602 handleDisable();
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001603 // Pbap service need receive STATE_TURNING_OFF intent to close
1604 bluetoothStateChangeHandler(BluetoothAdapter.STATE_ON,
1605 BluetoothAdapter.STATE_TURNING_OFF);
Zhihai Xu40874a02012-10-08 17:57:03 -07001606
Pavlin Radoslavov41401112016-06-27 15:25:18 -07001607 boolean didDisableTimeout = !waitForOnOff(false, true);
Zhihai Xu40874a02012-10-08 17:57:03 -07001608
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001609 bluetoothStateChangeHandler(BluetoothAdapter.STATE_TURNING_OFF,
Zhihai Xu40874a02012-10-08 17:57:03 -07001610 BluetoothAdapter.STATE_OFF);
Zhihai Xu40874a02012-10-08 17:57:03 -07001611 sendBluetoothServiceDownCallback();
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001612
Pavlin Radoslavove957a8a2016-05-24 15:28:41 -07001613 try {
1614 mBluetoothLock.writeLock().lock();
1615 if (mBluetooth != null) {
1616 mBluetooth = null;
1617 // Unbind
1618 mContext.unbindService(mConnection);
1619 }
1620 mBluetoothGatt = null;
1621 } finally {
1622 mBluetoothLock.writeLock().unlock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001623 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001624
Pavlin Radoslavov41401112016-06-27 15:25:18 -07001625 //
1626 // If disabling Bluetooth times out, wait for an
1627 // additional amount of time to ensure the process is
1628 // shut down completely before attempting to restart.
1629 //
1630 if (didDisableTimeout) {
1631 SystemClock.sleep(3000);
1632 } else {
1633 SystemClock.sleep(100);
1634 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001635
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001636 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
1637 mState = BluetoothAdapter.STATE_OFF;
Zhihai Xu40874a02012-10-08 17:57:03 -07001638 // enable
Zhihai Xu401202b2012-12-03 11:36:21 -08001639 handleEnable(mQuietEnable);
John Spurlock8a985d22014-02-25 09:40:05 -05001640 } else if (mBinding || mBluetooth != null) {
Zhihai Xu40874a02012-10-08 17:57:03 -07001641 Message userMsg = mHandler.obtainMessage(MESSAGE_USER_SWITCHED);
1642 userMsg.arg2 = 1 + msg.arg2;
Marie Janssencb21ad72016-12-13 10:51:02 -08001643 // if user is switched when service is binding retry after a delay
Zhihai Xu40874a02012-10-08 17:57:03 -07001644 mHandler.sendMessageDelayed(userMsg, USER_SWITCHED_TIME_MS);
1645 if (DBG) {
Marie Janssencb21ad72016-12-13 10:51:02 -08001646 Slog.d(TAG, "Retry MESSAGE_USER_SWITCHED " + userMsg.arg2);
Zhihai Xu40874a02012-10-08 17:57:03 -07001647 }
John Spurlock8a985d22014-02-25 09:40:05 -05001648 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001649 break;
1650 }
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001651 case MESSAGE_USER_UNLOCKED: {
1652 if (DBG) Slog.d(TAG, "MESSAGE_USER_UNLOCKED");
1653 mHandler.removeMessages(MESSAGE_USER_SWITCHED);
1654
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001655 if (mEnable && !mBinding && (mBluetooth == null)) {
1656 // We should be connected, but we gave up for some
1657 // reason; maybe the Bluetooth service wasn't encryption
1658 // aware, so try binding again.
1659 if (DBG) Slog.d(TAG, "Enabled but not bound; retrying after unlock");
1660 handleEnable(mQuietEnable);
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001661 }
1662 }
fredc0f420372012-04-12 00:02:00 -07001663 }
1664 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001665 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001666
Zhihai Xu401202b2012-12-03 11:36:21 -08001667 private void handleEnable(boolean quietMode) {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001668 mQuietEnable = quietMode;
1669
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001670 try {
1671 mBluetoothLock.writeLock().lock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001672 if ((mBluetooth == null) && (!mBinding)) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001673 //Start bind timeout and bind
1674 Message timeoutMsg=mHandler.obtainMessage(MESSAGE_TIMEOUT_BIND);
1675 mHandler.sendMessageDelayed(timeoutMsg,TIMEOUT_BIND_MS);
Matthew Xiecdce0b92012-07-12 19:06:15 -07001676 Intent i = new Intent(IBluetooth.class.getName());
Dianne Hackbornce09f5a2014-10-10 15:03:13 -07001677 if (!doBind(i, mConnection,Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT,
1678 UserHandle.CURRENT)) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001679 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
Zhihai Xu40874a02012-10-08 17:57:03 -07001680 } else {
1681 mBinding = true;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001682 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001683 } else if (mBluetooth != null) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001684 //Enable bluetooth
1685 try {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001686 if (!mQuietEnable) {
1687 if(!mBluetooth.enable()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001688 Slog.e(TAG,"IBluetooth.enable() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001689 }
1690 }
1691 else {
1692 if(!mBluetooth.enableNoAutoConnect()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001693 Slog.e(TAG,"IBluetooth.enableNoAutoConnect() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001694 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001695 }
1696 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001697 Slog.e(TAG,"Unable to call enable()",e);
Matthew Xiecdce0b92012-07-12 19:06:15 -07001698 }
1699 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001700 } finally {
1701 mBluetoothLock.writeLock().unlock();
Matthew Xiecdce0b92012-07-12 19:06:15 -07001702 }
1703 }
1704
Dianne Hackborn221ea892013-08-04 16:50:16 -07001705 boolean doBind(Intent intent, ServiceConnection conn, int flags, UserHandle user) {
1706 ComponentName comp = intent.resolveSystemService(mContext.getPackageManager(), 0);
1707 intent.setComponent(comp);
1708 if (comp == null || !mContext.bindServiceAsUser(intent, conn, flags, user)) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001709 Slog.e(TAG, "Fail to bind to: " + intent);
Dianne Hackborn221ea892013-08-04 16:50:16 -07001710 return false;
1711 }
1712 return true;
1713 }
1714
Zhihai Xu401202b2012-12-03 11:36:21 -08001715 private void handleDisable() {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001716 try {
1717 mBluetoothLock.readLock().lock();
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001718 if (mBluetooth != null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001719 if (DBG) Slog.d(TAG,"Sending off request.");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001720 if (!mBluetooth.disable()) {
1721 Slog.e(TAG,"IBluetooth.disable() returned false");
Matthew Xiecdce0b92012-07-12 19:06:15 -07001722 }
1723 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001724 } catch (RemoteException e) {
1725 Slog.e(TAG,"Unable to call disable()",e);
1726 } finally {
1727 mBluetoothLock.readLock().unlock();
Matthew Xiecdce0b92012-07-12 19:06:15 -07001728 }
1729 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001730
1731 private boolean checkIfCallerIsForegroundUser() {
1732 int foregroundUser;
1733 int callingUser = UserHandle.getCallingUserId();
Martijn Coenen8385c5a2012-11-29 10:14:16 -08001734 int callingUid = Binder.getCallingUid();
Zhihai Xu40874a02012-10-08 17:57:03 -07001735 long callingIdentity = Binder.clearCallingIdentity();
Benjamin Franze8b98922014-11-12 15:57:54 +00001736 UserManager um = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
1737 UserInfo ui = um.getProfileParent(callingUser);
1738 int parentUser = (ui != null) ? ui.id : UserHandle.USER_NULL;
Martijn Coenen8385c5a2012-11-29 10:14:16 -08001739 int callingAppId = UserHandle.getAppId(callingUid);
Zhihai Xu40874a02012-10-08 17:57:03 -07001740 boolean valid = false;
1741 try {
1742 foregroundUser = ActivityManager.getCurrentUser();
Martijn Coenen8385c5a2012-11-29 10:14:16 -08001743 valid = (callingUser == foregroundUser) ||
Benjamin Franze8b98922014-11-12 15:57:54 +00001744 parentUser == foregroundUser ||
Adrian Roosbd9a9a52014-08-18 15:31:57 +02001745 callingAppId == Process.NFC_UID ||
1746 callingAppId == mSystemUiUid;
Marie Janssencb21ad72016-12-13 10:51:02 -08001747 if (DBG && !valid) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001748 Slog.d(TAG, "checkIfCallerIsForegroundUser: valid=" + valid
Zhihai Xu40874a02012-10-08 17:57:03 -07001749 + " callingUser=" + callingUser
Benjamin Franze8b98922014-11-12 15:57:54 +00001750 + " parentUser=" + parentUser
Zhihai Xu40874a02012-10-08 17:57:03 -07001751 + " foregroundUser=" + foregroundUser);
1752 }
1753 } finally {
1754 Binder.restoreCallingIdentity(callingIdentity);
1755 }
1756 return valid;
1757 }
1758
Nitin Arorad055adb2015-03-02 15:03:51 -08001759 private void sendBleStateChanged(int prevState, int newState) {
Marie Janssencb21ad72016-12-13 10:51:02 -08001760 if (DBG) Slog.d(TAG,"Sending BLE State Change: " + BluetoothAdapter.nameForState(prevState) +
1761 " > " + BluetoothAdapter.nameForState(newState));
Nitin Arorad055adb2015-03-02 15:03:51 -08001762 // Send broadcast message to everyone else
1763 Intent intent = new Intent(BluetoothAdapter.ACTION_BLE_STATE_CHANGED);
1764 intent.putExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE, prevState);
1765 intent.putExtra(BluetoothAdapter.EXTRA_STATE, newState);
1766 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1767 mContext.sendBroadcastAsUser(intent, UserHandle.ALL, BLUETOOTH_PERM);
1768 }
1769
Zhihai Xu40874a02012-10-08 17:57:03 -07001770 private void bluetoothStateChangeHandler(int prevState, int newState) {
Nitin Arorad055adb2015-03-02 15:03:51 -08001771 boolean isStandardBroadcast = true;
Marie Janssencb21ad72016-12-13 10:51:02 -08001772 if (prevState == newState) { // No change. Nothing to do.
1773 return;
1774 }
1775 // Notify all proxy objects first of adapter state change
1776 if (newState == BluetoothAdapter.STATE_BLE_ON ||
1777 newState == BluetoothAdapter.STATE_OFF) {
1778 boolean intermediate_off = (prevState == BluetoothAdapter.STATE_TURNING_OFF
1779 && newState == BluetoothAdapter.STATE_BLE_ON);
Zhihai Xu40874a02012-10-08 17:57:03 -07001780
Marie Janssencb21ad72016-12-13 10:51:02 -08001781 if (newState == BluetoothAdapter.STATE_OFF) {
1782 // If Bluetooth is off, send service down event to proxy objects, and unbind
1783 if (DBG) Slog.d(TAG, "Bluetooth is complete send Service Down");
1784 sendBluetoothServiceDownCallback();
1785 unbindAndFinish();
Nitin Arorad055adb2015-03-02 15:03:51 -08001786 sendBleStateChanged(prevState, newState);
Marie Janssencb21ad72016-12-13 10:51:02 -08001787 // Don't broadcast as it has already been broadcast before
Nitin Arorad055adb2015-03-02 15:03:51 -08001788 isStandardBroadcast = false;
1789
Marie Janssencb21ad72016-12-13 10:51:02 -08001790 } else if (!intermediate_off) {
1791 // connect to GattService
1792 if (DBG) Slog.d(TAG, "Bluetooth is in LE only mode");
1793 if (mBluetoothGatt != null) {
1794 if (DBG) Slog.d(TAG, "Calling BluetoothGattServiceUp");
1795 onBluetoothGattServiceUp();
1796 } else {
1797 if (DBG) Slog.d(TAG, "Binding Bluetooth GATT service");
1798 if (mContext.getPackageManager().hasSystemFeature(
1799 PackageManager.FEATURE_BLUETOOTH_LE)) {
1800 Intent i = new Intent(IBluetoothGatt.class.getName());
1801 doBind(i, mConnection, Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT, UserHandle.CURRENT);
1802 }
Nitin Arorad055adb2015-03-02 15:03:51 -08001803 }
Marie Janssencb21ad72016-12-13 10:51:02 -08001804 sendBleStateChanged(prevState, newState);
1805 //Don't broadcase this as std intent
1806 isStandardBroadcast = false;
1807
1808 } else if (intermediate_off) {
1809 if (DBG) Slog.d(TAG, "Intermediate off, back to LE only mode");
1810 // For LE only mode, broadcast as is
1811 sendBleStateChanged(prevState, newState);
1812 sendBluetoothStateCallback(false); // BT is OFF for general users
1813 // Broadcast as STATE_OFF
1814 newState = BluetoothAdapter.STATE_OFF;
1815 sendBrEdrDownCallback();
Nitin Arorad055adb2015-03-02 15:03:51 -08001816 }
Marie Janssencb21ad72016-12-13 10:51:02 -08001817 } else if (newState == BluetoothAdapter.STATE_ON) {
1818 boolean isUp = (newState == BluetoothAdapter.STATE_ON);
1819 sendBluetoothStateCallback(isUp);
1820 sendBleStateChanged(prevState, newState);
1821
1822 } else if (newState == BluetoothAdapter.STATE_BLE_TURNING_ON ||
1823 newState == BluetoothAdapter.STATE_BLE_TURNING_OFF ) {
1824 sendBleStateChanged(prevState, newState);
1825 isStandardBroadcast = false;
1826
1827 } else if (newState == BluetoothAdapter.STATE_TURNING_ON ||
1828 newState == BluetoothAdapter.STATE_TURNING_OFF) {
1829 sendBleStateChanged(prevState, newState);
1830 }
1831
1832 if (isStandardBroadcast) {
1833 if (prevState == BluetoothAdapter.STATE_BLE_ON) {
1834 // Show prevState of BLE_ON as OFF to standard users
1835 prevState = BluetoothAdapter.STATE_OFF;
1836 }
1837 Intent intent = new Intent(BluetoothAdapter.ACTION_STATE_CHANGED);
1838 intent.putExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE, prevState);
1839 intent.putExtra(BluetoothAdapter.EXTRA_STATE, newState);
1840 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1841 mContext.sendBroadcastAsUser(intent, UserHandle.ALL, BLUETOOTH_PERM);
Zhihai Xu40874a02012-10-08 17:57:03 -07001842 }
1843 }
1844
1845 /**
1846 * if on is true, wait for state become ON
1847 * if off is true, wait for state become OFF
1848 * if both on and off are false, wait for state not ON
1849 */
1850 private boolean waitForOnOff(boolean on, boolean off) {
1851 int i = 0;
1852 while (i < 10) {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001853 try {
1854 mBluetoothLock.readLock().lock();
1855 if (mBluetooth == null) break;
1856 if (on) {
1857 if (mBluetooth.getState() == BluetoothAdapter.STATE_ON) return true;
1858 } else if (off) {
1859 if (mBluetooth.getState() == BluetoothAdapter.STATE_OFF) return true;
1860 } else {
1861 if (mBluetooth.getState() != BluetoothAdapter.STATE_ON) return true;
Zhihai Xu40874a02012-10-08 17:57:03 -07001862 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001863 } catch (RemoteException e) {
1864 Slog.e(TAG, "getState()", e);
1865 break;
1866 } finally {
1867 mBluetoothLock.readLock().unlock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001868 }
1869 if (on || off) {
1870 SystemClock.sleep(300);
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07001871 } else {
Zhihai Xu40874a02012-10-08 17:57:03 -07001872 SystemClock.sleep(50);
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07001873 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001874 i++;
1875 }
Jeff Sharkey67609c72016-03-05 14:29:13 -07001876 Slog.e(TAG,"waitForOnOff time out");
Zhihai Xu40874a02012-10-08 17:57:03 -07001877 return false;
1878 }
Zhihai Xu681ae7f2012-11-12 15:14:18 -08001879
Zhihai Xu401202b2012-12-03 11:36:21 -08001880 private void sendDisableMsg() {
1881 mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_DISABLE));
1882 }
1883
1884 private void sendEnableMsg(boolean quietMode) {
1885 mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_ENABLE,
1886 quietMode ? 1 : 0, 0));
1887 }
1888
Marie Janssen2977c3e2016-11-09 12:01:24 -08001889 private void recoverBluetoothServiceFromError(boolean clearBle) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001890 Slog.e(TAG,"recoverBluetoothServiceFromError");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001891 try {
1892 mBluetoothLock.readLock().lock();
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001893 if (mBluetooth != null) {
1894 //Unregister callback object
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001895 mBluetooth.unregisterCallback(mBluetoothCallback);
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001896 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001897 } catch (RemoteException re) {
1898 Slog.e(TAG, "Unable to unregister", re);
1899 } finally {
1900 mBluetoothLock.readLock().unlock();
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001901 }
1902
1903 SystemClock.sleep(500);
1904
1905 // disable
1906 handleDisable();
1907
1908 waitForOnOff(false, true);
1909
1910 sendBluetoothServiceDownCallback();
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001911
Pavlin Radoslavove957a8a2016-05-24 15:28:41 -07001912 try {
1913 mBluetoothLock.writeLock().lock();
1914 if (mBluetooth != null) {
1915 mBluetooth = null;
1916 // Unbind
1917 mContext.unbindService(mConnection);
1918 }
1919 mBluetoothGatt = null;
1920 } finally {
1921 mBluetoothLock.writeLock().unlock();
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001922 }
1923
1924 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
1925 mState = BluetoothAdapter.STATE_OFF;
1926
Marie Janssen2977c3e2016-11-09 12:01:24 -08001927 if (clearBle) {
1928 clearBleApps();
1929 }
1930
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001931 mEnable = false;
1932
1933 if (mErrorRecoveryRetryCounter++ < MAX_ERROR_RESTART_RETRIES) {
1934 // Send a Bluetooth Restart message to reenable bluetooth
1935 Message restartMsg = mHandler.obtainMessage(
1936 MESSAGE_RESTART_BLUETOOTH_SERVICE);
1937 mHandler.sendMessageDelayed(restartMsg, ERROR_RESTART_TIME_MS);
1938 } else {
1939 // todo: notify user to power down and power up phone to make bluetooth work.
1940 }
1941 }
Mike Lockwood726d4de2014-10-28 14:06:28 -07001942
Lenka Trochtova13a05192016-12-02 12:19:39 +01001943 private boolean isBluetoothDisallowed() {
1944 long callingIdentity = Binder.clearCallingIdentity();
1945 try {
1946 return mContext.getSystemService(UserManager.class)
1947 .hasUserRestriction(UserManager.DISALLOW_BLUETOOTH, UserHandle.SYSTEM);
1948 } finally {
1949 Binder.restoreCallingIdentity(callingIdentity);
1950 }
1951 }
1952
Mike Lockwood726d4de2014-10-28 14:06:28 -07001953 @Override
Pavlin Radoslavov6e8faff2016-02-23 11:54:37 -08001954 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1955 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DUMP, TAG);
1956 String errorMsg = null;
1957 if (mBluetoothBinder == null) {
1958 errorMsg = "Bluetooth Service not connected";
1959 } else {
1960 try {
1961 mBluetoothBinder.dump(fd, args);
1962 } catch (RemoteException re) {
1963 errorMsg = "RemoteException while calling Bluetooth Service";
1964 }
Mike Lockwood726d4de2014-10-28 14:06:28 -07001965 }
Pavlin Radoslavov6e8faff2016-02-23 11:54:37 -08001966 if (errorMsg != null) {
1967 // Silently return if we are extracting metrics in Protobuf format
1968 if ((args.length > 0) && args[0].startsWith("--proto"))
1969 return;
1970 writer.println(errorMsg);
1971 }
Mike Lockwood726d4de2014-10-28 14:06:28 -07001972 }
fredc0f420372012-04-12 00:02:00 -07001973}