blob: 1035ac8f7c7b024a5ceb7bc87d6d81a3472a7a14 [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
720 if (!isEnabled() && mPermissionReviewRequired
721 && startConsentUiIfNeeded(packageName, callingUid,
722 BluetoothAdapter.ACTION_REQUEST_ENABLE)) {
723 return false;
724 }
fredcf2458862012-04-16 15:18:27 -0700725 }
726
Zhihai Xu401202b2012-12-03 11:36:21 -0800727 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700728 Slog.d(TAG,"enable(): mBluetooth =" + mBluetooth +
Marie Janssencb21ad72016-12-13 10:51:02 -0800729 " mBinding = " + mBinding + " mState = " +
730 BluetoothAdapter.nameForState(mState));
Sanket Agarwal090bf552016-04-21 14:10:55 -0700731 }
Zhihai Xu401202b2012-12-03 11:36:21 -0800732
733 synchronized(mReceiver) {
734 mQuietEnableExternal = false;
735 mEnableExternal = true;
736 // waive WRITE_SECURE_SETTINGS permission check
Zhihai Xu401202b2012-12-03 11:36:21 -0800737 sendEnableMsg(false);
738 }
Jeff Sharkey67609c72016-03-05 14:29:13 -0700739 if (DBG) Slog.d(TAG, "enable returning");
Zhihai Xu401202b2012-12-03 11:36:21 -0800740 return true;
fredc0f420372012-04-12 00:02:00 -0700741 }
742
Svetoslav Ganovc2ac5bd2016-06-29 17:31:44 -0700743 public boolean disable(String packageName, boolean persist) throws RemoteException {
744 final int callingUid = Binder.getCallingUid();
745 final boolean callerSystem = UserHandle.getAppId(callingUid) == Process.SYSTEM_UID;
Zhihai Xu40874a02012-10-08 17:57:03 -0700746
Svetoslav Ganovc2ac5bd2016-06-29 17:31:44 -0700747 if (!callerSystem) {
748 if (!checkIfCallerIsForegroundUser()) {
749 Slog.w(TAG, "disable(): not allowed for non-active and non system user");
750 return false;
751 }
752
753 mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
754 "Need BLUETOOTH ADMIN permission");
755
756 if (isEnabled() && mPermissionReviewRequired
757 && startConsentUiIfNeeded(packageName, callingUid,
758 BluetoothAdapter.ACTION_REQUEST_DISABLE)) {
759 return false;
760 }
Zhihai Xu40874a02012-10-08 17:57:03 -0700761 }
762
fredcf2458862012-04-16 15:18:27 -0700763 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700764 Slog.d(TAG,"disable(): mBluetooth = " + mBluetooth +
Matthew Xiecdce0b92012-07-12 19:06:15 -0700765 " mBinding = " + mBinding);
766 }
fredcf2458862012-04-16 15:18:27 -0700767
Zhihai Xu401202b2012-12-03 11:36:21 -0800768 synchronized(mReceiver) {
769 if (persist) {
Zhihai Xu401202b2012-12-03 11:36:21 -0800770 persistBluetoothSetting(BLUETOOTH_OFF);
Zhihai Xu401202b2012-12-03 11:36:21 -0800771 }
772 mEnableExternal = false;
773 sendDisableMsg();
774 }
fredc0f420372012-04-12 00:02:00 -0700775 return true;
776 }
777
Svetoslav Ganovc2ac5bd2016-06-29 17:31:44 -0700778 private boolean startConsentUiIfNeeded(String packageName,
779 int callingUid, String intentAction) throws RemoteException {
780 try {
781 // Validate the package only if we are going to use it
782 ApplicationInfo applicationInfo = mContext.getPackageManager()
783 .getApplicationInfoAsUser(packageName,
784 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
785 UserHandle.getUserId(callingUid));
786 if (applicationInfo.uid != callingUid) {
787 throw new SecurityException("Package " + callingUid
788 + " not in uid " + callingUid);
789 }
790
791 // Legacy apps in permission review mode trigger a user prompt
792 if (applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
793 Intent intent = new Intent(intentAction);
794 mContext.startActivity(intent);
795 return true;
796 }
797 } catch (PackageManager.NameNotFoundException e) {
798 throw new RemoteException(e.getMessage());
799 }
800 return false;
801 }
802
fredc649fe492012-04-19 01:07:18 -0700803 public void unbindAndFinish() {
fredcf2458862012-04-16 15:18:27 -0700804 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700805 Slog.d(TAG,"unbindAndFinish(): " + mBluetooth +
Marie Janssencb21ad72016-12-13 10:51:02 -0800806 " mBinding = " + mBinding + " mUnbinding = " + mUnbinding);
fredcf2458862012-04-16 15:18:27 -0700807 }
808
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700809 try {
810 mBluetoothLock.writeLock().lock();
fredc0f420372012-04-12 00:02:00 -0700811 if (mUnbinding) return;
812 mUnbinding = true;
Pavlin Radoslavove47ec142016-06-01 22:25:18 -0700813 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
Pavlin Radoslavov74f60c02016-09-21 17:28:11 -0700814 mHandler.removeMessages(MESSAGE_BIND_PROFILE_SERVICE);
Zhihai Xu40874a02012-10-08 17:57:03 -0700815 if (mBluetooth != null) {
Andre Eisenbach305fdab2015-11-11 21:43:26 -0800816 //Unregister callback object
817 try {
818 mBluetooth.unregisterCallback(mBluetoothCallback);
819 } catch (RemoteException re) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700820 Slog.e(TAG, "Unable to unregister BluetoothCallback",re);
fredcbf072a72012-05-09 16:52:50 -0700821 }
Marie Janssen9db28eb2016-01-12 16:05:15 -0800822 mBluetoothBinder = null;
fredcd6883532012-04-25 17:46:13 -0700823 mBluetooth = null;
fredc0f420372012-04-12 00:02:00 -0700824 mContext.unbindService(mConnection);
fredcd6883532012-04-25 17:46:13 -0700825 mUnbinding = false;
Zhihai Xu40874a02012-10-08 17:57:03 -0700826 mBinding = false;
fredcf2458862012-04-16 15:18:27 -0700827 } else {
Marie Janssencb21ad72016-12-13 10:51:02 -0800828 mUnbinding = false;
fredc0f420372012-04-12 00:02:00 -0700829 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800830 mBluetoothGatt = null;
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700831 } finally {
832 mBluetoothLock.writeLock().unlock();
fredc0f420372012-04-12 00:02:00 -0700833 }
834 }
835
Matthew Xieddf7e472013-03-01 18:41:02 -0800836 public IBluetoothGatt getBluetoothGatt() {
837 // sync protection
838 return mBluetoothGatt;
839 }
840
Benjamin Franze8b98922014-11-12 15:57:54 +0000841 @Override
842 public boolean bindBluetoothProfileService(int bluetoothProfile,
843 IBluetoothProfileServiceConnection proxy) {
844 if (!mEnable) {
845 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700846 Slog.d(TAG, "Trying to bind to profile: " + bluetoothProfile +
Benjamin Franze8b98922014-11-12 15:57:54 +0000847 ", while Bluetooth was disabled");
848 }
849 return false;
850 }
851 synchronized (mProfileServices) {
852 ProfileServiceConnections psc = mProfileServices.get(new Integer(bluetoothProfile));
853 if (psc == null) {
854 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700855 Slog.d(TAG, "Creating new ProfileServiceConnections object for"
Benjamin Franze8b98922014-11-12 15:57:54 +0000856 + " profile: " + bluetoothProfile);
857 }
Benjamin Franz5b614592014-12-09 18:58:45 +0000858
859 if (bluetoothProfile != BluetoothProfile.HEADSET) return false;
860
861 Intent intent = new Intent(IBluetoothHeadset.class.getName());
Benjamin Franze8b98922014-11-12 15:57:54 +0000862 psc = new ProfileServiceConnections(intent);
Benjamin Franz5b614592014-12-09 18:58:45 +0000863 if (!psc.bindService()) return false;
864
Benjamin Franze8b98922014-11-12 15:57:54 +0000865 mProfileServices.put(new Integer(bluetoothProfile), psc);
Benjamin Franze8b98922014-11-12 15:57:54 +0000866 }
867 }
868
869 // Introducing a delay to give the client app time to prepare
870 Message addProxyMsg = mHandler.obtainMessage(MESSAGE_ADD_PROXY_DELAYED);
871 addProxyMsg.arg1 = bluetoothProfile;
872 addProxyMsg.obj = proxy;
873 mHandler.sendMessageDelayed(addProxyMsg, ADD_PROXY_DELAY_MS);
874 return true;
875 }
876
877 @Override
878 public void unbindBluetoothProfileService(int bluetoothProfile,
879 IBluetoothProfileServiceConnection proxy) {
880 synchronized (mProfileServices) {
881 ProfileServiceConnections psc = mProfileServices.get(new Integer(bluetoothProfile));
882 if (psc == null) {
883 return;
884 }
885 psc.removeProxy(proxy);
886 }
887 }
888
889 private void unbindAllBluetoothProfileServices() {
890 synchronized (mProfileServices) {
891 for (Integer i : mProfileServices.keySet()) {
892 ProfileServiceConnections psc = mProfileServices.get(i);
Benjamin Franz5b614592014-12-09 18:58:45 +0000893 try {
894 mContext.unbindService(psc);
895 } catch (IllegalArgumentException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700896 Slog.e(TAG, "Unable to unbind service with intent: " + psc.mIntent, e);
Benjamin Franz5b614592014-12-09 18:58:45 +0000897 }
Benjamin Franze8b98922014-11-12 15:57:54 +0000898 psc.removeAllProxies();
899 }
900 mProfileServices.clear();
901 }
902 }
903
904 /**
Miao Chou658bf2f2015-06-26 17:14:35 -0700905 * Send enable message and set adapter name and address. Called when the boot phase becomes
906 * PHASE_SYSTEM_SERVICES_READY.
907 */
908 public void handleOnBootPhase() {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700909 if (DBG) Slog.d(TAG, "Bluetooth boot completed");
Lenka Trochtova13a05192016-12-02 12:19:39 +0100910 UserManagerInternal userManagerInternal =
911 LocalServices.getService(UserManagerInternal.class);
912 userManagerInternal.addUserRestrictionsListener(mUserRestrictionsListener);
913 if (isBluetoothDisallowed()) {
914 return;
915 }
Miao Chou658bf2f2015-06-26 17:14:35 -0700916 if (mEnableExternal && isBluetoothPersistedStateOnBluetooth()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700917 if (DBG) Slog.d(TAG, "Auto-enabling Bluetooth.");
Miao Chou658bf2f2015-06-26 17:14:35 -0700918 sendEnableMsg(mQuietEnableExternal);
Ajay Panickerbf796d82016-03-11 13:47:20 -0800919 } else if (!isNameAndAddressSet()) {
920 if (DBG) Slog.d(TAG, "Getting adapter name and address");
Ajay Panicker4bb48302016-03-31 14:14:27 -0700921 Message getMsg = mHandler.obtainMessage(MESSAGE_GET_NAME_AND_ADDRESS);
922 mHandler.sendMessage(getMsg);
Miao Chou658bf2f2015-06-26 17:14:35 -0700923 }
Miao Chou658bf2f2015-06-26 17:14:35 -0700924 }
925
926 /**
927 * Called when switching to a different foreground user.
928 */
929 public void handleOnSwitchUser(int userHandle) {
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -0700930 if (DBG) Slog.d(TAG, "User " + userHandle + " switched");
931 mHandler.obtainMessage(MESSAGE_USER_SWITCHED, userHandle, 0).sendToTarget();
932 }
933
934 /**
935 * Called when user is unlocked.
936 */
937 public void handleOnUnlockUser(int userHandle) {
938 if (DBG) Slog.d(TAG, "User " + userHandle + " unlocked");
939 mHandler.obtainMessage(MESSAGE_USER_UNLOCKED, userHandle, 0).sendToTarget();
Miao Chou658bf2f2015-06-26 17:14:35 -0700940 }
941
942 /**
Benjamin Franze8b98922014-11-12 15:57:54 +0000943 * This class manages the clients connected to a given ProfileService
944 * and maintains the connection with that service.
945 */
946 final private class ProfileServiceConnections implements ServiceConnection,
947 IBinder.DeathRecipient {
948 final RemoteCallbackList<IBluetoothProfileServiceConnection> mProxies =
949 new RemoteCallbackList <IBluetoothProfileServiceConnection>();
950 IBinder mService;
951 ComponentName mClassName;
952 Intent mIntent;
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700953 boolean mInvokingProxyCallbacks = false;
Benjamin Franze8b98922014-11-12 15:57:54 +0000954
955 ProfileServiceConnections(Intent intent) {
956 mService = null;
957 mClassName = null;
958 mIntent = intent;
959 }
960
Benjamin Franz5b614592014-12-09 18:58:45 +0000961 private boolean bindService() {
962 if (mIntent != null && mService == null &&
963 doBind(mIntent, this, 0, UserHandle.CURRENT_OR_SELF)) {
Benjamin Franze8b98922014-11-12 15:57:54 +0000964 Message msg = mHandler.obtainMessage(MESSAGE_BIND_PROFILE_SERVICE);
965 msg.obj = this;
966 mHandler.sendMessageDelayed(msg, TIMEOUT_BIND_MS);
Benjamin Franz5b614592014-12-09 18:58:45 +0000967 return true;
Benjamin Franze8b98922014-11-12 15:57:54 +0000968 }
Jeff Sharkey67609c72016-03-05 14:29:13 -0700969 Slog.w(TAG, "Unable to bind with intent: " + mIntent);
Benjamin Franz5b614592014-12-09 18:58:45 +0000970 return false;
Benjamin Franze8b98922014-11-12 15:57:54 +0000971 }
972
973 private void addProxy(IBluetoothProfileServiceConnection proxy) {
974 mProxies.register(proxy);
975 if (mService != null) {
976 try{
977 proxy.onServiceConnected(mClassName, mService);
978 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700979 Slog.e(TAG, "Unable to connect to proxy", e);
Benjamin Franze8b98922014-11-12 15:57:54 +0000980 }
981 } else {
982 if (!mHandler.hasMessages(MESSAGE_BIND_PROFILE_SERVICE, this)) {
983 Message msg = mHandler.obtainMessage(MESSAGE_BIND_PROFILE_SERVICE);
984 msg.obj = this;
985 mHandler.sendMessage(msg);
986 }
987 }
988 }
989
990 private void removeProxy(IBluetoothProfileServiceConnection proxy) {
991 if (proxy != null) {
992 if (mProxies.unregister(proxy)) {
993 try {
994 proxy.onServiceDisconnected(mClassName);
995 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700996 Slog.e(TAG, "Unable to disconnect proxy", e);
Benjamin Franze8b98922014-11-12 15:57:54 +0000997 }
998 }
999 } else {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001000 Slog.w(TAG, "Trying to remove a null proxy");
Benjamin Franze8b98922014-11-12 15:57:54 +00001001 }
1002 }
1003
1004 private void removeAllProxies() {
1005 onServiceDisconnected(mClassName);
1006 mProxies.kill();
1007 }
1008
1009 @Override
1010 public void onServiceConnected(ComponentName className, IBinder service) {
1011 // remove timeout message
1012 mHandler.removeMessages(MESSAGE_BIND_PROFILE_SERVICE, this);
1013 mService = service;
1014 mClassName = className;
1015 try {
1016 mService.linkToDeath(this, 0);
1017 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001018 Slog.e(TAG, "Unable to linkToDeath", e);
Benjamin Franze8b98922014-11-12 15:57:54 +00001019 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001020
1021 if (mInvokingProxyCallbacks) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001022 Slog.e(TAG, "Proxy callbacks already in progress.");
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001023 return;
Benjamin Franze8b98922014-11-12 15:57:54 +00001024 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001025 mInvokingProxyCallbacks = true;
1026
1027 final int n = mProxies.beginBroadcast();
1028 try {
1029 for (int i = 0; i < n; i++) {
1030 try {
1031 mProxies.getBroadcastItem(i).onServiceConnected(className, service);
1032 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001033 Slog.e(TAG, "Unable to connect to proxy", e);
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001034 }
1035 }
1036 } finally {
1037 mProxies.finishBroadcast();
1038 mInvokingProxyCallbacks = false;
1039 }
Benjamin Franze8b98922014-11-12 15:57:54 +00001040 }
1041
1042 @Override
1043 public void onServiceDisconnected(ComponentName className) {
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001044 if (mService == null) return;
Benjamin Franze8b98922014-11-12 15:57:54 +00001045 mService.unlinkToDeath(this, 0);
1046 mService = null;
1047 mClassName = null;
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001048
1049 if (mInvokingProxyCallbacks) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001050 Slog.e(TAG, "Proxy callbacks already in progress.");
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001051 return;
Benjamin Franze8b98922014-11-12 15:57:54 +00001052 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001053 mInvokingProxyCallbacks = true;
1054
1055 final int n = mProxies.beginBroadcast();
1056 try {
1057 for (int i = 0; i < n; i++) {
1058 try {
1059 mProxies.getBroadcastItem(i).onServiceDisconnected(className);
1060 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001061 Slog.e(TAG, "Unable to disconnect from proxy", e);
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001062 }
1063 }
1064 } finally {
1065 mProxies.finishBroadcast();
1066 mInvokingProxyCallbacks = false;
1067 }
Benjamin Franze8b98922014-11-12 15:57:54 +00001068 }
1069
1070 @Override
1071 public void binderDied() {
1072 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001073 Slog.w(TAG, "Profile service for profile: " + mClassName
Benjamin Franze8b98922014-11-12 15:57:54 +00001074 + " died.");
1075 }
1076 onServiceDisconnected(mClassName);
1077 // Trigger rebind
1078 Message msg = mHandler.obtainMessage(MESSAGE_BIND_PROFILE_SERVICE);
1079 msg.obj = this;
1080 mHandler.sendMessageDelayed(msg, TIMEOUT_BIND_MS);
1081 }
1082 }
1083
fredcbf072a72012-05-09 16:52:50 -07001084 private void sendBluetoothStateCallback(boolean isUp) {
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001085 try {
1086 int n = mStateChangeCallbacks.beginBroadcast();
Jeff Sharkey67609c72016-03-05 14:29:13 -07001087 if (DBG) Slog.d(TAG,"Broadcasting onBluetoothStateChange("+isUp+") to " + n + " receivers.");
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001088 for (int i=0; i <n;i++) {
1089 try {
1090 mStateChangeCallbacks.getBroadcastItem(i).onBluetoothStateChange(isUp);
1091 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001092 Slog.e(TAG, "Unable to call onBluetoothStateChange() on callback #" + i , e);
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001093 }
fredcbf072a72012-05-09 16:52:50 -07001094 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001095 } finally {
1096 mStateChangeCallbacks.finishBroadcast();
fredcbf072a72012-05-09 16:52:50 -07001097 }
fredcbf072a72012-05-09 16:52:50 -07001098 }
1099
1100 /**
Zhihai Xu40874a02012-10-08 17:57:03 -07001101 * Inform BluetoothAdapter instances that Adapter service is up
1102 */
1103 private void sendBluetoothServiceUpCallback() {
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001104 try {
1105 int n = mCallbacks.beginBroadcast();
Jeff Sharkey67609c72016-03-05 14:29:13 -07001106 Slog.d(TAG,"Broadcasting onBluetoothServiceUp() to " + n + " receivers.");
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001107 for (int i=0; i <n;i++) {
1108 try {
1109 mCallbacks.getBroadcastItem(i).onBluetoothServiceUp(mBluetooth);
1110 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001111 Slog.e(TAG, "Unable to call onBluetoothServiceUp() on callback #" + i, e);
Zhihai Xu40874a02012-10-08 17:57:03 -07001112 }
1113 }
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001114 } finally {
1115 mCallbacks.finishBroadcast();
Zhihai Xu40874a02012-10-08 17:57:03 -07001116 }
1117 }
1118 /**
fredcbf072a72012-05-09 16:52:50 -07001119 * Inform BluetoothAdapter instances that Adapter service is down
1120 */
1121 private void sendBluetoothServiceDownCallback() {
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001122 try {
1123 int n = mCallbacks.beginBroadcast();
Jeff Sharkey67609c72016-03-05 14:29:13 -07001124 Slog.d(TAG,"Broadcasting onBluetoothServiceDown() to " + n + " receivers.");
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001125 for (int i=0; i <n;i++) {
1126 try {
1127 mCallbacks.getBroadcastItem(i).onBluetoothServiceDown();
1128 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001129 Slog.e(TAG, "Unable to call onBluetoothServiceDown() on callback #" + i, e);
fredcd6883532012-04-25 17:46:13 -07001130 }
1131 }
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001132 } finally {
1133 mCallbacks.finishBroadcast();
fredcd6883532012-04-25 17:46:13 -07001134 }
1135 }
Svet Ganov408abf72015-05-12 19:13:36 -07001136
fredc0f420372012-04-12 00:02:00 -07001137 public String getAddress() {
Matthew Xieaf5ddbf2012-12-04 10:47:43 -08001138 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
Svet Ganov408abf72015-05-12 19:13:36 -07001139 "Need BLUETOOTH permission");
Zhihai Xu40874a02012-10-08 17:57:03 -07001140
Zhihai Xu6eb76522012-11-29 15:41:04 -08001141 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
Svet Ganov408abf72015-05-12 19:13:36 -07001142 (!checkIfCallerIsForegroundUser())) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001143 Slog.w(TAG,"getAddress(): not allowed for non-active and non system user");
Zhihai Xu6eb76522012-11-29 15:41:04 -08001144 return null;
Zhihai Xu40874a02012-10-08 17:57:03 -07001145 }
1146
Svet Ganov408abf72015-05-12 19:13:36 -07001147 if (mContext.checkCallingOrSelfPermission(Manifest.permission.LOCAL_MAC_ADDRESS)
1148 != PackageManager.PERMISSION_GRANTED) {
1149 return BluetoothAdapter.DEFAULT_MAC_ADDRESS;
1150 }
1151
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001152 try {
1153 mBluetoothLock.readLock().lock();
1154 if (mBluetooth != null) return mBluetooth.getAddress();
1155 } catch (RemoteException e) {
1156 Slog.e(TAG, "getAddress(): Unable to retrieve address remotely. Returning cached address", e);
1157 } finally {
1158 mBluetoothLock.readLock().unlock();
fredc116d1d462012-04-20 14:47:08 -07001159 }
Ajay Panickerbf796d82016-03-11 13:47:20 -08001160
Matthew Xiecdce0b92012-07-12 19:06:15 -07001161 // mAddress is accessed from outside.
1162 // It is alright without a lock. Here, bluetooth is off, no other thread is
1163 // changing mAddress
fredc0f420372012-04-12 00:02:00 -07001164 return mAddress;
1165 }
fredc649fe492012-04-19 01:07:18 -07001166
fredc0f420372012-04-12 00:02:00 -07001167 public String getName() {
Matthew Xieaf5ddbf2012-12-04 10:47:43 -08001168 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
1169 "Need BLUETOOTH permission");
Zhihai Xu40874a02012-10-08 17:57:03 -07001170
Zhihai Xu6eb76522012-11-29 15:41:04 -08001171 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
1172 (!checkIfCallerIsForegroundUser())) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001173 Slog.w(TAG,"getName(): not allowed for non-active and non system user");
Zhihai Xu6eb76522012-11-29 15:41:04 -08001174 return null;
Zhihai Xu40874a02012-10-08 17:57:03 -07001175 }
1176
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001177 try {
1178 mBluetoothLock.readLock().lock();
1179 if (mBluetooth != null) return mBluetooth.getName();
1180 } catch (RemoteException e) {
1181 Slog.e(TAG, "getName(): Unable to retrieve name remotely. Returning cached name", e);
1182 } finally {
1183 mBluetoothLock.readLock().unlock();
fredc116d1d462012-04-20 14:47:08 -07001184 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001185
Matthew Xiecdce0b92012-07-12 19:06:15 -07001186 // mName is accessed from outside.
1187 // It alright without a lock. Here, bluetooth is off, no other thread is
1188 // changing mName
fredc0f420372012-04-12 00:02:00 -07001189 return mName;
1190 }
1191
fredc0f420372012-04-12 00:02:00 -07001192 private class BluetoothServiceConnection implements ServiceConnection {
Marie Janssencb21ad72016-12-13 10:51:02 -08001193 public void onServiceConnected(ComponentName componentName, IBinder service) {
1194 String name = componentName.getClassName();
1195 if (DBG) Slog.d(TAG, "BluetoothServiceConnection: " + name);
fredc0f420372012-04-12 00:02:00 -07001196 Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_SERVICE_CONNECTED);
Marie Janssencb21ad72016-12-13 10:51:02 -08001197 if (name.equals("com.android.bluetooth.btservice.AdapterService")) {
Matthew Xieddf7e472013-03-01 18:41:02 -08001198 msg.arg1 = SERVICE_IBLUETOOTH;
Marie Janssencb21ad72016-12-13 10:51:02 -08001199 } else if (name.equals("com.android.bluetooth.gatt.GattService")) {
Matthew Xieddf7e472013-03-01 18:41:02 -08001200 msg.arg1 = SERVICE_IBLUETOOTHGATT;
1201 } else {
Marie Janssencb21ad72016-12-13 10:51:02 -08001202 Slog.e(TAG, "Unknown service connected: " + name);
Matthew Xieddf7e472013-03-01 18:41:02 -08001203 return;
1204 }
fredc0f420372012-04-12 00:02:00 -07001205 msg.obj = service;
1206 mHandler.sendMessage(msg);
1207 }
1208
Marie Janssencb21ad72016-12-13 10:51:02 -08001209 public void onServiceDisconnected(ComponentName componentName) {
1210 // Called if we unexpectedly disconnect.
1211 String name = componentName.getClassName();
1212 if (DBG) Slog.d(TAG, "BluetoothServiceConnection, disconnected: " + name);
fredc0f420372012-04-12 00:02:00 -07001213 Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED);
Marie Janssencb21ad72016-12-13 10:51:02 -08001214 if (name.equals("com.android.bluetooth.btservice.AdapterService")) {
Matthew Xieddf7e472013-03-01 18:41:02 -08001215 msg.arg1 = SERVICE_IBLUETOOTH;
Marie Janssencb21ad72016-12-13 10:51:02 -08001216 } else if (name.equals("com.android.bluetooth.gatt.GattService")) {
Matthew Xieddf7e472013-03-01 18:41:02 -08001217 msg.arg1 = SERVICE_IBLUETOOTHGATT;
1218 } else {
Marie Janssencb21ad72016-12-13 10:51:02 -08001219 Slog.e(TAG, "Unknown service disconnected: " + name);
Matthew Xieddf7e472013-03-01 18:41:02 -08001220 return;
1221 }
fredc0f420372012-04-12 00:02:00 -07001222 mHandler.sendMessage(msg);
1223 }
1224 }
1225
1226 private BluetoothServiceConnection mConnection = new BluetoothServiceConnection();
1227
Zhihai Xu40874a02012-10-08 17:57:03 -07001228 private class BluetoothHandler extends Handler {
Ajay Panicker4bb48302016-03-31 14:14:27 -07001229 boolean mGetNameAddressOnly = false;
1230
Zhihai Xu40874a02012-10-08 17:57:03 -07001231 public BluetoothHandler(Looper looper) {
1232 super(looper);
1233 }
1234
fredc0f420372012-04-12 00:02:00 -07001235 @Override
1236 public void handleMessage(Message msg) {
fredc0f420372012-04-12 00:02:00 -07001237 switch (msg.what) {
Ajay Panicker4bb48302016-03-31 14:14:27 -07001238 case MESSAGE_GET_NAME_AND_ADDRESS:
1239 if (DBG) Slog.d(TAG, "MESSAGE_GET_NAME_AND_ADDRESS");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001240 try {
1241 mBluetoothLock.writeLock().lock();
Ajay Panicker4bb48302016-03-31 14:14:27 -07001242 if ((mBluetooth == null) && (!mBinding)) {
1243 if (DBG) Slog.d(TAG, "Binding to service to get name and address");
1244 mGetNameAddressOnly = true;
1245 Message timeoutMsg = mHandler.obtainMessage(MESSAGE_TIMEOUT_BIND);
1246 mHandler.sendMessageDelayed(timeoutMsg, TIMEOUT_BIND_MS);
1247 Intent i = new Intent(IBluetooth.class.getName());
1248 if (!doBind(i, mConnection,
1249 Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT,
1250 UserHandle.CURRENT)) {
1251 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
1252 } else {
1253 mBinding = true;
1254 }
1255 } else if (mBluetooth != null) {
1256 try {
1257 storeNameAndAddress(mBluetooth.getName(),
1258 mBluetooth.getAddress());
1259 } catch (RemoteException re) {
1260 Slog.e(TAG, "Unable to grab names", re);
1261 }
1262 if (mGetNameAddressOnly && !mEnable) {
1263 unbindAndFinish();
1264 }
1265 mGetNameAddressOnly = false;
1266 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001267 } finally {
1268 mBluetoothLock.writeLock().unlock();
Ajay Panicker4bb48302016-03-31 14:14:27 -07001269 }
1270 break;
1271
Matthew Xiecdce0b92012-07-12 19:06:15 -07001272 case MESSAGE_ENABLE:
fredcf2458862012-04-16 15:18:27 -07001273 if (DBG) {
Marie Janssencb21ad72016-12-13 10:51:02 -08001274 Slog.d(TAG, "MESSAGE_ENABLE(" + msg.arg1 + "): mBluetooth = " + mBluetooth);
fredc649fe492012-04-19 01:07:18 -07001275 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001276 mHandler.removeMessages(MESSAGE_RESTART_BLUETOOTH_SERVICE);
1277 mEnable = true;
Calvin Ona0b91d72016-06-15 17:58:23 -07001278
1279 // Use service interface to get the exact state
1280 try {
1281 mBluetoothLock.readLock().lock();
1282 if (mBluetooth != null) {
1283 int state = mBluetooth.getState();
1284 if (state == BluetoothAdapter.STATE_BLE_ON) {
1285 Slog.w(TAG, "BT is in BLE_ON State");
1286 mBluetooth.onLeServiceUp();
1287 break;
1288 }
1289 }
1290 } catch (RemoteException e) {
1291 Slog.e(TAG, "", e);
1292 } finally {
1293 mBluetoothLock.readLock().unlock();
1294 }
1295
1296 mQuietEnable = (msg.arg1 == 1);
Pavlin Radoslavove47ec142016-06-01 22:25:18 -07001297 if (mBluetooth == null) {
Calvin Ona0b91d72016-06-15 17:58:23 -07001298 handleEnable(mQuietEnable);
Pavlin Radoslavove47ec142016-06-01 22:25:18 -07001299 } else {
1300 //
1301 // We need to wait until transitioned to STATE_OFF and
1302 // the previous Bluetooth process has exited. The
1303 // waiting period has three components:
1304 // (a) Wait until the local state is STATE_OFF. This
1305 // is accomplished by "waitForOnOff(false, true)".
1306 // (b) Wait until the STATE_OFF state is updated to
1307 // all components.
1308 // (c) Wait until the Bluetooth process exits, and
1309 // ActivityManager detects it.
1310 // The waiting for (b) and (c) is accomplished by
1311 // delaying the MESSAGE_RESTART_BLUETOOTH_SERVICE
1312 // message. On slower devices, that delay needs to be
1313 // on the order of (2 * SERVICE_RESTART_TIME_MS).
1314 //
1315 waitForOnOff(false, true);
Pavlin Radoslavove47ec142016-06-01 22:25:18 -07001316 Message restartMsg = mHandler.obtainMessage(
1317 MESSAGE_RESTART_BLUETOOTH_SERVICE);
1318 mHandler.sendMessageDelayed(restartMsg,
1319 2 * SERVICE_RESTART_TIME_MS);
1320 }
fredc649fe492012-04-19 01:07:18 -07001321 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001322
fredc0f420372012-04-12 00:02:00 -07001323 case MESSAGE_DISABLE:
Marie Janssencb21ad72016-12-13 10:51:02 -08001324 if (DBG) Slog.d(TAG, "MESSAGE_DISABLE: mBluetooth = " + mBluetooth);
Zhihai Xu40874a02012-10-08 17:57:03 -07001325 mHandler.removeMessages(MESSAGE_RESTART_BLUETOOTH_SERVICE);
1326 if (mEnable && mBluetooth != null) {
1327 waitForOnOff(true, false);
1328 mEnable = false;
Zhihai Xu401202b2012-12-03 11:36:21 -08001329 handleDisable();
Zhihai Xu40874a02012-10-08 17:57:03 -07001330 waitForOnOff(false, false);
1331 } else {
1332 mEnable = false;
Zhihai Xu401202b2012-12-03 11:36:21 -08001333 handleDisable();
Zhihai Xu40874a02012-10-08 17:57:03 -07001334 }
fredc0f420372012-04-12 00:02:00 -07001335 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001336
fredc0f420372012-04-12 00:02:00 -07001337 case MESSAGE_REGISTER_ADAPTER:
1338 {
1339 IBluetoothManagerCallback callback = (IBluetoothManagerCallback) msg.obj;
Marie Janssencb21ad72016-12-13 10:51:02 -08001340 mCallbacks.register(callback);
fredc0f420372012-04-12 00:02:00 -07001341 break;
Marie Janssencb21ad72016-12-13 10:51:02 -08001342 }
fredc0f420372012-04-12 00:02:00 -07001343 case MESSAGE_UNREGISTER_ADAPTER:
1344 {
1345 IBluetoothManagerCallback callback = (IBluetoothManagerCallback) msg.obj;
Marie Janssencb21ad72016-12-13 10:51:02 -08001346 mCallbacks.unregister(callback);
fredc0f420372012-04-12 00:02:00 -07001347 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001348 }
fredc0f420372012-04-12 00:02:00 -07001349 case MESSAGE_REGISTER_STATE_CHANGE_CALLBACK:
1350 {
1351 IBluetoothStateChangeCallback callback = (IBluetoothStateChangeCallback) msg.obj;
Marie Janssencb21ad72016-12-13 10:51:02 -08001352 mStateChangeCallbacks.register(callback);
fredc0f420372012-04-12 00:02:00 -07001353 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001354 }
fredc0f420372012-04-12 00:02:00 -07001355 case MESSAGE_UNREGISTER_STATE_CHANGE_CALLBACK:
1356 {
1357 IBluetoothStateChangeCallback callback = (IBluetoothStateChangeCallback) msg.obj;
Marie Janssencb21ad72016-12-13 10:51:02 -08001358 mStateChangeCallbacks.unregister(callback);
fredc0f420372012-04-12 00:02:00 -07001359 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001360 }
Benjamin Franze8b98922014-11-12 15:57:54 +00001361 case MESSAGE_ADD_PROXY_DELAYED:
1362 {
1363 ProfileServiceConnections psc = mProfileServices.get(
1364 new Integer(msg.arg1));
1365 if (psc == null) {
1366 break;
1367 }
1368 IBluetoothProfileServiceConnection proxy =
1369 (IBluetoothProfileServiceConnection) msg.obj;
1370 psc.addProxy(proxy);
1371 break;
1372 }
1373 case MESSAGE_BIND_PROFILE_SERVICE:
1374 {
1375 ProfileServiceConnections psc = (ProfileServiceConnections) msg.obj;
1376 removeMessages(MESSAGE_BIND_PROFILE_SERVICE, msg.obj);
1377 if (psc == null) {
1378 break;
1379 }
1380 psc.bindService();
1381 break;
1382 }
fredc0f420372012-04-12 00:02:00 -07001383 case MESSAGE_BLUETOOTH_SERVICE_CONNECTED:
1384 {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001385 if (DBG) Slog.d(TAG,"MESSAGE_BLUETOOTH_SERVICE_CONNECTED: " + msg.arg1);
fredc0f420372012-04-12 00:02:00 -07001386
1387 IBinder service = (IBinder) msg.obj;
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001388 try {
1389 mBluetoothLock.writeLock().lock();
Matthew Xieddf7e472013-03-01 18:41:02 -08001390 if (msg.arg1 == SERVICE_IBLUETOOTHGATT) {
1391 mBluetoothGatt = IBluetoothGatt.Stub.asInterface(service);
Nitin Arorad055adb2015-03-02 15:03:51 -08001392 onBluetoothGattServiceUp();
Matthew Xieddf7e472013-03-01 18:41:02 -08001393 break;
1394 } // else must be SERVICE_IBLUETOOTH
1395
1396 //Remove timeout
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001397 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
Matthew Xieddf7e472013-03-01 18:41:02 -08001398
fredc0f420372012-04-12 00:02:00 -07001399 mBinding = false;
Marie Janssen9db28eb2016-01-12 16:05:15 -08001400 mBluetoothBinder = service;
fredc0f420372012-04-12 00:02:00 -07001401 mBluetooth = IBluetooth.Stub.asInterface(service);
fredc0f420372012-04-12 00:02:00 -07001402
Ajay Panicker4bb48302016-03-31 14:14:27 -07001403 if (!isNameAndAddressSet()) {
1404 Message getMsg = mHandler.obtainMessage(MESSAGE_GET_NAME_AND_ADDRESS);
1405 mHandler.sendMessage(getMsg);
1406 if (mGetNameAddressOnly) return;
1407 }
1408
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001409 try {
1410 boolean enableHciSnoopLog = (Settings.Secure.getInt(mContentResolver,
1411 Settings.Secure.BLUETOOTH_HCI_LOG, 0) == 1);
1412 if (!mBluetooth.configHciSnoopLog(enableHciSnoopLog)) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001413 Slog.e(TAG,"IBluetooth.configHciSnoopLog return false");
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001414 }
1415 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001416 Slog.e(TAG,"Unable to call configHciSnoopLog", e);
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001417 }
1418
Matthew Xiecdce0b92012-07-12 19:06:15 -07001419 //Register callback object
fredcbf072a72012-05-09 16:52:50 -07001420 try {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001421 mBluetooth.registerCallback(mBluetoothCallback);
1422 } catch (RemoteException re) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001423 Slog.e(TAG, "Unable to register BluetoothCallback",re);
fredcbf072a72012-05-09 16:52:50 -07001424 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001425 //Inform BluetoothAdapter instances that service is up
Zhihai Xu40874a02012-10-08 17:57:03 -07001426 sendBluetoothServiceUpCallback();
1427
Matthew Xiecdce0b92012-07-12 19:06:15 -07001428 //Do enable request
1429 try {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001430 if (mQuietEnable == false) {
Marie Janssencb21ad72016-12-13 10:51:02 -08001431 if (!mBluetooth.enable()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001432 Slog.e(TAG,"IBluetooth.enable() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001433 }
Marie Janssencb21ad72016-12-13 10:51:02 -08001434 } else {
1435 if (!mBluetooth.enableNoAutoConnect()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001436 Slog.e(TAG,"IBluetooth.enableNoAutoConnect() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001437 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001438 }
1439 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001440 Slog.e(TAG,"Unable to call enable()",e);
Matthew Xiecdce0b92012-07-12 19:06:15 -07001441 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001442 } finally {
1443 mBluetoothLock.writeLock().unlock();
Freda8c6df02012-07-11 10:25:23 -07001444 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001445
1446 if (!mEnable) {
1447 waitForOnOff(true, false);
Zhihai Xu401202b2012-12-03 11:36:21 -08001448 handleDisable();
Zhihai Xu40874a02012-10-08 17:57:03 -07001449 waitForOnOff(false, false);
1450 }
fredc649fe492012-04-19 01:07:18 -07001451 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001452 }
fredcbf072a72012-05-09 16:52:50 -07001453 case MESSAGE_BLUETOOTH_STATE_CHANGE:
fredc0f420372012-04-12 00:02:00 -07001454 {
fredcbf072a72012-05-09 16:52:50 -07001455 int prevState = msg.arg1;
1456 int newState = msg.arg2;
Marie Janssencb21ad72016-12-13 10:51:02 -08001457 if (DBG) {
1458 Slog.d(TAG, "MESSAGE_BLUETOOTH_STATE_CHANGE: " + BluetoothAdapter.nameForState(prevState) + " > " +
1459 BluetoothAdapter.nameForState(newState));
1460 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001461 mState = newState;
1462 bluetoothStateChangeHandler(prevState, newState);
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001463 // handle error state transition case from TURNING_ON to OFF
1464 // unbind and rebind bluetooth service and enable bluetooth
Nitin Arorad055adb2015-03-02 15:03:51 -08001465 if ((prevState == BluetoothAdapter.STATE_BLE_TURNING_ON) &&
Calvin Ona0b91d72016-06-15 17:58:23 -07001466 (newState == BluetoothAdapter.STATE_OFF) &&
1467 (mBluetooth != null) && mEnable) {
Marie Janssen2977c3e2016-11-09 12:01:24 -08001468 recoverBluetoothServiceFromError(false);
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001469 }
Nitin Arorad055adb2015-03-02 15:03:51 -08001470 if ((prevState == BluetoothAdapter.STATE_TURNING_ON) &&
Calvin Ona0b91d72016-06-15 17:58:23 -07001471 (newState == BluetoothAdapter.STATE_BLE_ON) &&
1472 (mBluetooth != null) && mEnable) {
Marie Janssen2977c3e2016-11-09 12:01:24 -08001473 recoverBluetoothServiceFromError(true);
Nitin Arorad055adb2015-03-02 15:03:51 -08001474 }
Calvin Ona0b91d72016-06-15 17:58:23 -07001475 // If we tried to enable BT while BT was in the process of shutting down,
1476 // wait for the BT process to fully tear down and then force a restart
1477 // here. This is a bit of a hack (b/29363429).
1478 if ((prevState == BluetoothAdapter.STATE_BLE_TURNING_OFF) &&
1479 (newState == BluetoothAdapter.STATE_OFF)) {
1480 if (mEnable) {
1481 Slog.d(TAG, "Entering STATE_OFF but mEnabled is true; restarting.");
1482 waitForOnOff(false, true);
1483 Message restartMsg = mHandler.obtainMessage(
1484 MESSAGE_RESTART_BLUETOOTH_SERVICE);
1485 mHandler.sendMessageDelayed(restartMsg, 2 * SERVICE_RESTART_TIME_MS);
1486 }
1487 }
Nitin Arorad055adb2015-03-02 15:03:51 -08001488 if (newState == BluetoothAdapter.STATE_ON ||
Calvin Ona0b91d72016-06-15 17:58:23 -07001489 newState == BluetoothAdapter.STATE_BLE_ON) {
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001490 // bluetooth is working, reset the counter
1491 if (mErrorRecoveryRetryCounter != 0) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001492 Slog.w(TAG, "bluetooth is recovered from error");
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001493 mErrorRecoveryRetryCounter = 0;
1494 }
1495 }
fredc649fe492012-04-19 01:07:18 -07001496 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001497 }
fredc0f420372012-04-12 00:02:00 -07001498 case MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED:
1499 {
Marie Janssencb21ad72016-12-13 10:51:02 -08001500 Slog.e(TAG, "MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED(" + msg.arg1 + ")");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001501 try {
1502 mBluetoothLock.writeLock().lock();
Matthew Xieddf7e472013-03-01 18:41:02 -08001503 if (msg.arg1 == SERVICE_IBLUETOOTH) {
1504 // if service is unbinded already, do nothing and return
1505 if (mBluetooth == null) break;
1506 mBluetooth = null;
1507 } else if (msg.arg1 == SERVICE_IBLUETOOTHGATT) {
1508 mBluetoothGatt = null;
1509 break;
1510 } else {
Marie Janssencb21ad72016-12-13 10:51:02 -08001511 Slog.e(TAG, "Unknown argument for service disconnect!");
Matthew Xieddf7e472013-03-01 18:41:02 -08001512 break;
1513 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001514 } finally {
1515 mBluetoothLock.writeLock().unlock();
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301516 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001517
1518 if (mEnable) {
1519 mEnable = false;
1520 // Send a Bluetooth Restart message
1521 Message restartMsg = mHandler.obtainMessage(
1522 MESSAGE_RESTART_BLUETOOTH_SERVICE);
1523 mHandler.sendMessageDelayed(restartMsg,
1524 SERVICE_RESTART_TIME_MS);
1525 }
1526
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001527 sendBluetoothServiceDownCallback();
Zhihai Xu40874a02012-10-08 17:57:03 -07001528
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001529 // Send BT state broadcast to update
1530 // the BT icon correctly
1531 if ((mState == BluetoothAdapter.STATE_TURNING_ON) ||
Calvin Ona0b91d72016-06-15 17:58:23 -07001532 (mState == BluetoothAdapter.STATE_ON)) {
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001533 bluetoothStateChangeHandler(BluetoothAdapter.STATE_ON,
1534 BluetoothAdapter.STATE_TURNING_OFF);
1535 mState = BluetoothAdapter.STATE_TURNING_OFF;
Zhihai Xu40874a02012-10-08 17:57:03 -07001536 }
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001537 if (mState == BluetoothAdapter.STATE_TURNING_OFF) {
1538 bluetoothStateChangeHandler(BluetoothAdapter.STATE_TURNING_OFF,
1539 BluetoothAdapter.STATE_OFF);
1540 }
1541
1542 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
1543 mState = BluetoothAdapter.STATE_OFF;
fredc649fe492012-04-19 01:07:18 -07001544 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001545 }
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301546 case MESSAGE_RESTART_BLUETOOTH_SERVICE:
1547 {
Marie Janssencb21ad72016-12-13 10:51:02 -08001548 Slog.d(TAG, "MESSAGE_RESTART_BLUETOOTH_SERVICE");
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301549 /* Enable without persisting the setting as
1550 it doesnt change when IBluetooth
1551 service restarts */
Zhihai Xu40874a02012-10-08 17:57:03 -07001552 mEnable = true;
Zhihai Xu401202b2012-12-03 11:36:21 -08001553 handleEnable(mQuietEnable);
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301554 break;
1555 }
Marie Janssencb21ad72016-12-13 10:51:02 -08001556 case MESSAGE_TIMEOUT_BIND: {
1557 Slog.e(TAG, "MESSAGE_TIMEOUT_BIND");
1558 mBluetoothLock.writeLock().lock();
1559 mBinding = false;
1560 mBluetoothLock.writeLock().unlock();
1561 break;
1562 }
fredc0f420372012-04-12 00:02:00 -07001563 case MESSAGE_TIMEOUT_UNBIND:
1564 {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001565 Slog.e(TAG, "MESSAGE_TIMEOUT_UNBIND");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001566 mBluetoothLock.writeLock().lock();
1567 mUnbinding = false;
1568 mBluetoothLock.writeLock().unlock();
fredc649fe492012-04-19 01:07:18 -07001569 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001570 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001571
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001572 case MESSAGE_USER_SWITCHED: {
1573 if (DBG) Slog.d(TAG, "MESSAGE_USER_SWITCHED");
Zhihai Xu40874a02012-10-08 17:57:03 -07001574 mHandler.removeMessages(MESSAGE_USER_SWITCHED);
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001575
Zhihai Xu40874a02012-10-08 17:57:03 -07001576 /* disable and enable BT when detect a user switch */
1577 if (mEnable && mBluetooth != null) {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001578 try {
1579 mBluetoothLock.readLock().lock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001580 if (mBluetooth != null) {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001581 mBluetooth.unregisterCallback(mBluetoothCallback);
Zhihai Xu40874a02012-10-08 17:57:03 -07001582 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001583 } catch (RemoteException re) {
1584 Slog.e(TAG, "Unable to unregister", re);
1585 } finally {
1586 mBluetoothLock.readLock().unlock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001587 }
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001588
1589 if (mState == BluetoothAdapter.STATE_TURNING_OFF) {
1590 // MESSAGE_USER_SWITCHED happened right after MESSAGE_ENABLE
1591 bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_OFF);
1592 mState = BluetoothAdapter.STATE_OFF;
1593 }
1594 if (mState == BluetoothAdapter.STATE_OFF) {
1595 bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_TURNING_ON);
1596 mState = BluetoothAdapter.STATE_TURNING_ON;
1597 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001598
1599 waitForOnOff(true, false);
1600
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001601 if (mState == BluetoothAdapter.STATE_TURNING_ON) {
1602 bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_ON);
1603 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001604
Benjamin Franze8b98922014-11-12 15:57:54 +00001605 unbindAllBluetoothProfileServices();
Zhihai Xu40874a02012-10-08 17:57:03 -07001606 // disable
Zhihai Xu401202b2012-12-03 11:36:21 -08001607 handleDisable();
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001608 // Pbap service need receive STATE_TURNING_OFF intent to close
1609 bluetoothStateChangeHandler(BluetoothAdapter.STATE_ON,
1610 BluetoothAdapter.STATE_TURNING_OFF);
Zhihai Xu40874a02012-10-08 17:57:03 -07001611
Pavlin Radoslavov41401112016-06-27 15:25:18 -07001612 boolean didDisableTimeout = !waitForOnOff(false, true);
Zhihai Xu40874a02012-10-08 17:57:03 -07001613
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001614 bluetoothStateChangeHandler(BluetoothAdapter.STATE_TURNING_OFF,
Zhihai Xu40874a02012-10-08 17:57:03 -07001615 BluetoothAdapter.STATE_OFF);
Zhihai Xu40874a02012-10-08 17:57:03 -07001616 sendBluetoothServiceDownCallback();
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001617
Pavlin Radoslavove957a8a2016-05-24 15:28:41 -07001618 try {
1619 mBluetoothLock.writeLock().lock();
1620 if (mBluetooth != null) {
1621 mBluetooth = null;
1622 // Unbind
1623 mContext.unbindService(mConnection);
1624 }
1625 mBluetoothGatt = null;
1626 } finally {
1627 mBluetoothLock.writeLock().unlock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001628 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001629
Pavlin Radoslavov41401112016-06-27 15:25:18 -07001630 //
1631 // If disabling Bluetooth times out, wait for an
1632 // additional amount of time to ensure the process is
1633 // shut down completely before attempting to restart.
1634 //
1635 if (didDisableTimeout) {
1636 SystemClock.sleep(3000);
1637 } else {
1638 SystemClock.sleep(100);
1639 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001640
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001641 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
1642 mState = BluetoothAdapter.STATE_OFF;
Zhihai Xu40874a02012-10-08 17:57:03 -07001643 // enable
Zhihai Xu401202b2012-12-03 11:36:21 -08001644 handleEnable(mQuietEnable);
John Spurlock8a985d22014-02-25 09:40:05 -05001645 } else if (mBinding || mBluetooth != null) {
Zhihai Xu40874a02012-10-08 17:57:03 -07001646 Message userMsg = mHandler.obtainMessage(MESSAGE_USER_SWITCHED);
1647 userMsg.arg2 = 1 + msg.arg2;
Marie Janssencb21ad72016-12-13 10:51:02 -08001648 // if user is switched when service is binding retry after a delay
Zhihai Xu40874a02012-10-08 17:57:03 -07001649 mHandler.sendMessageDelayed(userMsg, USER_SWITCHED_TIME_MS);
1650 if (DBG) {
Marie Janssencb21ad72016-12-13 10:51:02 -08001651 Slog.d(TAG, "Retry MESSAGE_USER_SWITCHED " + userMsg.arg2);
Zhihai Xu40874a02012-10-08 17:57:03 -07001652 }
John Spurlock8a985d22014-02-25 09:40:05 -05001653 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001654 break;
1655 }
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001656 case MESSAGE_USER_UNLOCKED: {
1657 if (DBG) Slog.d(TAG, "MESSAGE_USER_UNLOCKED");
1658 mHandler.removeMessages(MESSAGE_USER_SWITCHED);
1659
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001660 if (mEnable && !mBinding && (mBluetooth == null)) {
1661 // We should be connected, but we gave up for some
1662 // reason; maybe the Bluetooth service wasn't encryption
1663 // aware, so try binding again.
1664 if (DBG) Slog.d(TAG, "Enabled but not bound; retrying after unlock");
1665 handleEnable(mQuietEnable);
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001666 }
1667 }
fredc0f420372012-04-12 00:02:00 -07001668 }
1669 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001670 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001671
Zhihai Xu401202b2012-12-03 11:36:21 -08001672 private void handleEnable(boolean quietMode) {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001673 mQuietEnable = quietMode;
1674
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001675 try {
1676 mBluetoothLock.writeLock().lock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001677 if ((mBluetooth == null) && (!mBinding)) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001678 //Start bind timeout and bind
1679 Message timeoutMsg=mHandler.obtainMessage(MESSAGE_TIMEOUT_BIND);
1680 mHandler.sendMessageDelayed(timeoutMsg,TIMEOUT_BIND_MS);
Matthew Xiecdce0b92012-07-12 19:06:15 -07001681 Intent i = new Intent(IBluetooth.class.getName());
Dianne Hackbornce09f5a2014-10-10 15:03:13 -07001682 if (!doBind(i, mConnection,Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT,
1683 UserHandle.CURRENT)) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001684 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
Zhihai Xu40874a02012-10-08 17:57:03 -07001685 } else {
1686 mBinding = true;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001687 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001688 } else if (mBluetooth != null) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001689 //Enable bluetooth
1690 try {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001691 if (!mQuietEnable) {
1692 if(!mBluetooth.enable()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001693 Slog.e(TAG,"IBluetooth.enable() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001694 }
1695 }
1696 else {
1697 if(!mBluetooth.enableNoAutoConnect()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001698 Slog.e(TAG,"IBluetooth.enableNoAutoConnect() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001699 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001700 }
1701 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001702 Slog.e(TAG,"Unable to call enable()",e);
Matthew Xiecdce0b92012-07-12 19:06:15 -07001703 }
1704 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001705 } finally {
1706 mBluetoothLock.writeLock().unlock();
Matthew Xiecdce0b92012-07-12 19:06:15 -07001707 }
1708 }
1709
Dianne Hackborn221ea892013-08-04 16:50:16 -07001710 boolean doBind(Intent intent, ServiceConnection conn, int flags, UserHandle user) {
1711 ComponentName comp = intent.resolveSystemService(mContext.getPackageManager(), 0);
1712 intent.setComponent(comp);
1713 if (comp == null || !mContext.bindServiceAsUser(intent, conn, flags, user)) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001714 Slog.e(TAG, "Fail to bind to: " + intent);
Dianne Hackborn221ea892013-08-04 16:50:16 -07001715 return false;
1716 }
1717 return true;
1718 }
1719
Zhihai Xu401202b2012-12-03 11:36:21 -08001720 private void handleDisable() {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001721 try {
1722 mBluetoothLock.readLock().lock();
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001723 if (mBluetooth != null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001724 if (DBG) Slog.d(TAG,"Sending off request.");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001725 if (!mBluetooth.disable()) {
1726 Slog.e(TAG,"IBluetooth.disable() returned false");
Matthew Xiecdce0b92012-07-12 19:06:15 -07001727 }
1728 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001729 } catch (RemoteException e) {
1730 Slog.e(TAG,"Unable to call disable()",e);
1731 } finally {
1732 mBluetoothLock.readLock().unlock();
Matthew Xiecdce0b92012-07-12 19:06:15 -07001733 }
1734 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001735
1736 private boolean checkIfCallerIsForegroundUser() {
1737 int foregroundUser;
1738 int callingUser = UserHandle.getCallingUserId();
Martijn Coenen8385c5a2012-11-29 10:14:16 -08001739 int callingUid = Binder.getCallingUid();
Zhihai Xu40874a02012-10-08 17:57:03 -07001740 long callingIdentity = Binder.clearCallingIdentity();
Benjamin Franze8b98922014-11-12 15:57:54 +00001741 UserManager um = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
1742 UserInfo ui = um.getProfileParent(callingUser);
1743 int parentUser = (ui != null) ? ui.id : UserHandle.USER_NULL;
Martijn Coenen8385c5a2012-11-29 10:14:16 -08001744 int callingAppId = UserHandle.getAppId(callingUid);
Zhihai Xu40874a02012-10-08 17:57:03 -07001745 boolean valid = false;
1746 try {
1747 foregroundUser = ActivityManager.getCurrentUser();
Martijn Coenen8385c5a2012-11-29 10:14:16 -08001748 valid = (callingUser == foregroundUser) ||
Benjamin Franze8b98922014-11-12 15:57:54 +00001749 parentUser == foregroundUser ||
Adrian Roosbd9a9a52014-08-18 15:31:57 +02001750 callingAppId == Process.NFC_UID ||
1751 callingAppId == mSystemUiUid;
Marie Janssencb21ad72016-12-13 10:51:02 -08001752 if (DBG && !valid) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001753 Slog.d(TAG, "checkIfCallerIsForegroundUser: valid=" + valid
Zhihai Xu40874a02012-10-08 17:57:03 -07001754 + " callingUser=" + callingUser
Benjamin Franze8b98922014-11-12 15:57:54 +00001755 + " parentUser=" + parentUser
Zhihai Xu40874a02012-10-08 17:57:03 -07001756 + " foregroundUser=" + foregroundUser);
1757 }
1758 } finally {
1759 Binder.restoreCallingIdentity(callingIdentity);
1760 }
1761 return valid;
1762 }
1763
Nitin Arorad055adb2015-03-02 15:03:51 -08001764 private void sendBleStateChanged(int prevState, int newState) {
Marie Janssencb21ad72016-12-13 10:51:02 -08001765 if (DBG) Slog.d(TAG,"Sending BLE State Change: " + BluetoothAdapter.nameForState(prevState) +
1766 " > " + BluetoothAdapter.nameForState(newState));
Nitin Arorad055adb2015-03-02 15:03:51 -08001767 // Send broadcast message to everyone else
1768 Intent intent = new Intent(BluetoothAdapter.ACTION_BLE_STATE_CHANGED);
1769 intent.putExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE, prevState);
1770 intent.putExtra(BluetoothAdapter.EXTRA_STATE, newState);
1771 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1772 mContext.sendBroadcastAsUser(intent, UserHandle.ALL, BLUETOOTH_PERM);
1773 }
1774
Zhihai Xu40874a02012-10-08 17:57:03 -07001775 private void bluetoothStateChangeHandler(int prevState, int newState) {
Nitin Arorad055adb2015-03-02 15:03:51 -08001776 boolean isStandardBroadcast = true;
Marie Janssencb21ad72016-12-13 10:51:02 -08001777 if (prevState == newState) { // No change. Nothing to do.
1778 return;
1779 }
1780 // Notify all proxy objects first of adapter state change
1781 if (newState == BluetoothAdapter.STATE_BLE_ON ||
1782 newState == BluetoothAdapter.STATE_OFF) {
1783 boolean intermediate_off = (prevState == BluetoothAdapter.STATE_TURNING_OFF
1784 && newState == BluetoothAdapter.STATE_BLE_ON);
Zhihai Xu40874a02012-10-08 17:57:03 -07001785
Marie Janssencb21ad72016-12-13 10:51:02 -08001786 if (newState == BluetoothAdapter.STATE_OFF) {
1787 // If Bluetooth is off, send service down event to proxy objects, and unbind
1788 if (DBG) Slog.d(TAG, "Bluetooth is complete send Service Down");
1789 sendBluetoothServiceDownCallback();
1790 unbindAndFinish();
Nitin Arorad055adb2015-03-02 15:03:51 -08001791 sendBleStateChanged(prevState, newState);
Marie Janssencb21ad72016-12-13 10:51:02 -08001792 // Don't broadcast as it has already been broadcast before
Nitin Arorad055adb2015-03-02 15:03:51 -08001793 isStandardBroadcast = false;
1794
Marie Janssencb21ad72016-12-13 10:51:02 -08001795 } else if (!intermediate_off) {
1796 // connect to GattService
1797 if (DBG) Slog.d(TAG, "Bluetooth is in LE only mode");
1798 if (mBluetoothGatt != null) {
1799 if (DBG) Slog.d(TAG, "Calling BluetoothGattServiceUp");
1800 onBluetoothGattServiceUp();
1801 } else {
1802 if (DBG) Slog.d(TAG, "Binding Bluetooth GATT service");
1803 if (mContext.getPackageManager().hasSystemFeature(
1804 PackageManager.FEATURE_BLUETOOTH_LE)) {
1805 Intent i = new Intent(IBluetoothGatt.class.getName());
1806 doBind(i, mConnection, Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT, UserHandle.CURRENT);
1807 }
Nitin Arorad055adb2015-03-02 15:03:51 -08001808 }
Marie Janssencb21ad72016-12-13 10:51:02 -08001809 sendBleStateChanged(prevState, newState);
1810 //Don't broadcase this as std intent
1811 isStandardBroadcast = false;
1812
1813 } else if (intermediate_off) {
1814 if (DBG) Slog.d(TAG, "Intermediate off, back to LE only mode");
1815 // For LE only mode, broadcast as is
1816 sendBleStateChanged(prevState, newState);
1817 sendBluetoothStateCallback(false); // BT is OFF for general users
1818 // Broadcast as STATE_OFF
1819 newState = BluetoothAdapter.STATE_OFF;
1820 sendBrEdrDownCallback();
Nitin Arorad055adb2015-03-02 15:03:51 -08001821 }
Marie Janssencb21ad72016-12-13 10:51:02 -08001822 } else if (newState == BluetoothAdapter.STATE_ON) {
1823 boolean isUp = (newState == BluetoothAdapter.STATE_ON);
1824 sendBluetoothStateCallback(isUp);
1825 sendBleStateChanged(prevState, newState);
1826
1827 } else if (newState == BluetoothAdapter.STATE_BLE_TURNING_ON ||
1828 newState == BluetoothAdapter.STATE_BLE_TURNING_OFF ) {
1829 sendBleStateChanged(prevState, newState);
1830 isStandardBroadcast = false;
1831
1832 } else if (newState == BluetoothAdapter.STATE_TURNING_ON ||
1833 newState == BluetoothAdapter.STATE_TURNING_OFF) {
1834 sendBleStateChanged(prevState, newState);
1835 }
1836
1837 if (isStandardBroadcast) {
1838 if (prevState == BluetoothAdapter.STATE_BLE_ON) {
1839 // Show prevState of BLE_ON as OFF to standard users
1840 prevState = BluetoothAdapter.STATE_OFF;
1841 }
1842 Intent intent = new Intent(BluetoothAdapter.ACTION_STATE_CHANGED);
1843 intent.putExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE, prevState);
1844 intent.putExtra(BluetoothAdapter.EXTRA_STATE, newState);
1845 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1846 mContext.sendBroadcastAsUser(intent, UserHandle.ALL, BLUETOOTH_PERM);
Zhihai Xu40874a02012-10-08 17:57:03 -07001847 }
1848 }
1849
1850 /**
1851 * if on is true, wait for state become ON
1852 * if off is true, wait for state become OFF
1853 * if both on and off are false, wait for state not ON
1854 */
1855 private boolean waitForOnOff(boolean on, boolean off) {
1856 int i = 0;
1857 while (i < 10) {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001858 try {
1859 mBluetoothLock.readLock().lock();
1860 if (mBluetooth == null) break;
1861 if (on) {
1862 if (mBluetooth.getState() == BluetoothAdapter.STATE_ON) return true;
1863 } else if (off) {
1864 if (mBluetooth.getState() == BluetoothAdapter.STATE_OFF) return true;
1865 } else {
1866 if (mBluetooth.getState() != BluetoothAdapter.STATE_ON) return true;
Zhihai Xu40874a02012-10-08 17:57:03 -07001867 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001868 } catch (RemoteException e) {
1869 Slog.e(TAG, "getState()", e);
1870 break;
1871 } finally {
1872 mBluetoothLock.readLock().unlock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001873 }
1874 if (on || off) {
1875 SystemClock.sleep(300);
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07001876 } else {
Zhihai Xu40874a02012-10-08 17:57:03 -07001877 SystemClock.sleep(50);
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07001878 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001879 i++;
1880 }
Jeff Sharkey67609c72016-03-05 14:29:13 -07001881 Slog.e(TAG,"waitForOnOff time out");
Zhihai Xu40874a02012-10-08 17:57:03 -07001882 return false;
1883 }
Zhihai Xu681ae7f2012-11-12 15:14:18 -08001884
Zhihai Xu401202b2012-12-03 11:36:21 -08001885 private void sendDisableMsg() {
1886 mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_DISABLE));
1887 }
1888
1889 private void sendEnableMsg(boolean quietMode) {
1890 mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_ENABLE,
1891 quietMode ? 1 : 0, 0));
1892 }
1893
Marie Janssen2977c3e2016-11-09 12:01:24 -08001894 private void recoverBluetoothServiceFromError(boolean clearBle) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001895 Slog.e(TAG,"recoverBluetoothServiceFromError");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001896 try {
1897 mBluetoothLock.readLock().lock();
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001898 if (mBluetooth != null) {
1899 //Unregister callback object
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001900 mBluetooth.unregisterCallback(mBluetoothCallback);
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001901 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001902 } catch (RemoteException re) {
1903 Slog.e(TAG, "Unable to unregister", re);
1904 } finally {
1905 mBluetoothLock.readLock().unlock();
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001906 }
1907
1908 SystemClock.sleep(500);
1909
1910 // disable
1911 handleDisable();
1912
1913 waitForOnOff(false, true);
1914
1915 sendBluetoothServiceDownCallback();
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001916
Pavlin Radoslavove957a8a2016-05-24 15:28:41 -07001917 try {
1918 mBluetoothLock.writeLock().lock();
1919 if (mBluetooth != null) {
1920 mBluetooth = null;
1921 // Unbind
1922 mContext.unbindService(mConnection);
1923 }
1924 mBluetoothGatt = null;
1925 } finally {
1926 mBluetoothLock.writeLock().unlock();
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001927 }
1928
1929 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
1930 mState = BluetoothAdapter.STATE_OFF;
1931
Marie Janssen2977c3e2016-11-09 12:01:24 -08001932 if (clearBle) {
1933 clearBleApps();
1934 }
1935
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001936 mEnable = false;
1937
1938 if (mErrorRecoveryRetryCounter++ < MAX_ERROR_RESTART_RETRIES) {
1939 // Send a Bluetooth Restart message to reenable bluetooth
1940 Message restartMsg = mHandler.obtainMessage(
1941 MESSAGE_RESTART_BLUETOOTH_SERVICE);
1942 mHandler.sendMessageDelayed(restartMsg, ERROR_RESTART_TIME_MS);
1943 } else {
1944 // todo: notify user to power down and power up phone to make bluetooth work.
1945 }
1946 }
Mike Lockwood726d4de2014-10-28 14:06:28 -07001947
Lenka Trochtova13a05192016-12-02 12:19:39 +01001948 private boolean isBluetoothDisallowed() {
1949 long callingIdentity = Binder.clearCallingIdentity();
1950 try {
1951 return mContext.getSystemService(UserManager.class)
1952 .hasUserRestriction(UserManager.DISALLOW_BLUETOOTH, UserHandle.SYSTEM);
1953 } finally {
1954 Binder.restoreCallingIdentity(callingIdentity);
1955 }
1956 }
1957
Mike Lockwood726d4de2014-10-28 14:06:28 -07001958 @Override
Pavlin Radoslavov6e8faff2016-02-23 11:54:37 -08001959 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1960 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DUMP, TAG);
1961 String errorMsg = null;
1962 if (mBluetoothBinder == null) {
1963 errorMsg = "Bluetooth Service not connected";
1964 } else {
1965 try {
1966 mBluetoothBinder.dump(fd, args);
1967 } catch (RemoteException re) {
1968 errorMsg = "RemoteException while calling Bluetooth Service";
1969 }
Mike Lockwood726d4de2014-10-28 14:06:28 -07001970 }
Pavlin Radoslavov6e8faff2016-02-23 11:54:37 -08001971 if (errorMsg != null) {
1972 // Silently return if we are extracting metrics in Protobuf format
1973 if ((args.length > 0) && args[0].startsWith("--proto"))
1974 return;
1975 writer.println(errorMsg);
1976 }
Mike Lockwood726d4de2014-10-28 14:06:28 -07001977 }
fredc0f420372012-04-12 00:02:00 -07001978}