blob: cedc6dc257aec35c1a1ad4f1b477fb10c39ca6fa [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;
Shijian Li5e7fc7c2017-01-11 17:32:12 +000031import android.content.ActivityNotFoundException;
fredc0f420372012-04-12 00:02:00 -070032import android.content.BroadcastReceiver;
33import android.content.ComponentName;
34import android.content.ContentResolver;
35import android.content.Context;
36import android.content.Intent;
37import android.content.IntentFilter;
38import android.content.ServiceConnection;
Svetoslav Ganovb1e2da72016-06-29 17:31:44 -070039import android.content.pm.ApplicationInfo;
Matthew Xie32ab77b2013-05-08 19:26:57 -070040import android.content.pm.PackageManager;
Benjamin Franze8b98922014-11-12 15:57:54 +000041import android.content.pm.UserInfo;
Wei Wange4a744b2015-06-11 17:50:29 -070042import android.database.ContentObserver;
Zhihai Xu40874a02012-10-08 17:57:03 -070043import android.os.Binder;
Lenka Trochtova13a05192016-12-02 12:19:39 +010044import android.os.Bundle;
Svetoslav Ganovb1e2da72016-06-29 17:31:44 -070045import android.os.Build;
fredc0f420372012-04-12 00:02:00 -070046import android.os.Handler;
fredc0f420372012-04-12 00:02:00 -070047import android.os.IBinder;
Zhihai Xu40874a02012-10-08 17:57:03 -070048import android.os.Looper;
fredc0f420372012-04-12 00:02:00 -070049import android.os.Message;
Zhihai Xu40874a02012-10-08 17:57:03 -070050import android.os.Process;
fredcd6883532012-04-25 17:46:13 -070051import android.os.RemoteCallbackList;
fredc0f420372012-04-12 00:02:00 -070052import android.os.RemoteException;
Zhihai Xu40874a02012-10-08 17:57:03 -070053import android.os.SystemClock;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070054import android.os.UserHandle;
Benjamin Franze8b98922014-11-12 15:57:54 +000055import android.os.UserManager;
Lenka Trochtova13a05192016-12-02 12:19:39 +010056import android.os.UserManagerInternal;
57import android.os.UserManagerInternal.UserRestrictionsListener;
fredc0f420372012-04-12 00:02:00 -070058import android.provider.Settings;
Wei Wang67d84162015-04-26 17:04:29 -070059import android.provider.Settings.SettingNotFoundException;
Jeff Sharkey67609c72016-03-05 14:29:13 -070060import android.util.Slog;
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;
Marie Janssen59804562016-12-28 14:13:21 -080065import java.util.concurrent.locks.ReentrantReadWriteLock;
Benjamin Franze8b98922014-11-12 15:57:54 +000066import java.util.HashMap;
Marie Janssen59804562016-12-28 14:13:21 -080067import java.util.LinkedList;
Benjamin Franze8b98922014-11-12 15:57:54 +000068import java.util.Map;
Miao Chou658bf2f2015-06-26 17:14:35 -070069
Marie Janssen59804562016-12-28 14:13:21 -080070
fredc0f420372012-04-12 00:02:00 -070071class BluetoothManagerService extends IBluetoothManager.Stub {
72 private static final String TAG = "BluetoothManagerService";
Pavlin Radoslavov41401112016-06-27 15:25:18 -070073 private static final boolean DBG = true;
fredc0f420372012-04-12 00:02:00 -070074
fredc0f420372012-04-12 00:02:00 -070075 private static final String BLUETOOTH_ADMIN_PERM = android.Manifest.permission.BLUETOOTH_ADMIN;
76 private static final String BLUETOOTH_PERM = android.Manifest.permission.BLUETOOTH;
fredc0f420372012-04-12 00:02:00 -070077 private static final String ACTION_SERVICE_STATE_CHANGED="com.android.bluetooth.btservice.action.STATE_CHANGED";
78 private static final String EXTRA_ACTION="action";
Zhihai Xud31c3222012-10-31 16:08:57 -070079 private static final String SECURE_SETTINGS_BLUETOOTH_ADDR_VALID="bluetooth_addr_valid";
fredc0f420372012-04-12 00:02:00 -070080 private static final String SECURE_SETTINGS_BLUETOOTH_ADDRESS="bluetooth_address";
81 private static final String SECURE_SETTINGS_BLUETOOTH_NAME="bluetooth_name";
fredc0f420372012-04-12 00:02:00 -070082 private static final int TIMEOUT_BIND_MS = 3000; //Maximum msec to wait for a bind
83 private static final int TIMEOUT_SAVE_MS = 500; //Maximum msec to wait for a save
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +053084 //Maximum msec to wait for service restart
85 private static final int SERVICE_RESTART_TIME_MS = 200;
Zhihai Xudd9d17d2013-01-08 17:05:58 -080086 //Maximum msec to wait for restart due to error
87 private static final int ERROR_RESTART_TIME_MS = 3000;
Zhihai Xu40874a02012-10-08 17:57:03 -070088 //Maximum msec to delay MESSAGE_USER_SWITCHED
89 private static final int USER_SWITCHED_TIME_MS = 200;
Benjamin Franze8b98922014-11-12 15:57:54 +000090 // Delay for the addProxy function in msec
91 private static final int ADD_PROXY_DELAY_MS = 100;
fredc0f420372012-04-12 00:02:00 -070092
93 private static final int MESSAGE_ENABLE = 1;
94 private static final int MESSAGE_DISABLE = 2;
fredc649fe492012-04-19 01:07:18 -070095 private static final int MESSAGE_REGISTER_ADAPTER = 20;
96 private static final int MESSAGE_UNREGISTER_ADAPTER = 21;
97 private static final int MESSAGE_REGISTER_STATE_CHANGE_CALLBACK = 30;
98 private static final int MESSAGE_UNREGISTER_STATE_CHANGE_CALLBACK = 31;
99 private static final int MESSAGE_BLUETOOTH_SERVICE_CONNECTED = 40;
100 private static final int MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED = 41;
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +0530101 private static final int MESSAGE_RESTART_BLUETOOTH_SERVICE = 42;
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -0700102 private static final int MESSAGE_BLUETOOTH_STATE_CHANGE = 60;
103 private static final int MESSAGE_TIMEOUT_BIND = 100;
104 private static final int MESSAGE_TIMEOUT_UNBIND = 101;
Ajay Panicker4bb48302016-03-31 14:14:27 -0700105 private static final int MESSAGE_GET_NAME_AND_ADDRESS = 200;
Zhihai Xu40874a02012-10-08 17:57:03 -0700106 private static final int MESSAGE_USER_SWITCHED = 300;
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -0700107 private static final int MESSAGE_USER_UNLOCKED = 301;
Benjamin Franze8b98922014-11-12 15:57:54 +0000108 private static final int MESSAGE_ADD_PROXY_DELAYED = 400;
109 private static final int MESSAGE_BIND_PROFILE_SERVICE = 401;
Marie Janssencb21ad72016-12-13 10:51:02 -0800110
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -0700111 private static final int MAX_SAVE_RETRIES = 3;
112 private static final int MAX_ERROR_RESTART_RETRIES = 6;
Zhihai Xudd9d17d2013-01-08 17:05:58 -0800113
Zhihai Xu401202b2012-12-03 11:36:21 -0800114 // Bluetooth persisted setting is off
115 private static final int BLUETOOTH_OFF=0;
116 // Bluetooth persisted setting is on
117 // and Airplane mode won't affect Bluetooth state at start up
118 private static final int BLUETOOTH_ON_BLUETOOTH=1;
119 // Bluetooth persisted setting is on
120 // but Airplane mode will affect Bluetooth state at start up
121 // and Airplane mode will have higher priority.
122 private static final int BLUETOOTH_ON_AIRPLANE=2;
fredc0f420372012-04-12 00:02:00 -0700123
Matthew Xieddf7e472013-03-01 18:41:02 -0800124 private static final int SERVICE_IBLUETOOTH = 1;
125 private static final int SERVICE_IBLUETOOTHGATT = 2;
126
fredc0f420372012-04-12 00:02:00 -0700127 private final Context mContext;
Matthew Xiecdce0b92012-07-12 19:06:15 -0700128
129 // Locks are not provided for mName and mAddress.
130 // They are accessed in handler or broadcast receiver, same thread context.
fredc0f420372012-04-12 00:02:00 -0700131 private String mAddress;
132 private String mName;
Matthew Xie6fde3092012-07-11 17:10:07 -0700133 private final ContentResolver mContentResolver;
134 private final RemoteCallbackList<IBluetoothManagerCallback> mCallbacks;
135 private final RemoteCallbackList<IBluetoothStateChangeCallback> mStateChangeCallbacks;
Marie Janssen9db28eb2016-01-12 16:05:15 -0800136 private IBinder mBluetoothBinder;
fredc649fe492012-04-19 01:07:18 -0700137 private IBluetooth mBluetooth;
Matthew Xieddf7e472013-03-01 18:41:02 -0800138 private IBluetoothGatt mBluetoothGatt;
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700139 private final ReentrantReadWriteLock mBluetoothLock =
140 new ReentrantReadWriteLock();
fredc649fe492012-04-19 01:07:18 -0700141 private boolean mBinding;
142 private boolean mUnbinding;
Marie Janssen59804562016-12-28 14:13:21 -0800143
Zhihai Xu401202b2012-12-03 11:36:21 -0800144 // used inside handler thread
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700145 private boolean mQuietEnable = false;
Marie Janssen59804562016-12-28 14:13:21 -0800146 private boolean mEnable;
147
148 /**
149 * Used for tracking apps that enabled / disabled Bluetooth.
150 */
151 private class ActiveLog {
152 private String mPackageName;
153 private boolean mEnable;
154 private long mTimestamp;
155
156 public ActiveLog(String packageName, boolean enable, long timestamp) {
157 mPackageName = packageName;
158 mEnable = enable;
159 mTimestamp = timestamp;
160 }
161
162 public long getTime() {
163 return mTimestamp;
164 }
165
166 public String toString() {
167 return android.text.format.DateFormat.format("MM-dd hh:mm:ss ", mTimestamp) +
168 (mEnable ? " Enabled " : " Disabled ") + " by " + mPackageName;
169 }
170
171 }
172
173 private LinkedList<ActiveLog> mActiveLogs;
174
175 // configuration from external IBinder call which is used to
Zhihai Xu401202b2012-12-03 11:36:21 -0800176 // synchronize with broadcast receiver.
177 private boolean mQuietEnableExternal;
Zhihai Xu401202b2012-12-03 11:36:21 -0800178 private boolean mEnableExternal;
Marie Janssen59804562016-12-28 14:13:21 -0800179
180 // Map of apps registered to keep BLE scanning on.
181 private Map<IBinder, ClientDeathRecipient> mBleApps = new ConcurrentHashMap<IBinder, ClientDeathRecipient>();
182
Zhihai Xu40874a02012-10-08 17:57:03 -0700183 private int mState;
Zhihai Xu40874a02012-10-08 17:57:03 -0700184 private final BluetoothHandler mHandler;
Zhihai Xudd9d17d2013-01-08 17:05:58 -0800185 private int mErrorRecoveryRetryCounter;
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200186 private final int mSystemUiUid;
fredc0f420372012-04-12 00:02:00 -0700187
Benjamin Franze8b98922014-11-12 15:57:54 +0000188 // Save a ProfileServiceConnections object for each of the bound
189 // bluetooth profile services
190 private final Map <Integer, ProfileServiceConnections> mProfileServices =
191 new HashMap <Integer, ProfileServiceConnections>();
192
Svetoslav Ganovb1e2da72016-06-29 17:31:44 -0700193 private final boolean mPermissionReviewRequired;
194
fredc649fe492012-04-19 01:07:18 -0700195 private void registerForAirplaneMode(IntentFilter filter) {
196 final ContentResolver resolver = mContext.getContentResolver();
Christopher Tatec09cdce2012-09-10 16:50:14 -0700197 final String airplaneModeRadios = Settings.Global.getString(resolver,
198 Settings.Global.AIRPLANE_MODE_RADIOS);
199 final String toggleableRadios = Settings.Global.getString(resolver,
200 Settings.Global.AIRPLANE_MODE_TOGGLEABLE_RADIOS);
fredc649fe492012-04-19 01:07:18 -0700201 boolean mIsAirplaneSensitive = airplaneModeRadios == null ? true :
Christopher Tatec09cdce2012-09-10 16:50:14 -0700202 airplaneModeRadios.contains(Settings.Global.RADIO_BLUETOOTH);
fredc649fe492012-04-19 01:07:18 -0700203 if (mIsAirplaneSensitive) {
204 filter.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED);
205 }
206 }
207
Marie Janssen59804562016-12-28 14:13:21 -0800208 private final IBluetoothCallback mBluetoothCallback = new IBluetoothCallback.Stub() {
fredcbf072a72012-05-09 16:52:50 -0700209 @Override
210 public void onBluetoothStateChange(int prevState, int newState) throws RemoteException {
211 Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_STATE_CHANGE,prevState,newState);
212 mHandler.sendMessage(msg);
213 }
214 };
215
Lenka Trochtova13a05192016-12-02 12:19:39 +0100216 private final UserRestrictionsListener mUserRestrictionsListener =
217 new UserRestrictionsListener() {
218 @Override
219 public void onUserRestrictionsChanged(int userId, Bundle newRestrictions,
220 Bundle prevRestrictions) {
221 final boolean bluetoothDisallowed =
222 newRestrictions.getBoolean(UserManager.DISALLOW_BLUETOOTH);
223 if ((mEnable || mEnableExternal) && bluetoothDisallowed) {
Ivan Podogov903d6412016-12-13 16:34:53 +0000224 try {
225 disable("android.os.UserManagerInternal", true);
226 } catch (RemoteException e) {
227 // Shouldn't happen: startConsentUiIfNeeded not called
228 // when from system.
229 }
Lenka Trochtova13a05192016-12-02 12:19:39 +0100230 }
231 }
232 };
233
fredcbf072a72012-05-09 16:52:50 -0700234 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
fredc0f420372012-04-12 00:02:00 -0700235 @Override
236 public void onReceive(Context context, Intent intent) {
237 String action = intent.getAction();
fredcbf072a72012-05-09 16:52:50 -0700238 if (BluetoothAdapter.ACTION_LOCAL_NAME_CHANGED.equals(action)) {
fredc0f420372012-04-12 00:02:00 -0700239 String newName = intent.getStringExtra(BluetoothAdapter.EXTRA_LOCAL_NAME);
Jeff Sharkey67609c72016-03-05 14:29:13 -0700240 if (DBG) Slog.d(TAG, "Bluetooth Adapter name changed to " + newName);
fredc0f420372012-04-12 00:02:00 -0700241 if (newName != null) {
242 storeNameAndAddress(newName, null);
243 }
fredc649fe492012-04-19 01:07:18 -0700244 } else if (Intent.ACTION_AIRPLANE_MODE_CHANGED.equals(action)) {
Zhihai Xu401202b2012-12-03 11:36:21 -0800245 synchronized(mReceiver) {
246 if (isBluetoothPersistedStateOn()) {
247 if (isAirplaneModeOn()) {
248 persistBluetoothSetting(BLUETOOTH_ON_AIRPLANE);
249 } else {
250 persistBluetoothSetting(BLUETOOTH_ON_BLUETOOTH);
251 }
252 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800253
254 int st = BluetoothAdapter.STATE_OFF;
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700255 try {
256 mBluetoothLock.readLock().lock();
257 if (mBluetooth != null) {
Nitin Arorad055adb2015-03-02 15:03:51 -0800258 st = mBluetooth.getState();
Nitin Arorad055adb2015-03-02 15:03:51 -0800259 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700260 } catch (RemoteException e) {
261 Slog.e(TAG, "Unable to call getState", e);
262 } finally {
263 mBluetoothLock.readLock().unlock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800264 }
Marie Janssenf2fc1582016-12-14 13:44:28 -0800265 Slog.d(TAG, "Airplane Mode change - current state: " +
266 BluetoothAdapter.nameForState(st));
Nitin Arorad055adb2015-03-02 15:03:51 -0800267
Zhihai Xu401202b2012-12-03 11:36:21 -0800268 if (isAirplaneModeOn()) {
Nitin Arorad055adb2015-03-02 15:03:51 -0800269 // Clear registered LE apps to force shut-off
Marie Janssen2977c3e2016-11-09 12:01:24 -0800270 clearBleApps();
Nitin Arorad055adb2015-03-02 15:03:51 -0800271 if (st == BluetoothAdapter.STATE_BLE_ON) {
272 //if state is BLE_ON make sure you trigger disableBLE part
273 try {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700274 mBluetoothLock.readLock().lock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800275 if (mBluetooth != null) {
276 mBluetooth.onBrEdrDown();
Marie Janssen6a383a72016-10-25 10:47:51 -0700277 mEnable = false;
Nitin Arorad055adb2015-03-02 15:03:51 -0800278 mEnableExternal = false;
279 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700280 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700281 Slog.e(TAG,"Unable to call onBrEdrDown", e);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700282 } finally {
Pavlin Radoslavov7ee53be2016-06-09 12:58:07 -0700283 mBluetoothLock.readLock().unlock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800284 }
285 } else if (st == BluetoothAdapter.STATE_ON){
286 // disable without persisting the setting
Jeff Sharkey67609c72016-03-05 14:29:13 -0700287 Slog.d(TAG, "Calling disable");
Marie Janssen59804562016-12-28 14:13:21 -0800288 sendDisableMsg("airplane mode");
Nitin Arorad055adb2015-03-02 15:03:51 -0800289 }
Zhihai Xu401202b2012-12-03 11:36:21 -0800290 } else if (mEnableExternal) {
291 // enable without persisting the setting
Jeff Sharkey67609c72016-03-05 14:29:13 -0700292 Slog.d(TAG, "Calling enable");
Marie Janssen59804562016-12-28 14:13:21 -0800293 sendEnableMsg(mQuietEnableExternal, "airplane mode");
Zhihai Xu401202b2012-12-03 11:36:21 -0800294 }
fredc649fe492012-04-19 01:07:18 -0700295 }
fredc0f420372012-04-12 00:02:00 -0700296 }
297 }
298 };
299
300 BluetoothManagerService(Context context) {
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700301 mHandler = new BluetoothHandler(IoThread.get().getLooper());
Zhihai Xu40874a02012-10-08 17:57:03 -0700302
fredc0f420372012-04-12 00:02:00 -0700303 mContext = context;
Svetoslav Ganovb1e2da72016-06-29 17:31:44 -0700304
305 mPermissionReviewRequired = Build.PERMISSIONS_REVIEW_REQUIRED
306 || context.getResources().getBoolean(
307 com.android.internal.R.bool.config_permissionReviewRequired);
308
Marie Janssen59804562016-12-28 14:13:21 -0800309 mActiveLogs = new LinkedList<ActiveLog>();
fredc0f420372012-04-12 00:02:00 -0700310 mBluetooth = null;
Marie Janssen9db28eb2016-01-12 16:05:15 -0800311 mBluetoothBinder = null;
Nitin Arorad055adb2015-03-02 15:03:51 -0800312 mBluetoothGatt = null;
fredc0f420372012-04-12 00:02:00 -0700313 mBinding = false;
314 mUnbinding = false;
Zhihai Xu40874a02012-10-08 17:57:03 -0700315 mEnable = false;
316 mState = BluetoothAdapter.STATE_OFF;
Zhihai Xu401202b2012-12-03 11:36:21 -0800317 mQuietEnableExternal = false;
318 mEnableExternal = false;
fredc0f420372012-04-12 00:02:00 -0700319 mAddress = null;
320 mName = null;
Zhihai Xudd9d17d2013-01-08 17:05:58 -0800321 mErrorRecoveryRetryCounter = 0;
fredc0f420372012-04-12 00:02:00 -0700322 mContentResolver = context.getContentResolver();
Wei Wange4a744b2015-06-11 17:50:29 -0700323 // Observe BLE scan only mode settings change.
324 registerForBleScanModeChange();
fredcd6883532012-04-25 17:46:13 -0700325 mCallbacks = new RemoteCallbackList<IBluetoothManagerCallback>();
326 mStateChangeCallbacks = new RemoteCallbackList<IBluetoothStateChangeCallback>();
Miao Chou658bf2f2015-06-26 17:14:35 -0700327 IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_LOCAL_NAME_CHANGED);
Matthew Xie6fde3092012-07-11 17:10:07 -0700328 registerForAirplaneMode(filter);
Dianne Hackbornd83a0962014-05-02 16:28:33 -0700329 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
Matthew Xie6fde3092012-07-11 17:10:07 -0700330 mContext.registerReceiver(mReceiver, filter);
fredc0f420372012-04-12 00:02:00 -0700331 loadStoredNameAndAddress();
Zhihai Xu401202b2012-12-03 11:36:21 -0800332 if (isBluetoothPersistedStateOn()) {
Marie Janssen9fa24912016-10-18 10:04:24 -0700333 if (DBG) Slog.d(TAG, "Startup: Bluetooth persisted state is ON.");
Zhihai Xu401202b2012-12-03 11:36:21 -0800334 mEnableExternal = true;
fredc0f420372012-04-12 00:02:00 -0700335 }
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200336
Marie Janssen59804562016-12-28 14:13:21 -0800337 int systemUiUid = -1;
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200338 try {
Marie Janssen59804562016-12-28 14:13:21 -0800339 systemUiUid = mContext.getPackageManager().getPackageUidAsUser("com.android.systemui",
Jeff Sharkeyc5967e92016-01-07 18:50:29 -0700340 PackageManager.MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM);
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200341 } catch (PackageManager.NameNotFoundException e) {
Joe LaPennaacddf2b2015-09-04 12:52:42 -0700342 // Some platforms, such as wearables do not have a system ui.
Jeff Sharkey67609c72016-03-05 14:29:13 -0700343 Slog.w(TAG, "Unable to resolve SystemUI's UID.", e);
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200344 }
Marie Janssen59804562016-12-28 14:13:21 -0800345 mSystemUiUid = systemUiUid;
fredc0f420372012-04-12 00:02:00 -0700346 }
347
fredc649fe492012-04-19 01:07:18 -0700348 /**
349 * Returns true if airplane mode is currently on
350 */
351 private final boolean isAirplaneModeOn() {
Christopher Tatec09cdce2012-09-10 16:50:14 -0700352 return Settings.Global.getInt(mContext.getContentResolver(),
353 Settings.Global.AIRPLANE_MODE_ON, 0) == 1;
fredc649fe492012-04-19 01:07:18 -0700354 }
355
356 /**
357 * Returns true if the Bluetooth saved state is "on"
358 */
359 private final boolean isBluetoothPersistedStateOn() {
Marie Janssen9fa24912016-10-18 10:04:24 -0700360 int state = Settings.Global.getInt(mContentResolver,
361 Settings.Global.BLUETOOTH_ON, -1);
362 if (DBG) Slog.d(TAG, "Bluetooth persisted state: " + state);
363 return state != BLUETOOTH_OFF;
Zhihai Xu401202b2012-12-03 11:36:21 -0800364 }
365
366 /**
367 * Returns true if the Bluetooth saved state is BLUETOOTH_ON_BLUETOOTH
368 */
369 private final boolean isBluetoothPersistedStateOnBluetooth() {
370 return Settings.Global.getInt(mContentResolver,
Andre Eisenbach8c184312016-09-06 18:03:10 -0700371 Settings.Global.BLUETOOTH_ON, BLUETOOTH_ON_BLUETOOTH) == BLUETOOTH_ON_BLUETOOTH;
fredc649fe492012-04-19 01:07:18 -0700372 }
373
374 /**
375 * Save the Bluetooth on/off state
fredc649fe492012-04-19 01:07:18 -0700376 */
Zhihai Xu401202b2012-12-03 11:36:21 -0800377 private void persistBluetoothSetting(int value) {
Marie Janssen9fa24912016-10-18 10:04:24 -0700378 if (DBG) Slog.d(TAG, "Persisting Bluetooth Setting: " + value);
Marie Janssenfa630682016-12-15 13:51:30 -0800379 // waive WRITE_SECURE_SETTINGS permission check
380 long callingIdentity = Binder.clearCallingIdentity();
Jeff Brownbf6f6f92012-09-25 15:03:20 -0700381 Settings.Global.putInt(mContext.getContentResolver(),
382 Settings.Global.BLUETOOTH_ON,
Zhihai Xu401202b2012-12-03 11:36:21 -0800383 value);
Marie Janssenfa630682016-12-15 13:51:30 -0800384 Binder.restoreCallingIdentity(callingIdentity);
fredc649fe492012-04-19 01:07:18 -0700385 }
386
387 /**
388 * Returns true if the Bluetooth Adapter's name and address is
389 * locally cached
390 * @return
391 */
fredc0f420372012-04-12 00:02:00 -0700392 private boolean isNameAndAddressSet() {
393 return mName !=null && mAddress!= null && mName.length()>0 && mAddress.length()>0;
394 }
395
fredc649fe492012-04-19 01:07:18 -0700396 /**
397 * Retrieve the Bluetooth Adapter's name and address and save it in
398 * in the local cache
399 */
fredc0f420372012-04-12 00:02:00 -0700400 private void loadStoredNameAndAddress() {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700401 if (DBG) Slog.d(TAG, "Loading stored name and address");
Zhihai Xud31c3222012-10-31 16:08:57 -0700402 if (mContext.getResources().getBoolean
403 (com.android.internal.R.bool.config_bluetooth_address_validation) &&
404 Settings.Secure.getInt(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDR_VALID, 0) == 0) {
405 // if the valid flag is not set, don't load the address and name
Jeff Sharkey67609c72016-03-05 14:29:13 -0700406 if (DBG) Slog.d(TAG, "invalid bluetooth name and address stored");
Zhihai Xud31c3222012-10-31 16:08:57 -0700407 return;
408 }
fredc0f420372012-04-12 00:02:00 -0700409 mName = Settings.Secure.getString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_NAME);
410 mAddress = Settings.Secure.getString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDRESS);
Jeff Sharkey67609c72016-03-05 14:29:13 -0700411 if (DBG) Slog.d(TAG, "Stored bluetooth Name=" + mName + ",Address=" + mAddress);
fredc0f420372012-04-12 00:02:00 -0700412 }
413
fredc649fe492012-04-19 01:07:18 -0700414 /**
415 * Save the Bluetooth name and address in the persistent store.
416 * Only non-null values will be saved.
417 * @param name
418 * @param address
419 */
fredc0f420372012-04-12 00:02:00 -0700420 private void storeNameAndAddress(String name, String address) {
421 if (name != null) {
422 Settings.Secure.putString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_NAME, name);
fredc0f420372012-04-12 00:02:00 -0700423 mName = name;
Jeff Sharkey67609c72016-03-05 14:29:13 -0700424 if (DBG) Slog.d(TAG,"Stored Bluetooth name: " +
fredc649fe492012-04-19 01:07:18 -0700425 Settings.Secure.getString(mContentResolver,SECURE_SETTINGS_BLUETOOTH_NAME));
fredc0f420372012-04-12 00:02:00 -0700426 }
427
428 if (address != null) {
429 Settings.Secure.putString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDRESS, address);
fredc0f420372012-04-12 00:02:00 -0700430 mAddress=address;
Jeff Sharkey67609c72016-03-05 14:29:13 -0700431 if (DBG) Slog.d(TAG,"Stored Bluetoothaddress: " +
fredc649fe492012-04-19 01:07:18 -0700432 Settings.Secure.getString(mContentResolver,SECURE_SETTINGS_BLUETOOTH_ADDRESS));
fredc0f420372012-04-12 00:02:00 -0700433 }
Zhihai Xud31c3222012-10-31 16:08:57 -0700434
435 if ((name != null) && (address != null)) {
436 Settings.Secure.putInt(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDR_VALID, 1);
437 }
fredc0f420372012-04-12 00:02:00 -0700438 }
439
440 public IBluetooth registerAdapter(IBluetoothManagerCallback callback){
Natalie Silvanovich55db6462014-05-01 16:12:23 -0700441 if (callback == null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700442 Slog.w(TAG, "Callback is null in registerAdapter");
Natalie Silvanovich55db6462014-05-01 16:12:23 -0700443 return null;
444 }
fredc0f420372012-04-12 00:02:00 -0700445 Message msg = mHandler.obtainMessage(MESSAGE_REGISTER_ADAPTER);
446 msg.obj = callback;
447 mHandler.sendMessage(msg);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700448
449 return mBluetooth;
fredc0f420372012-04-12 00:02:00 -0700450 }
451
452 public void unregisterAdapter(IBluetoothManagerCallback callback) {
Natalie Silvanovich55db6462014-05-01 16:12:23 -0700453 if (callback == null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700454 Slog.w(TAG, "Callback is null in unregisterAdapter");
Natalie Silvanovich55db6462014-05-01 16:12:23 -0700455 return;
456 }
fredc0f420372012-04-12 00:02:00 -0700457 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
458 "Need BLUETOOTH permission");
459 Message msg = mHandler.obtainMessage(MESSAGE_UNREGISTER_ADAPTER);
460 msg.obj = callback;
461 mHandler.sendMessage(msg);
462 }
463
464 public void registerStateChangeCallback(IBluetoothStateChangeCallback callback) {
465 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
466 "Need BLUETOOTH permission");
Marie Janssencb21ad72016-12-13 10:51:02 -0800467 if (callback == null) {
468 Slog.w(TAG, "registerStateChangeCallback: Callback is null!");
469 return;
470 }
fredc0f420372012-04-12 00:02:00 -0700471 Message msg = mHandler.obtainMessage(MESSAGE_REGISTER_STATE_CHANGE_CALLBACK);
472 msg.obj = callback;
473 mHandler.sendMessage(msg);
474 }
475
476 public void unregisterStateChangeCallback(IBluetoothStateChangeCallback callback) {
477 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
478 "Need BLUETOOTH permission");
Marie Janssencb21ad72016-12-13 10:51:02 -0800479 if (callback == null) {
480 Slog.w(TAG, "unregisterStateChangeCallback: Callback is null!");
481 return;
482 }
fredc0f420372012-04-12 00:02:00 -0700483 Message msg = mHandler.obtainMessage(MESSAGE_UNREGISTER_STATE_CHANGE_CALLBACK);
484 msg.obj = callback;
485 mHandler.sendMessage(msg);
486 }
487
488 public boolean isEnabled() {
Zhihai Xu6eb76522012-11-29 15:41:04 -0800489 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
490 (!checkIfCallerIsForegroundUser())) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700491 Slog.w(TAG,"isEnabled(): not allowed for non-active and non system user");
Zhihai Xu40874a02012-10-08 17:57:03 -0700492 return false;
493 }
494
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700495 try {
496 mBluetoothLock.readLock().lock();
497 if (mBluetooth != null) return mBluetooth.isEnabled();
498 } catch (RemoteException e) {
499 Slog.e(TAG, "isEnabled()", e);
500 } finally {
501 mBluetoothLock.readLock().unlock();
fredc0f420372012-04-12 00:02:00 -0700502 }
503 return false;
504 }
505
Christine Hallstrom995c90a2016-05-25 15:49:08 -0700506 public int getState() {
507 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
508 (!checkIfCallerIsForegroundUser())) {
Marie Janssencb21ad72016-12-13 10:51:02 -0800509 Slog.w(TAG, "getState(): report OFF for non-active and non system user");
Christine Hallstrom995c90a2016-05-25 15:49:08 -0700510 return BluetoothAdapter.STATE_OFF;
511 }
512
513 try {
514 mBluetoothLock.readLock().lock();
515 if (mBluetooth != null) return mBluetooth.getState();
516 } catch (RemoteException e) {
517 Slog.e(TAG, "getState()", e);
518 } finally {
519 mBluetoothLock.readLock().unlock();
520 }
521 return BluetoothAdapter.STATE_OFF;
522 }
523
Nitin Arorad055adb2015-03-02 15:03:51 -0800524 class ClientDeathRecipient implements IBinder.DeathRecipient {
Marie Janssen59804562016-12-28 14:13:21 -0800525 private String mPackageName;
526
527 public ClientDeathRecipient(String packageName) {
528 mPackageName = packageName;
529 }
530
Nitin Arorad055adb2015-03-02 15:03:51 -0800531 public void binderDied() {
Marie Janssen59804562016-12-28 14:13:21 -0800532 if (DBG) Slog.d(TAG, "Binder is dead - unregister " + mPackageName);
Marie Janssen2977c3e2016-11-09 12:01:24 -0800533 if (isBleAppPresent()) {
534 // Nothing to do, another app is here.
535 return;
536 }
537 if (DBG) Slog.d(TAG, "Disabling LE only mode after application crash");
538 try {
539 mBluetoothLock.readLock().lock();
540 if (mBluetooth != null &&
541 mBluetooth.getState() == BluetoothAdapter.STATE_BLE_ON) {
542 mEnable = false;
543 mBluetooth.onBrEdrDown();
Nitin Arorad055adb2015-03-02 15:03:51 -0800544 }
Marie Janssen2977c3e2016-11-09 12:01:24 -0800545 } catch (RemoteException e) {
546 Slog.e(TAG,"Unable to call onBrEdrDown", e);
547 } finally {
548 mBluetoothLock.readLock().unlock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800549 }
550 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800551
Marie Janssen59804562016-12-28 14:13:21 -0800552 public String getPackageName() {
553 return mPackageName;
554 }
555 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800556
Wei Wang67d84162015-04-26 17:04:29 -0700557 @Override
558 public boolean isBleScanAlwaysAvailable() {
Marie Janssen6a383a72016-10-25 10:47:51 -0700559 if (isAirplaneModeOn() && !mEnable) {
560 return false;
561 }
Wei Wang67d84162015-04-26 17:04:29 -0700562 try {
563 return (Settings.Global.getInt(mContentResolver,
564 Settings.Global.BLE_SCAN_ALWAYS_AVAILABLE)) != 0;
565 } catch (SettingNotFoundException e) {
566 }
567 return false;
568 }
569
Wei Wange4a744b2015-06-11 17:50:29 -0700570 // Monitor change of BLE scan only mode settings.
571 private void registerForBleScanModeChange() {
572 ContentObserver contentObserver = new ContentObserver(null) {
573 @Override
574 public void onChange(boolean selfChange) {
Marie Janssen2977c3e2016-11-09 12:01:24 -0800575 if (isBleScanAlwaysAvailable()) {
576 // Nothing to do
577 return;
578 }
579 // BLE scan is not available.
580 disableBleScanMode();
581 clearBleApps();
582 try {
583 mBluetoothLock.readLock().lock();
584 if (mBluetooth != null) mBluetooth.onBrEdrDown();
585 } catch (RemoteException e) {
586 Slog.e(TAG, "error when disabling bluetooth", e);
587 } finally {
588 mBluetoothLock.readLock().unlock();
Wei Wange4a744b2015-06-11 17:50:29 -0700589 }
590 }
591 };
592
593 mContentResolver.registerContentObserver(
594 Settings.Global.getUriFor(Settings.Global.BLE_SCAN_ALWAYS_AVAILABLE),
595 false, contentObserver);
596 }
597
598 // Disable ble scan only mode.
599 private void disableBleScanMode() {
600 try {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700601 mBluetoothLock.writeLock().lock();
Wei Wange4a744b2015-06-11 17:50:29 -0700602 if (mBluetooth != null && (mBluetooth.getState() != BluetoothAdapter.STATE_ON)) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700603 if (DBG) Slog.d(TAG, "Reseting the mEnable flag for clean disable");
Wei Wange4a744b2015-06-11 17:50:29 -0700604 mEnable = false;
605 }
606 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700607 Slog.e(TAG, "getState()", e);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700608 } finally {
609 mBluetoothLock.writeLock().unlock();
Wei Wange4a744b2015-06-11 17:50:29 -0700610 }
611 }
612
Marie Janssen59804562016-12-28 14:13:21 -0800613 public int updateBleAppCount(IBinder token, boolean enable, String packageName) {
614 ClientDeathRecipient r = mBleApps.get(token);
615 if (r == null && enable) {
616 ClientDeathRecipient deathRec = new ClientDeathRecipient(packageName);
617 try {
618 token.linkToDeath(deathRec, 0);
619 } catch (RemoteException ex) {
620 throw new IllegalArgumentException("BLE app (" + packageName + ") already dead!");
Nitin Arorad055adb2015-03-02 15:03:51 -0800621 }
Marie Janssen59804562016-12-28 14:13:21 -0800622 mBleApps.put(token, deathRec);
623 if (DBG) Slog.d(TAG, "Registered for death of " + packageName);
624 } else if (!enable && r != null) {
625 // Unregister death recipient as the app goes away.
626 token.unlinkToDeath(r, 0);
627 mBleApps.remove(token);
628 if (DBG) Slog.d(TAG, "Unregistered for death of " + packageName);
Nitin Arorad055adb2015-03-02 15:03:51 -0800629 }
Marie Janssen2977c3e2016-11-09 12:01:24 -0800630 int appCount = mBleApps.size();
631 if (DBG) Slog.d(TAG, appCount + " registered Ble Apps");
632 if (appCount == 0 && mEnable) {
Wei Wange4a744b2015-06-11 17:50:29 -0700633 disableBleScanMode();
Nitin Arorad055adb2015-03-02 15:03:51 -0800634 }
Marie Janssen2977c3e2016-11-09 12:01:24 -0800635 return appCount;
Nitin Arorad055adb2015-03-02 15:03:51 -0800636 }
637
Wei Wange4a744b2015-06-11 17:50:29 -0700638 // Clear all apps using BLE scan only mode.
639 private void clearBleApps() {
Marie Janssen2977c3e2016-11-09 12:01:24 -0800640 mBleApps.clear();
Wei Wange4a744b2015-06-11 17:50:29 -0700641 }
642
Marie Janssen59804562016-12-28 14:13:21 -0800643 /** @hide */
Nitin Arorad055adb2015-03-02 15:03:51 -0800644 public boolean isBleAppPresent() {
Marie Janssen2977c3e2016-11-09 12:01:24 -0800645 if (DBG) Slog.d(TAG, "isBleAppPresent() count: " + mBleApps.size());
646 return mBleApps.size() > 0;
Nitin Arorad055adb2015-03-02 15:03:51 -0800647 }
648
649 /**
Marie Janssenfa630682016-12-15 13:51:30 -0800650 * Action taken when GattService is turned on
Nitin Arorad055adb2015-03-02 15:03:51 -0800651 */
652 private void onBluetoothGattServiceUp() {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700653 if (DBG) Slog.d(TAG,"BluetoothGatt Service is Up");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700654 try {
655 mBluetoothLock.readLock().lock();
Marie Janssenfa630682016-12-15 13:51:30 -0800656 if (mBluetooth == null) {
657 if (DBG) Slog.w(TAG, "onBluetoothServiceUp: mBluetooth is null!");
658 return;
659 }
660 int st = mBluetooth.getState();
661 if (st != BluetoothAdapter.STATE_BLE_ON) {
662 if (DBG) Slog.v(TAG, "onBluetoothServiceUp: state isn't BLE_ON: " +
663 BluetoothAdapter.nameForState(st));
664 return;
665 }
666 if (isBluetoothPersistedStateOnBluetooth() || !isBleAppPresent()) {
667 // This triggers transition to STATE_ON
Nitin Arorad055adb2015-03-02 15:03:51 -0800668 mBluetooth.onLeServiceUp();
Nitin Arorad055adb2015-03-02 15:03:51 -0800669 persistBluetoothSetting(BLUETOOTH_ON_BLUETOOTH);
Nitin Arorad055adb2015-03-02 15:03:51 -0800670 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700671 } catch (RemoteException e) {
672 Slog.e(TAG,"Unable to call onServiceUp", e);
673 } finally {
674 mBluetoothLock.readLock().unlock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800675 }
676 }
677
678 /**
679 * Inform BluetoothAdapter instances that BREDR part is down
680 * and turn off all service and stack if no LE app needs it
681 */
682 private void sendBrEdrDownCallback() {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700683 if (DBG) Slog.d(TAG,"Calling sendBrEdrDownCallback callbacks");
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700684
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700685 if (mBluetooth == null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700686 Slog.w(TAG, "Bluetooth handle is null");
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700687 return;
688 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800689
690 if (isBleAppPresent() == false) {
691 try {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700692 mBluetoothLock.readLock().lock();
693 if (mBluetooth != null) mBluetooth.onBrEdrDown();
694 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700695 Slog.e(TAG, "Call to onBrEdrDown() failed.", e);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700696 } finally {
697 mBluetoothLock.readLock().unlock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800698 }
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700699 } else {
700 // Need to stay at BLE ON. Disconnect all Gatt connections
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700701 try {
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700702 mBluetoothGatt.unregAll();
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700703 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700704 Slog.e(TAG, "Unable to disconnect all apps.", e);
Nitin Arorad055adb2015-03-02 15:03:51 -0800705 }
706 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800707 }
708
Marie Janssen59804562016-12-28 14:13:21 -0800709 public boolean enableNoAutoConnect(String packageName)
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700710 {
Lenka Trochtova13a05192016-12-02 12:19:39 +0100711 if (isBluetoothDisallowed()) {
712 if (DBG) {
713 Slog.d(TAG, "enableNoAutoConnect(): not enabling - bluetooth disallowed");
714 }
715 return false;
716 }
717
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700718 mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
719 "Need BLUETOOTH ADMIN permission");
Zhihai Xu40874a02012-10-08 17:57:03 -0700720
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700721 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700722 Slog.d(TAG,"enableNoAutoConnect(): mBluetooth =" + mBluetooth +
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700723 " mBinding = " + mBinding);
724 }
Martijn Coenen8385c5a2012-11-29 10:14:16 -0800725 int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
726
727 if (callingAppId != Process.NFC_UID) {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700728 throw new SecurityException("no permission to enable Bluetooth quietly");
729 }
Martijn Coenen8385c5a2012-11-29 10:14:16 -0800730
Zhihai Xu401202b2012-12-03 11:36:21 -0800731 synchronized(mReceiver) {
732 mQuietEnableExternal = true;
733 mEnableExternal = true;
Marie Janssen59804562016-12-28 14:13:21 -0800734 sendEnableMsg(true, packageName);
Zhihai Xu401202b2012-12-03 11:36:21 -0800735 }
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700736 return true;
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700737 }
Ajay Panicker4bb48302016-03-31 14:14:27 -0700738
Svetoslav Ganovb1e2da72016-06-29 17:31:44 -0700739 public boolean enable(String packageName) throws RemoteException {
Lenka Trochtova13a05192016-12-02 12:19:39 +0100740 if (isBluetoothDisallowed()) {
741 if (DBG) {
742 Slog.d(TAG,"enable(): not enabling - bluetooth disallowed");
743 }
744 return false;
745 }
746
Svetoslav Ganovb1e2da72016-06-29 17:31:44 -0700747 final int callingUid = Binder.getCallingUid();
748 final boolean callerSystem = UserHandle.getAppId(callingUid) == Process.SYSTEM_UID;
749
750 if (!callerSystem) {
751 if (!checkIfCallerIsForegroundUser()) {
752 Slog.w(TAG, "enable(): not allowed for non-active and non system user");
753 return false;
754 }
755
756 mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
757 "Need BLUETOOTH ADMIN permission");
758
Shijian Li5e7fc7c2017-01-11 17:32:12 +0000759 if (!isEnabled() && mPermissionReviewRequired
760 && startConsentUiIfNeeded(packageName, callingUid,
761 BluetoothAdapter.ACTION_REQUEST_ENABLE)) {
Svetoslav Ganovb1e2da72016-06-29 17:31:44 -0700762 return false;
763 }
fredcf2458862012-04-16 15:18:27 -0700764 }
765
Zhihai Xu401202b2012-12-03 11:36:21 -0800766 if (DBG) {
Marie Janssen59804562016-12-28 14:13:21 -0800767 Slog.d(TAG,"enable(" + packageName + "): mBluetooth =" + mBluetooth +
Marie Janssencb21ad72016-12-13 10:51:02 -0800768 " mBinding = " + mBinding + " mState = " +
769 BluetoothAdapter.nameForState(mState));
Sanket Agarwal090bf552016-04-21 14:10:55 -0700770 }
Zhihai Xu401202b2012-12-03 11:36:21 -0800771
772 synchronized(mReceiver) {
773 mQuietEnableExternal = false;
774 mEnableExternal = true;
775 // waive WRITE_SECURE_SETTINGS permission check
Marie Janssen59804562016-12-28 14:13:21 -0800776 sendEnableMsg(false, packageName);
Zhihai Xu401202b2012-12-03 11:36:21 -0800777 }
Jeff Sharkey67609c72016-03-05 14:29:13 -0700778 if (DBG) Slog.d(TAG, "enable returning");
Zhihai Xu401202b2012-12-03 11:36:21 -0800779 return true;
fredc0f420372012-04-12 00:02:00 -0700780 }
781
Svetoslav Ganovb1e2da72016-06-29 17:31:44 -0700782 public boolean disable(String packageName, boolean persist) throws RemoteException {
783 final int callingUid = Binder.getCallingUid();
784 final boolean callerSystem = UserHandle.getAppId(callingUid) == Process.SYSTEM_UID;
Zhihai Xu40874a02012-10-08 17:57:03 -0700785
Svetoslav Ganovb1e2da72016-06-29 17:31:44 -0700786 if (!callerSystem) {
787 if (!checkIfCallerIsForegroundUser()) {
788 Slog.w(TAG, "disable(): not allowed for non-active and non system user");
789 return false;
790 }
791
792 mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
793 "Need BLUETOOTH ADMIN permission");
794
Shijian Li5e7fc7c2017-01-11 17:32:12 +0000795 if (isEnabled() && mPermissionReviewRequired
796 && startConsentUiIfNeeded(packageName, callingUid,
797 BluetoothAdapter.ACTION_REQUEST_DISABLE)) {
Svetoslav Ganovb1e2da72016-06-29 17:31:44 -0700798 return false;
799 }
Zhihai Xu40874a02012-10-08 17:57:03 -0700800 }
801
fredcf2458862012-04-16 15:18:27 -0700802 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700803 Slog.d(TAG,"disable(): mBluetooth = " + mBluetooth +
Matthew Xiecdce0b92012-07-12 19:06:15 -0700804 " mBinding = " + mBinding);
805 }
fredcf2458862012-04-16 15:18:27 -0700806
Zhihai Xu401202b2012-12-03 11:36:21 -0800807 synchronized(mReceiver) {
808 if (persist) {
Zhihai Xu401202b2012-12-03 11:36:21 -0800809 persistBluetoothSetting(BLUETOOTH_OFF);
Zhihai Xu401202b2012-12-03 11:36:21 -0800810 }
811 mEnableExternal = false;
Marie Janssen59804562016-12-28 14:13:21 -0800812 sendDisableMsg(packageName);
Zhihai Xu401202b2012-12-03 11:36:21 -0800813 }
fredc0f420372012-04-12 00:02:00 -0700814 return true;
815 }
816
Shijian Li5e7fc7c2017-01-11 17:32:12 +0000817 private boolean startConsentUiIfNeeded(String packageName,
818 int callingUid, String intentAction) throws RemoteException {
Svetoslav Ganovb1e2da72016-06-29 17:31:44 -0700819 try {
820 // Validate the package only if we are going to use it
821 ApplicationInfo applicationInfo = mContext.getPackageManager()
822 .getApplicationInfoAsUser(packageName,
823 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
824 UserHandle.getUserId(callingUid));
825 if (applicationInfo.uid != callingUid) {
826 throw new SecurityException("Package " + callingUid
827 + " not in uid " + callingUid);
828 }
829
Ivan Podogovd2d32b12016-12-05 16:46:52 +0000830 Intent intent = new Intent(intentAction);
Shijian Li5e7fc7c2017-01-11 17:32:12 +0000831 intent.putExtra(Intent.EXTRA_PACKAGE_NAME, packageName);
832 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
833 | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
834 try {
835 mContext.startActivity(intent);
836 } catch (ActivityNotFoundException e) {
837 // Shouldn't happen
838 Slog.e(TAG, "Intent to handle action " + intentAction + " missing");
839 return false;
840 }
841 return true;
Svetoslav Ganovb1e2da72016-06-29 17:31:44 -0700842 } catch (PackageManager.NameNotFoundException e) {
843 throw new RemoteException(e.getMessage());
844 }
Svetoslav Ganovb1e2da72016-06-29 17:31:44 -0700845 }
846
fredc649fe492012-04-19 01:07:18 -0700847 public void unbindAndFinish() {
fredcf2458862012-04-16 15:18:27 -0700848 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700849 Slog.d(TAG,"unbindAndFinish(): " + mBluetooth +
Marie Janssencb21ad72016-12-13 10:51:02 -0800850 " mBinding = " + mBinding + " mUnbinding = " + mUnbinding);
fredcf2458862012-04-16 15:18:27 -0700851 }
852
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700853 try {
854 mBluetoothLock.writeLock().lock();
fredc0f420372012-04-12 00:02:00 -0700855 if (mUnbinding) return;
856 mUnbinding = true;
Pavlin Radoslavove47ec142016-06-01 22:25:18 -0700857 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
Pavlin Radoslavovc7dda102016-09-21 17:28:11 -0700858 mHandler.removeMessages(MESSAGE_BIND_PROFILE_SERVICE);
Zhihai Xu40874a02012-10-08 17:57:03 -0700859 if (mBluetooth != null) {
Andre Eisenbach305fdab2015-11-11 21:43:26 -0800860 //Unregister callback object
861 try {
862 mBluetooth.unregisterCallback(mBluetoothCallback);
863 } catch (RemoteException re) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700864 Slog.e(TAG, "Unable to unregister BluetoothCallback",re);
fredcbf072a72012-05-09 16:52:50 -0700865 }
Marie Janssen9db28eb2016-01-12 16:05:15 -0800866 mBluetoothBinder = null;
fredcd6883532012-04-25 17:46:13 -0700867 mBluetooth = null;
fredc0f420372012-04-12 00:02:00 -0700868 mContext.unbindService(mConnection);
fredcd6883532012-04-25 17:46:13 -0700869 mUnbinding = false;
Zhihai Xu40874a02012-10-08 17:57:03 -0700870 mBinding = false;
fredcf2458862012-04-16 15:18:27 -0700871 } else {
Marie Janssencb21ad72016-12-13 10:51:02 -0800872 mUnbinding = false;
fredc0f420372012-04-12 00:02:00 -0700873 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800874 mBluetoothGatt = null;
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700875 } finally {
876 mBluetoothLock.writeLock().unlock();
fredc0f420372012-04-12 00:02:00 -0700877 }
878 }
879
Matthew Xieddf7e472013-03-01 18:41:02 -0800880 public IBluetoothGatt getBluetoothGatt() {
881 // sync protection
882 return mBluetoothGatt;
883 }
884
Benjamin Franze8b98922014-11-12 15:57:54 +0000885 @Override
886 public boolean bindBluetoothProfileService(int bluetoothProfile,
887 IBluetoothProfileServiceConnection proxy) {
888 if (!mEnable) {
889 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700890 Slog.d(TAG, "Trying to bind to profile: " + bluetoothProfile +
Benjamin Franze8b98922014-11-12 15:57:54 +0000891 ", while Bluetooth was disabled");
892 }
893 return false;
894 }
895 synchronized (mProfileServices) {
896 ProfileServiceConnections psc = mProfileServices.get(new Integer(bluetoothProfile));
897 if (psc == null) {
898 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700899 Slog.d(TAG, "Creating new ProfileServiceConnections object for"
Benjamin Franze8b98922014-11-12 15:57:54 +0000900 + " profile: " + bluetoothProfile);
901 }
Benjamin Franz5b614592014-12-09 18:58:45 +0000902
903 if (bluetoothProfile != BluetoothProfile.HEADSET) return false;
904
905 Intent intent = new Intent(IBluetoothHeadset.class.getName());
Benjamin Franze8b98922014-11-12 15:57:54 +0000906 psc = new ProfileServiceConnections(intent);
Benjamin Franz5b614592014-12-09 18:58:45 +0000907 if (!psc.bindService()) return false;
908
Benjamin Franze8b98922014-11-12 15:57:54 +0000909 mProfileServices.put(new Integer(bluetoothProfile), psc);
Benjamin Franze8b98922014-11-12 15:57:54 +0000910 }
911 }
912
913 // Introducing a delay to give the client app time to prepare
914 Message addProxyMsg = mHandler.obtainMessage(MESSAGE_ADD_PROXY_DELAYED);
915 addProxyMsg.arg1 = bluetoothProfile;
916 addProxyMsg.obj = proxy;
917 mHandler.sendMessageDelayed(addProxyMsg, ADD_PROXY_DELAY_MS);
918 return true;
919 }
920
921 @Override
922 public void unbindBluetoothProfileService(int bluetoothProfile,
923 IBluetoothProfileServiceConnection proxy) {
924 synchronized (mProfileServices) {
925 ProfileServiceConnections psc = mProfileServices.get(new Integer(bluetoothProfile));
926 if (psc == null) {
927 return;
928 }
929 psc.removeProxy(proxy);
930 }
931 }
932
933 private void unbindAllBluetoothProfileServices() {
934 synchronized (mProfileServices) {
935 for (Integer i : mProfileServices.keySet()) {
936 ProfileServiceConnections psc = mProfileServices.get(i);
Benjamin Franz5b614592014-12-09 18:58:45 +0000937 try {
938 mContext.unbindService(psc);
939 } catch (IllegalArgumentException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700940 Slog.e(TAG, "Unable to unbind service with intent: " + psc.mIntent, e);
Benjamin Franz5b614592014-12-09 18:58:45 +0000941 }
Benjamin Franze8b98922014-11-12 15:57:54 +0000942 psc.removeAllProxies();
943 }
944 mProfileServices.clear();
945 }
946 }
947
948 /**
Miao Chou658bf2f2015-06-26 17:14:35 -0700949 * Send enable message and set adapter name and address. Called when the boot phase becomes
950 * PHASE_SYSTEM_SERVICES_READY.
951 */
952 public void handleOnBootPhase() {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700953 if (DBG) Slog.d(TAG, "Bluetooth boot completed");
Lenka Trochtova13a05192016-12-02 12:19:39 +0100954 UserManagerInternal userManagerInternal =
955 LocalServices.getService(UserManagerInternal.class);
956 userManagerInternal.addUserRestrictionsListener(mUserRestrictionsListener);
Andre Eisenbach8b4838e2017-01-12 15:56:39 +0000957 if (isBluetoothDisallowed()) {
Lenka Trochtova13a05192016-12-02 12:19:39 +0100958 return;
959 }
Miao Chou658bf2f2015-06-26 17:14:35 -0700960 if (mEnableExternal && isBluetoothPersistedStateOnBluetooth()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700961 if (DBG) Slog.d(TAG, "Auto-enabling Bluetooth.");
Marie Janssen59804562016-12-28 14:13:21 -0800962 sendEnableMsg(mQuietEnableExternal, "system boot");
Ajay Panickerbf796d82016-03-11 13:47:20 -0800963 } else if (!isNameAndAddressSet()) {
964 if (DBG) Slog.d(TAG, "Getting adapter name and address");
Ajay Panicker4bb48302016-03-31 14:14:27 -0700965 Message getMsg = mHandler.obtainMessage(MESSAGE_GET_NAME_AND_ADDRESS);
966 mHandler.sendMessage(getMsg);
Miao Chou658bf2f2015-06-26 17:14:35 -0700967 }
Miao Chou658bf2f2015-06-26 17:14:35 -0700968 }
969
970 /**
971 * Called when switching to a different foreground user.
972 */
973 public void handleOnSwitchUser(int userHandle) {
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -0700974 if (DBG) Slog.d(TAG, "User " + userHandle + " switched");
975 mHandler.obtainMessage(MESSAGE_USER_SWITCHED, userHandle, 0).sendToTarget();
976 }
977
978 /**
979 * Called when user is unlocked.
980 */
981 public void handleOnUnlockUser(int userHandle) {
982 if (DBG) Slog.d(TAG, "User " + userHandle + " unlocked");
983 mHandler.obtainMessage(MESSAGE_USER_UNLOCKED, userHandle, 0).sendToTarget();
Miao Chou658bf2f2015-06-26 17:14:35 -0700984 }
985
986 /**
Benjamin Franze8b98922014-11-12 15:57:54 +0000987 * This class manages the clients connected to a given ProfileService
988 * and maintains the connection with that service.
989 */
990 final private class ProfileServiceConnections implements ServiceConnection,
991 IBinder.DeathRecipient {
992 final RemoteCallbackList<IBluetoothProfileServiceConnection> mProxies =
993 new RemoteCallbackList <IBluetoothProfileServiceConnection>();
994 IBinder mService;
995 ComponentName mClassName;
996 Intent mIntent;
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700997 boolean mInvokingProxyCallbacks = false;
Benjamin Franze8b98922014-11-12 15:57:54 +0000998
999 ProfileServiceConnections(Intent intent) {
1000 mService = null;
1001 mClassName = null;
1002 mIntent = intent;
1003 }
1004
Benjamin Franz5b614592014-12-09 18:58:45 +00001005 private boolean bindService() {
1006 if (mIntent != null && mService == null &&
1007 doBind(mIntent, this, 0, UserHandle.CURRENT_OR_SELF)) {
Benjamin Franze8b98922014-11-12 15:57:54 +00001008 Message msg = mHandler.obtainMessage(MESSAGE_BIND_PROFILE_SERVICE);
1009 msg.obj = this;
1010 mHandler.sendMessageDelayed(msg, TIMEOUT_BIND_MS);
Benjamin Franz5b614592014-12-09 18:58:45 +00001011 return true;
Benjamin Franze8b98922014-11-12 15:57:54 +00001012 }
Jeff Sharkey67609c72016-03-05 14:29:13 -07001013 Slog.w(TAG, "Unable to bind with intent: " + mIntent);
Benjamin Franz5b614592014-12-09 18:58:45 +00001014 return false;
Benjamin Franze8b98922014-11-12 15:57:54 +00001015 }
1016
1017 private void addProxy(IBluetoothProfileServiceConnection proxy) {
1018 mProxies.register(proxy);
1019 if (mService != null) {
1020 try{
1021 proxy.onServiceConnected(mClassName, mService);
1022 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001023 Slog.e(TAG, "Unable to connect to proxy", e);
Benjamin Franze8b98922014-11-12 15:57:54 +00001024 }
1025 } else {
1026 if (!mHandler.hasMessages(MESSAGE_BIND_PROFILE_SERVICE, this)) {
1027 Message msg = mHandler.obtainMessage(MESSAGE_BIND_PROFILE_SERVICE);
1028 msg.obj = this;
1029 mHandler.sendMessage(msg);
1030 }
1031 }
1032 }
1033
1034 private void removeProxy(IBluetoothProfileServiceConnection proxy) {
1035 if (proxy != null) {
1036 if (mProxies.unregister(proxy)) {
1037 try {
1038 proxy.onServiceDisconnected(mClassName);
1039 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001040 Slog.e(TAG, "Unable to disconnect proxy", e);
Benjamin Franze8b98922014-11-12 15:57:54 +00001041 }
1042 }
1043 } else {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001044 Slog.w(TAG, "Trying to remove a null proxy");
Benjamin Franze8b98922014-11-12 15:57:54 +00001045 }
1046 }
1047
1048 private void removeAllProxies() {
1049 onServiceDisconnected(mClassName);
1050 mProxies.kill();
1051 }
1052
1053 @Override
1054 public void onServiceConnected(ComponentName className, IBinder service) {
1055 // remove timeout message
1056 mHandler.removeMessages(MESSAGE_BIND_PROFILE_SERVICE, this);
1057 mService = service;
1058 mClassName = className;
1059 try {
1060 mService.linkToDeath(this, 0);
1061 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001062 Slog.e(TAG, "Unable to linkToDeath", e);
Benjamin Franze8b98922014-11-12 15:57:54 +00001063 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001064
1065 if (mInvokingProxyCallbacks) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001066 Slog.e(TAG, "Proxy callbacks already in progress.");
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001067 return;
Benjamin Franze8b98922014-11-12 15:57:54 +00001068 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001069 mInvokingProxyCallbacks = true;
1070
1071 final int n = mProxies.beginBroadcast();
1072 try {
1073 for (int i = 0; i < n; i++) {
1074 try {
1075 mProxies.getBroadcastItem(i).onServiceConnected(className, service);
1076 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001077 Slog.e(TAG, "Unable to connect to proxy", e);
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001078 }
1079 }
1080 } finally {
1081 mProxies.finishBroadcast();
1082 mInvokingProxyCallbacks = false;
1083 }
Benjamin Franze8b98922014-11-12 15:57:54 +00001084 }
1085
1086 @Override
1087 public void onServiceDisconnected(ComponentName className) {
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001088 if (mService == null) return;
Benjamin Franze8b98922014-11-12 15:57:54 +00001089 mService.unlinkToDeath(this, 0);
1090 mService = null;
1091 mClassName = null;
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001092
1093 if (mInvokingProxyCallbacks) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001094 Slog.e(TAG, "Proxy callbacks already in progress.");
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001095 return;
Benjamin Franze8b98922014-11-12 15:57:54 +00001096 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001097 mInvokingProxyCallbacks = true;
1098
1099 final int n = mProxies.beginBroadcast();
1100 try {
1101 for (int i = 0; i < n; i++) {
1102 try {
1103 mProxies.getBroadcastItem(i).onServiceDisconnected(className);
1104 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001105 Slog.e(TAG, "Unable to disconnect from proxy", e);
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001106 }
1107 }
1108 } finally {
1109 mProxies.finishBroadcast();
1110 mInvokingProxyCallbacks = false;
1111 }
Benjamin Franze8b98922014-11-12 15:57:54 +00001112 }
1113
1114 @Override
1115 public void binderDied() {
1116 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001117 Slog.w(TAG, "Profile service for profile: " + mClassName
Benjamin Franze8b98922014-11-12 15:57:54 +00001118 + " died.");
1119 }
1120 onServiceDisconnected(mClassName);
1121 // Trigger rebind
1122 Message msg = mHandler.obtainMessage(MESSAGE_BIND_PROFILE_SERVICE);
1123 msg.obj = this;
1124 mHandler.sendMessageDelayed(msg, TIMEOUT_BIND_MS);
1125 }
1126 }
1127
fredcbf072a72012-05-09 16:52:50 -07001128 private void sendBluetoothStateCallback(boolean isUp) {
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001129 try {
1130 int n = mStateChangeCallbacks.beginBroadcast();
Jeff Sharkey67609c72016-03-05 14:29:13 -07001131 if (DBG) Slog.d(TAG,"Broadcasting onBluetoothStateChange("+isUp+") to " + n + " receivers.");
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001132 for (int i=0; i <n;i++) {
1133 try {
1134 mStateChangeCallbacks.getBroadcastItem(i).onBluetoothStateChange(isUp);
1135 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001136 Slog.e(TAG, "Unable to call onBluetoothStateChange() on callback #" + i , e);
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001137 }
fredcbf072a72012-05-09 16:52:50 -07001138 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001139 } finally {
1140 mStateChangeCallbacks.finishBroadcast();
fredcbf072a72012-05-09 16:52:50 -07001141 }
fredcbf072a72012-05-09 16:52:50 -07001142 }
1143
1144 /**
Zhihai Xu40874a02012-10-08 17:57:03 -07001145 * Inform BluetoothAdapter instances that Adapter service is up
1146 */
1147 private void sendBluetoothServiceUpCallback() {
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001148 try {
1149 int n = mCallbacks.beginBroadcast();
Jeff Sharkey67609c72016-03-05 14:29:13 -07001150 Slog.d(TAG,"Broadcasting onBluetoothServiceUp() to " + n + " receivers.");
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001151 for (int i=0; i <n;i++) {
1152 try {
1153 mCallbacks.getBroadcastItem(i).onBluetoothServiceUp(mBluetooth);
1154 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001155 Slog.e(TAG, "Unable to call onBluetoothServiceUp() on callback #" + i, e);
Zhihai Xu40874a02012-10-08 17:57:03 -07001156 }
1157 }
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001158 } finally {
1159 mCallbacks.finishBroadcast();
Zhihai Xu40874a02012-10-08 17:57:03 -07001160 }
1161 }
1162 /**
fredcbf072a72012-05-09 16:52:50 -07001163 * Inform BluetoothAdapter instances that Adapter service is down
1164 */
1165 private void sendBluetoothServiceDownCallback() {
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001166 try {
1167 int n = mCallbacks.beginBroadcast();
Jeff Sharkey67609c72016-03-05 14:29:13 -07001168 Slog.d(TAG,"Broadcasting onBluetoothServiceDown() to " + n + " receivers.");
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001169 for (int i=0; i <n;i++) {
1170 try {
1171 mCallbacks.getBroadcastItem(i).onBluetoothServiceDown();
1172 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001173 Slog.e(TAG, "Unable to call onBluetoothServiceDown() on callback #" + i, e);
fredcd6883532012-04-25 17:46:13 -07001174 }
1175 }
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001176 } finally {
1177 mCallbacks.finishBroadcast();
fredcd6883532012-04-25 17:46:13 -07001178 }
1179 }
Svet Ganov408abf72015-05-12 19:13:36 -07001180
fredc0f420372012-04-12 00:02:00 -07001181 public String getAddress() {
Matthew Xieaf5ddbf2012-12-04 10:47:43 -08001182 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
Svet Ganov408abf72015-05-12 19:13:36 -07001183 "Need BLUETOOTH permission");
Zhihai Xu40874a02012-10-08 17:57:03 -07001184
Zhihai Xu6eb76522012-11-29 15:41:04 -08001185 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
Svet Ganov408abf72015-05-12 19:13:36 -07001186 (!checkIfCallerIsForegroundUser())) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001187 Slog.w(TAG,"getAddress(): not allowed for non-active and non system user");
Zhihai Xu6eb76522012-11-29 15:41:04 -08001188 return null;
Zhihai Xu40874a02012-10-08 17:57:03 -07001189 }
1190
Svet Ganov408abf72015-05-12 19:13:36 -07001191 if (mContext.checkCallingOrSelfPermission(Manifest.permission.LOCAL_MAC_ADDRESS)
1192 != PackageManager.PERMISSION_GRANTED) {
1193 return BluetoothAdapter.DEFAULT_MAC_ADDRESS;
1194 }
1195
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001196 try {
1197 mBluetoothLock.readLock().lock();
1198 if (mBluetooth != null) return mBluetooth.getAddress();
1199 } catch (RemoteException e) {
1200 Slog.e(TAG, "getAddress(): Unable to retrieve address remotely. Returning cached address", e);
1201 } finally {
1202 mBluetoothLock.readLock().unlock();
fredc116d1d462012-04-20 14:47:08 -07001203 }
Ajay Panickerbf796d82016-03-11 13:47:20 -08001204
Matthew Xiecdce0b92012-07-12 19:06:15 -07001205 // mAddress is accessed from outside.
1206 // It is alright without a lock. Here, bluetooth is off, no other thread is
1207 // changing mAddress
fredc0f420372012-04-12 00:02:00 -07001208 return mAddress;
1209 }
fredc649fe492012-04-19 01:07:18 -07001210
fredc0f420372012-04-12 00:02:00 -07001211 public String getName() {
Matthew Xieaf5ddbf2012-12-04 10:47:43 -08001212 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
1213 "Need BLUETOOTH permission");
Zhihai Xu40874a02012-10-08 17:57:03 -07001214
Zhihai Xu6eb76522012-11-29 15:41:04 -08001215 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
1216 (!checkIfCallerIsForegroundUser())) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001217 Slog.w(TAG,"getName(): not allowed for non-active and non system user");
Zhihai Xu6eb76522012-11-29 15:41:04 -08001218 return null;
Zhihai Xu40874a02012-10-08 17:57:03 -07001219 }
1220
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001221 try {
1222 mBluetoothLock.readLock().lock();
1223 if (mBluetooth != null) return mBluetooth.getName();
1224 } catch (RemoteException e) {
1225 Slog.e(TAG, "getName(): Unable to retrieve name remotely. Returning cached name", e);
1226 } finally {
1227 mBluetoothLock.readLock().unlock();
fredc116d1d462012-04-20 14:47:08 -07001228 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001229
Matthew Xiecdce0b92012-07-12 19:06:15 -07001230 // mName is accessed from outside.
1231 // It alright without a lock. Here, bluetooth is off, no other thread is
1232 // changing mName
fredc0f420372012-04-12 00:02:00 -07001233 return mName;
1234 }
1235
fredc0f420372012-04-12 00:02:00 -07001236 private class BluetoothServiceConnection implements ServiceConnection {
Marie Janssencb21ad72016-12-13 10:51:02 -08001237 public void onServiceConnected(ComponentName componentName, IBinder service) {
1238 String name = componentName.getClassName();
1239 if (DBG) Slog.d(TAG, "BluetoothServiceConnection: " + name);
fredc0f420372012-04-12 00:02:00 -07001240 Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_SERVICE_CONNECTED);
Marie Janssencb21ad72016-12-13 10:51:02 -08001241 if (name.equals("com.android.bluetooth.btservice.AdapterService")) {
Matthew Xieddf7e472013-03-01 18:41:02 -08001242 msg.arg1 = SERVICE_IBLUETOOTH;
Marie Janssencb21ad72016-12-13 10:51:02 -08001243 } else if (name.equals("com.android.bluetooth.gatt.GattService")) {
Matthew Xieddf7e472013-03-01 18:41:02 -08001244 msg.arg1 = SERVICE_IBLUETOOTHGATT;
1245 } else {
Marie Janssencb21ad72016-12-13 10:51:02 -08001246 Slog.e(TAG, "Unknown service connected: " + name);
Matthew Xieddf7e472013-03-01 18:41:02 -08001247 return;
1248 }
fredc0f420372012-04-12 00:02:00 -07001249 msg.obj = service;
1250 mHandler.sendMessage(msg);
1251 }
1252
Marie Janssencb21ad72016-12-13 10:51:02 -08001253 public void onServiceDisconnected(ComponentName componentName) {
1254 // Called if we unexpectedly disconnect.
1255 String name = componentName.getClassName();
1256 if (DBG) Slog.d(TAG, "BluetoothServiceConnection, disconnected: " + name);
fredc0f420372012-04-12 00:02:00 -07001257 Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED);
Marie Janssencb21ad72016-12-13 10:51:02 -08001258 if (name.equals("com.android.bluetooth.btservice.AdapterService")) {
Matthew Xieddf7e472013-03-01 18:41:02 -08001259 msg.arg1 = SERVICE_IBLUETOOTH;
Marie Janssencb21ad72016-12-13 10:51:02 -08001260 } else if (name.equals("com.android.bluetooth.gatt.GattService")) {
Matthew Xieddf7e472013-03-01 18:41:02 -08001261 msg.arg1 = SERVICE_IBLUETOOTHGATT;
1262 } else {
Marie Janssencb21ad72016-12-13 10:51:02 -08001263 Slog.e(TAG, "Unknown service disconnected: " + name);
Matthew Xieddf7e472013-03-01 18:41:02 -08001264 return;
1265 }
fredc0f420372012-04-12 00:02:00 -07001266 mHandler.sendMessage(msg);
1267 }
1268 }
1269
1270 private BluetoothServiceConnection mConnection = new BluetoothServiceConnection();
1271
Zhihai Xu40874a02012-10-08 17:57:03 -07001272 private class BluetoothHandler extends Handler {
Ajay Panicker4bb48302016-03-31 14:14:27 -07001273 boolean mGetNameAddressOnly = false;
1274
Zhihai Xu40874a02012-10-08 17:57:03 -07001275 public BluetoothHandler(Looper looper) {
1276 super(looper);
1277 }
1278
fredc0f420372012-04-12 00:02:00 -07001279 @Override
1280 public void handleMessage(Message msg) {
fredc0f420372012-04-12 00:02:00 -07001281 switch (msg.what) {
Ajay Panicker4bb48302016-03-31 14:14:27 -07001282 case MESSAGE_GET_NAME_AND_ADDRESS:
1283 if (DBG) Slog.d(TAG, "MESSAGE_GET_NAME_AND_ADDRESS");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001284 try {
1285 mBluetoothLock.writeLock().lock();
Ajay Panicker4bb48302016-03-31 14:14:27 -07001286 if ((mBluetooth == null) && (!mBinding)) {
1287 if (DBG) Slog.d(TAG, "Binding to service to get name and address");
1288 mGetNameAddressOnly = true;
1289 Message timeoutMsg = mHandler.obtainMessage(MESSAGE_TIMEOUT_BIND);
1290 mHandler.sendMessageDelayed(timeoutMsg, TIMEOUT_BIND_MS);
1291 Intent i = new Intent(IBluetooth.class.getName());
1292 if (!doBind(i, mConnection,
1293 Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT,
1294 UserHandle.CURRENT)) {
1295 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
1296 } else {
1297 mBinding = true;
1298 }
1299 } else if (mBluetooth != null) {
1300 try {
1301 storeNameAndAddress(mBluetooth.getName(),
1302 mBluetooth.getAddress());
1303 } catch (RemoteException re) {
1304 Slog.e(TAG, "Unable to grab names", re);
1305 }
1306 if (mGetNameAddressOnly && !mEnable) {
1307 unbindAndFinish();
1308 }
1309 mGetNameAddressOnly = false;
1310 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001311 } finally {
1312 mBluetoothLock.writeLock().unlock();
Ajay Panicker4bb48302016-03-31 14:14:27 -07001313 }
1314 break;
1315
Matthew Xiecdce0b92012-07-12 19:06:15 -07001316 case MESSAGE_ENABLE:
fredcf2458862012-04-16 15:18:27 -07001317 if (DBG) {
Marie Janssencb21ad72016-12-13 10:51:02 -08001318 Slog.d(TAG, "MESSAGE_ENABLE(" + msg.arg1 + "): mBluetooth = " + mBluetooth);
fredc649fe492012-04-19 01:07:18 -07001319 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001320 mHandler.removeMessages(MESSAGE_RESTART_BLUETOOTH_SERVICE);
1321 mEnable = true;
Calvin Ona0b91d72016-06-15 17:58:23 -07001322
1323 // Use service interface to get the exact state
1324 try {
1325 mBluetoothLock.readLock().lock();
1326 if (mBluetooth != null) {
1327 int state = mBluetooth.getState();
1328 if (state == BluetoothAdapter.STATE_BLE_ON) {
Marie Janssene0bfa2e2016-12-20 11:21:12 -08001329 Slog.w(TAG, "BT Enable in BLE_ON State, going to ON");
Calvin Ona0b91d72016-06-15 17:58:23 -07001330 mBluetooth.onLeServiceUp();
Marie Janssene0bfa2e2016-12-20 11:21:12 -08001331 persistBluetoothSetting(BLUETOOTH_ON_BLUETOOTH);
Calvin Ona0b91d72016-06-15 17:58:23 -07001332 break;
1333 }
1334 }
1335 } catch (RemoteException e) {
1336 Slog.e(TAG, "", e);
1337 } finally {
1338 mBluetoothLock.readLock().unlock();
1339 }
1340
1341 mQuietEnable = (msg.arg1 == 1);
Pavlin Radoslavove47ec142016-06-01 22:25:18 -07001342 if (mBluetooth == null) {
Calvin Ona0b91d72016-06-15 17:58:23 -07001343 handleEnable(mQuietEnable);
Pavlin Radoslavove47ec142016-06-01 22:25:18 -07001344 } else {
1345 //
1346 // We need to wait until transitioned to STATE_OFF and
1347 // the previous Bluetooth process has exited. The
1348 // waiting period has three components:
1349 // (a) Wait until the local state is STATE_OFF. This
1350 // is accomplished by "waitForOnOff(false, true)".
1351 // (b) Wait until the STATE_OFF state is updated to
1352 // all components.
1353 // (c) Wait until the Bluetooth process exits, and
1354 // ActivityManager detects it.
1355 // The waiting for (b) and (c) is accomplished by
1356 // delaying the MESSAGE_RESTART_BLUETOOTH_SERVICE
1357 // message. On slower devices, that delay needs to be
1358 // on the order of (2 * SERVICE_RESTART_TIME_MS).
1359 //
1360 waitForOnOff(false, true);
Pavlin Radoslavove47ec142016-06-01 22:25:18 -07001361 Message restartMsg = mHandler.obtainMessage(
1362 MESSAGE_RESTART_BLUETOOTH_SERVICE);
1363 mHandler.sendMessageDelayed(restartMsg,
1364 2 * SERVICE_RESTART_TIME_MS);
1365 }
fredc649fe492012-04-19 01:07:18 -07001366 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001367
fredc0f420372012-04-12 00:02:00 -07001368 case MESSAGE_DISABLE:
Marie Janssencb21ad72016-12-13 10:51:02 -08001369 if (DBG) Slog.d(TAG, "MESSAGE_DISABLE: mBluetooth = " + mBluetooth);
Zhihai Xu40874a02012-10-08 17:57:03 -07001370 mHandler.removeMessages(MESSAGE_RESTART_BLUETOOTH_SERVICE);
1371 if (mEnable && mBluetooth != null) {
1372 waitForOnOff(true, false);
1373 mEnable = false;
Zhihai Xu401202b2012-12-03 11:36:21 -08001374 handleDisable();
Zhihai Xu40874a02012-10-08 17:57:03 -07001375 waitForOnOff(false, false);
1376 } else {
1377 mEnable = false;
Zhihai Xu401202b2012-12-03 11:36:21 -08001378 handleDisable();
Zhihai Xu40874a02012-10-08 17:57:03 -07001379 }
fredc0f420372012-04-12 00:02:00 -07001380 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001381
fredc0f420372012-04-12 00:02:00 -07001382 case MESSAGE_REGISTER_ADAPTER:
1383 {
1384 IBluetoothManagerCallback callback = (IBluetoothManagerCallback) msg.obj;
Marie Janssencb21ad72016-12-13 10:51:02 -08001385 mCallbacks.register(callback);
fredc0f420372012-04-12 00:02:00 -07001386 break;
Marie Janssencb21ad72016-12-13 10:51:02 -08001387 }
fredc0f420372012-04-12 00:02:00 -07001388 case MESSAGE_UNREGISTER_ADAPTER:
1389 {
1390 IBluetoothManagerCallback callback = (IBluetoothManagerCallback) msg.obj;
Marie Janssencb21ad72016-12-13 10:51:02 -08001391 mCallbacks.unregister(callback);
fredc0f420372012-04-12 00:02:00 -07001392 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001393 }
fredc0f420372012-04-12 00:02:00 -07001394 case MESSAGE_REGISTER_STATE_CHANGE_CALLBACK:
1395 {
1396 IBluetoothStateChangeCallback callback = (IBluetoothStateChangeCallback) msg.obj;
Marie Janssencb21ad72016-12-13 10:51:02 -08001397 mStateChangeCallbacks.register(callback);
fredc0f420372012-04-12 00:02:00 -07001398 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001399 }
fredc0f420372012-04-12 00:02:00 -07001400 case MESSAGE_UNREGISTER_STATE_CHANGE_CALLBACK:
1401 {
1402 IBluetoothStateChangeCallback callback = (IBluetoothStateChangeCallback) msg.obj;
Marie Janssencb21ad72016-12-13 10:51:02 -08001403 mStateChangeCallbacks.unregister(callback);
fredc0f420372012-04-12 00:02:00 -07001404 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001405 }
Benjamin Franze8b98922014-11-12 15:57:54 +00001406 case MESSAGE_ADD_PROXY_DELAYED:
1407 {
1408 ProfileServiceConnections psc = mProfileServices.get(
1409 new Integer(msg.arg1));
1410 if (psc == null) {
1411 break;
1412 }
1413 IBluetoothProfileServiceConnection proxy =
1414 (IBluetoothProfileServiceConnection) msg.obj;
1415 psc.addProxy(proxy);
1416 break;
1417 }
1418 case MESSAGE_BIND_PROFILE_SERVICE:
1419 {
1420 ProfileServiceConnections psc = (ProfileServiceConnections) msg.obj;
1421 removeMessages(MESSAGE_BIND_PROFILE_SERVICE, msg.obj);
1422 if (psc == null) {
1423 break;
1424 }
1425 psc.bindService();
1426 break;
1427 }
fredc0f420372012-04-12 00:02:00 -07001428 case MESSAGE_BLUETOOTH_SERVICE_CONNECTED:
1429 {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001430 if (DBG) Slog.d(TAG,"MESSAGE_BLUETOOTH_SERVICE_CONNECTED: " + msg.arg1);
fredc0f420372012-04-12 00:02:00 -07001431
1432 IBinder service = (IBinder) msg.obj;
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001433 try {
1434 mBluetoothLock.writeLock().lock();
Matthew Xieddf7e472013-03-01 18:41:02 -08001435 if (msg.arg1 == SERVICE_IBLUETOOTHGATT) {
1436 mBluetoothGatt = IBluetoothGatt.Stub.asInterface(service);
Nitin Arorad055adb2015-03-02 15:03:51 -08001437 onBluetoothGattServiceUp();
Matthew Xieddf7e472013-03-01 18:41:02 -08001438 break;
1439 } // else must be SERVICE_IBLUETOOTH
1440
1441 //Remove timeout
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001442 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
Matthew Xieddf7e472013-03-01 18:41:02 -08001443
fredc0f420372012-04-12 00:02:00 -07001444 mBinding = false;
Marie Janssen9db28eb2016-01-12 16:05:15 -08001445 mBluetoothBinder = service;
fredc0f420372012-04-12 00:02:00 -07001446 mBluetooth = IBluetooth.Stub.asInterface(service);
fredc0f420372012-04-12 00:02:00 -07001447
Ajay Panicker4bb48302016-03-31 14:14:27 -07001448 if (!isNameAndAddressSet()) {
1449 Message getMsg = mHandler.obtainMessage(MESSAGE_GET_NAME_AND_ADDRESS);
1450 mHandler.sendMessage(getMsg);
1451 if (mGetNameAddressOnly) return;
1452 }
1453
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001454 try {
1455 boolean enableHciSnoopLog = (Settings.Secure.getInt(mContentResolver,
1456 Settings.Secure.BLUETOOTH_HCI_LOG, 0) == 1);
1457 if (!mBluetooth.configHciSnoopLog(enableHciSnoopLog)) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001458 Slog.e(TAG,"IBluetooth.configHciSnoopLog return false");
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001459 }
1460 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001461 Slog.e(TAG,"Unable to call configHciSnoopLog", e);
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001462 }
1463
Matthew Xiecdce0b92012-07-12 19:06:15 -07001464 //Register callback object
fredcbf072a72012-05-09 16:52:50 -07001465 try {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001466 mBluetooth.registerCallback(mBluetoothCallback);
1467 } catch (RemoteException re) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001468 Slog.e(TAG, "Unable to register BluetoothCallback",re);
fredcbf072a72012-05-09 16:52:50 -07001469 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001470 //Inform BluetoothAdapter instances that service is up
Zhihai Xu40874a02012-10-08 17:57:03 -07001471 sendBluetoothServiceUpCallback();
1472
Matthew Xiecdce0b92012-07-12 19:06:15 -07001473 //Do enable request
1474 try {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001475 if (mQuietEnable == false) {
Marie Janssencb21ad72016-12-13 10:51:02 -08001476 if (!mBluetooth.enable()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001477 Slog.e(TAG,"IBluetooth.enable() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001478 }
Marie Janssencb21ad72016-12-13 10:51:02 -08001479 } else {
1480 if (!mBluetooth.enableNoAutoConnect()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001481 Slog.e(TAG,"IBluetooth.enableNoAutoConnect() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001482 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001483 }
1484 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001485 Slog.e(TAG,"Unable to call enable()",e);
Matthew Xiecdce0b92012-07-12 19:06:15 -07001486 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001487 } finally {
1488 mBluetoothLock.writeLock().unlock();
Freda8c6df02012-07-11 10:25:23 -07001489 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001490
1491 if (!mEnable) {
1492 waitForOnOff(true, false);
Zhihai Xu401202b2012-12-03 11:36:21 -08001493 handleDisable();
Zhihai Xu40874a02012-10-08 17:57:03 -07001494 waitForOnOff(false, false);
1495 }
fredc649fe492012-04-19 01:07:18 -07001496 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001497 }
fredcbf072a72012-05-09 16:52:50 -07001498 case MESSAGE_BLUETOOTH_STATE_CHANGE:
fredc0f420372012-04-12 00:02:00 -07001499 {
fredcbf072a72012-05-09 16:52:50 -07001500 int prevState = msg.arg1;
1501 int newState = msg.arg2;
Marie Janssencb21ad72016-12-13 10:51:02 -08001502 if (DBG) {
1503 Slog.d(TAG, "MESSAGE_BLUETOOTH_STATE_CHANGE: " + BluetoothAdapter.nameForState(prevState) + " > " +
1504 BluetoothAdapter.nameForState(newState));
1505 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001506 mState = newState;
1507 bluetoothStateChangeHandler(prevState, newState);
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001508 // handle error state transition case from TURNING_ON to OFF
1509 // unbind and rebind bluetooth service and enable bluetooth
Nitin Arorad055adb2015-03-02 15:03:51 -08001510 if ((prevState == BluetoothAdapter.STATE_BLE_TURNING_ON) &&
Calvin Ona0b91d72016-06-15 17:58:23 -07001511 (newState == BluetoothAdapter.STATE_OFF) &&
1512 (mBluetooth != null) && mEnable) {
Marie Janssen2977c3e2016-11-09 12:01:24 -08001513 recoverBluetoothServiceFromError(false);
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001514 }
Nitin Arorad055adb2015-03-02 15:03:51 -08001515 if ((prevState == BluetoothAdapter.STATE_TURNING_ON) &&
Calvin Ona0b91d72016-06-15 17:58:23 -07001516 (newState == BluetoothAdapter.STATE_BLE_ON) &&
1517 (mBluetooth != null) && mEnable) {
Marie Janssen2977c3e2016-11-09 12:01:24 -08001518 recoverBluetoothServiceFromError(true);
Nitin Arorad055adb2015-03-02 15:03:51 -08001519 }
Calvin Ona0b91d72016-06-15 17:58:23 -07001520 // If we tried to enable BT while BT was in the process of shutting down,
1521 // wait for the BT process to fully tear down and then force a restart
1522 // here. This is a bit of a hack (b/29363429).
1523 if ((prevState == BluetoothAdapter.STATE_BLE_TURNING_OFF) &&
1524 (newState == BluetoothAdapter.STATE_OFF)) {
1525 if (mEnable) {
1526 Slog.d(TAG, "Entering STATE_OFF but mEnabled is true; restarting.");
1527 waitForOnOff(false, true);
1528 Message restartMsg = mHandler.obtainMessage(
1529 MESSAGE_RESTART_BLUETOOTH_SERVICE);
1530 mHandler.sendMessageDelayed(restartMsg, 2 * SERVICE_RESTART_TIME_MS);
1531 }
1532 }
Nitin Arorad055adb2015-03-02 15:03:51 -08001533 if (newState == BluetoothAdapter.STATE_ON ||
Calvin Ona0b91d72016-06-15 17:58:23 -07001534 newState == BluetoothAdapter.STATE_BLE_ON) {
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001535 // bluetooth is working, reset the counter
1536 if (mErrorRecoveryRetryCounter != 0) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001537 Slog.w(TAG, "bluetooth is recovered from error");
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001538 mErrorRecoveryRetryCounter = 0;
1539 }
1540 }
fredc649fe492012-04-19 01:07:18 -07001541 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001542 }
fredc0f420372012-04-12 00:02:00 -07001543 case MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED:
1544 {
Marie Janssencb21ad72016-12-13 10:51:02 -08001545 Slog.e(TAG, "MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED(" + msg.arg1 + ")");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001546 try {
1547 mBluetoothLock.writeLock().lock();
Matthew Xieddf7e472013-03-01 18:41:02 -08001548 if (msg.arg1 == SERVICE_IBLUETOOTH) {
1549 // if service is unbinded already, do nothing and return
1550 if (mBluetooth == null) break;
1551 mBluetooth = null;
1552 } else if (msg.arg1 == SERVICE_IBLUETOOTHGATT) {
1553 mBluetoothGatt = null;
1554 break;
1555 } else {
Marie Janssencb21ad72016-12-13 10:51:02 -08001556 Slog.e(TAG, "Unknown argument for service disconnect!");
Matthew Xieddf7e472013-03-01 18:41:02 -08001557 break;
1558 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001559 } finally {
1560 mBluetoothLock.writeLock().unlock();
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301561 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001562
1563 if (mEnable) {
1564 mEnable = false;
1565 // Send a Bluetooth Restart message
1566 Message restartMsg = mHandler.obtainMessage(
1567 MESSAGE_RESTART_BLUETOOTH_SERVICE);
1568 mHandler.sendMessageDelayed(restartMsg,
1569 SERVICE_RESTART_TIME_MS);
1570 }
1571
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001572 sendBluetoothServiceDownCallback();
Zhihai Xu40874a02012-10-08 17:57:03 -07001573
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001574 // Send BT state broadcast to update
1575 // the BT icon correctly
1576 if ((mState == BluetoothAdapter.STATE_TURNING_ON) ||
Calvin Ona0b91d72016-06-15 17:58:23 -07001577 (mState == BluetoothAdapter.STATE_ON)) {
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001578 bluetoothStateChangeHandler(BluetoothAdapter.STATE_ON,
1579 BluetoothAdapter.STATE_TURNING_OFF);
1580 mState = BluetoothAdapter.STATE_TURNING_OFF;
Zhihai Xu40874a02012-10-08 17:57:03 -07001581 }
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001582 if (mState == BluetoothAdapter.STATE_TURNING_OFF) {
1583 bluetoothStateChangeHandler(BluetoothAdapter.STATE_TURNING_OFF,
1584 BluetoothAdapter.STATE_OFF);
1585 }
1586
1587 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
1588 mState = BluetoothAdapter.STATE_OFF;
fredc649fe492012-04-19 01:07:18 -07001589 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001590 }
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301591 case MESSAGE_RESTART_BLUETOOTH_SERVICE:
1592 {
Marie Janssencb21ad72016-12-13 10:51:02 -08001593 Slog.d(TAG, "MESSAGE_RESTART_BLUETOOTH_SERVICE");
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301594 /* Enable without persisting the setting as
1595 it doesnt change when IBluetooth
1596 service restarts */
Zhihai Xu40874a02012-10-08 17:57:03 -07001597 mEnable = true;
Zhihai Xu401202b2012-12-03 11:36:21 -08001598 handleEnable(mQuietEnable);
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301599 break;
1600 }
Marie Janssencb21ad72016-12-13 10:51:02 -08001601 case MESSAGE_TIMEOUT_BIND: {
1602 Slog.e(TAG, "MESSAGE_TIMEOUT_BIND");
1603 mBluetoothLock.writeLock().lock();
1604 mBinding = false;
1605 mBluetoothLock.writeLock().unlock();
1606 break;
1607 }
fredc0f420372012-04-12 00:02:00 -07001608 case MESSAGE_TIMEOUT_UNBIND:
1609 {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001610 Slog.e(TAG, "MESSAGE_TIMEOUT_UNBIND");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001611 mBluetoothLock.writeLock().lock();
1612 mUnbinding = false;
1613 mBluetoothLock.writeLock().unlock();
fredc649fe492012-04-19 01:07:18 -07001614 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001615 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001616
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001617 case MESSAGE_USER_SWITCHED: {
1618 if (DBG) Slog.d(TAG, "MESSAGE_USER_SWITCHED");
Zhihai Xu40874a02012-10-08 17:57:03 -07001619 mHandler.removeMessages(MESSAGE_USER_SWITCHED);
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001620
Zhihai Xu40874a02012-10-08 17:57:03 -07001621 /* disable and enable BT when detect a user switch */
1622 if (mEnable && mBluetooth != null) {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001623 try {
1624 mBluetoothLock.readLock().lock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001625 if (mBluetooth != null) {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001626 mBluetooth.unregisterCallback(mBluetoothCallback);
Zhihai Xu40874a02012-10-08 17:57:03 -07001627 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001628 } catch (RemoteException re) {
1629 Slog.e(TAG, "Unable to unregister", re);
1630 } finally {
1631 mBluetoothLock.readLock().unlock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001632 }
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001633
1634 if (mState == BluetoothAdapter.STATE_TURNING_OFF) {
1635 // MESSAGE_USER_SWITCHED happened right after MESSAGE_ENABLE
1636 bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_OFF);
1637 mState = BluetoothAdapter.STATE_OFF;
1638 }
1639 if (mState == BluetoothAdapter.STATE_OFF) {
1640 bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_TURNING_ON);
1641 mState = BluetoothAdapter.STATE_TURNING_ON;
1642 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001643
1644 waitForOnOff(true, false);
1645
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001646 if (mState == BluetoothAdapter.STATE_TURNING_ON) {
1647 bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_ON);
1648 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001649
Benjamin Franze8b98922014-11-12 15:57:54 +00001650 unbindAllBluetoothProfileServices();
Zhihai Xu40874a02012-10-08 17:57:03 -07001651 // disable
Zhihai Xu401202b2012-12-03 11:36:21 -08001652 handleDisable();
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001653 // Pbap service need receive STATE_TURNING_OFF intent to close
1654 bluetoothStateChangeHandler(BluetoothAdapter.STATE_ON,
1655 BluetoothAdapter.STATE_TURNING_OFF);
Zhihai Xu40874a02012-10-08 17:57:03 -07001656
Pavlin Radoslavov41401112016-06-27 15:25:18 -07001657 boolean didDisableTimeout = !waitForOnOff(false, true);
Zhihai Xu40874a02012-10-08 17:57:03 -07001658
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001659 bluetoothStateChangeHandler(BluetoothAdapter.STATE_TURNING_OFF,
Zhihai Xu40874a02012-10-08 17:57:03 -07001660 BluetoothAdapter.STATE_OFF);
Zhihai Xu40874a02012-10-08 17:57:03 -07001661 sendBluetoothServiceDownCallback();
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001662
Pavlin Radoslavove957a8a2016-05-24 15:28:41 -07001663 try {
1664 mBluetoothLock.writeLock().lock();
1665 if (mBluetooth != null) {
1666 mBluetooth = null;
1667 // Unbind
1668 mContext.unbindService(mConnection);
1669 }
1670 mBluetoothGatt = null;
1671 } finally {
1672 mBluetoothLock.writeLock().unlock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001673 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001674
Pavlin Radoslavov41401112016-06-27 15:25:18 -07001675 //
1676 // If disabling Bluetooth times out, wait for an
1677 // additional amount of time to ensure the process is
1678 // shut down completely before attempting to restart.
1679 //
1680 if (didDisableTimeout) {
1681 SystemClock.sleep(3000);
1682 } else {
1683 SystemClock.sleep(100);
1684 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001685
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001686 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
1687 mState = BluetoothAdapter.STATE_OFF;
Zhihai Xu40874a02012-10-08 17:57:03 -07001688 // enable
Zhihai Xu401202b2012-12-03 11:36:21 -08001689 handleEnable(mQuietEnable);
John Spurlock8a985d22014-02-25 09:40:05 -05001690 } else if (mBinding || mBluetooth != null) {
Zhihai Xu40874a02012-10-08 17:57:03 -07001691 Message userMsg = mHandler.obtainMessage(MESSAGE_USER_SWITCHED);
1692 userMsg.arg2 = 1 + msg.arg2;
Marie Janssencb21ad72016-12-13 10:51:02 -08001693 // if user is switched when service is binding retry after a delay
Zhihai Xu40874a02012-10-08 17:57:03 -07001694 mHandler.sendMessageDelayed(userMsg, USER_SWITCHED_TIME_MS);
1695 if (DBG) {
Marie Janssencb21ad72016-12-13 10:51:02 -08001696 Slog.d(TAG, "Retry MESSAGE_USER_SWITCHED " + userMsg.arg2);
Zhihai Xu40874a02012-10-08 17:57:03 -07001697 }
John Spurlock8a985d22014-02-25 09:40:05 -05001698 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001699 break;
1700 }
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001701 case MESSAGE_USER_UNLOCKED: {
1702 if (DBG) Slog.d(TAG, "MESSAGE_USER_UNLOCKED");
1703 mHandler.removeMessages(MESSAGE_USER_SWITCHED);
1704
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001705 if (mEnable && !mBinding && (mBluetooth == null)) {
1706 // We should be connected, but we gave up for some
1707 // reason; maybe the Bluetooth service wasn't encryption
1708 // aware, so try binding again.
1709 if (DBG) Slog.d(TAG, "Enabled but not bound; retrying after unlock");
1710 handleEnable(mQuietEnable);
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001711 }
1712 }
fredc0f420372012-04-12 00:02:00 -07001713 }
1714 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001715 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001716
Zhihai Xu401202b2012-12-03 11:36:21 -08001717 private void handleEnable(boolean quietMode) {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001718 mQuietEnable = quietMode;
1719
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001720 try {
1721 mBluetoothLock.writeLock().lock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001722 if ((mBluetooth == null) && (!mBinding)) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001723 //Start bind timeout and bind
1724 Message timeoutMsg=mHandler.obtainMessage(MESSAGE_TIMEOUT_BIND);
1725 mHandler.sendMessageDelayed(timeoutMsg,TIMEOUT_BIND_MS);
Matthew Xiecdce0b92012-07-12 19:06:15 -07001726 Intent i = new Intent(IBluetooth.class.getName());
Dianne Hackbornce09f5a2014-10-10 15:03:13 -07001727 if (!doBind(i, mConnection,Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT,
1728 UserHandle.CURRENT)) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001729 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
Zhihai Xu40874a02012-10-08 17:57:03 -07001730 } else {
1731 mBinding = true;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001732 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001733 } else if (mBluetooth != null) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001734 //Enable bluetooth
1735 try {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001736 if (!mQuietEnable) {
1737 if(!mBluetooth.enable()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001738 Slog.e(TAG,"IBluetooth.enable() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001739 }
1740 }
1741 else {
1742 if(!mBluetooth.enableNoAutoConnect()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001743 Slog.e(TAG,"IBluetooth.enableNoAutoConnect() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001744 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001745 }
1746 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001747 Slog.e(TAG,"Unable to call enable()",e);
Matthew Xiecdce0b92012-07-12 19:06:15 -07001748 }
1749 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001750 } finally {
1751 mBluetoothLock.writeLock().unlock();
Matthew Xiecdce0b92012-07-12 19:06:15 -07001752 }
1753 }
1754
Dianne Hackborn221ea892013-08-04 16:50:16 -07001755 boolean doBind(Intent intent, ServiceConnection conn, int flags, UserHandle user) {
1756 ComponentName comp = intent.resolveSystemService(mContext.getPackageManager(), 0);
1757 intent.setComponent(comp);
1758 if (comp == null || !mContext.bindServiceAsUser(intent, conn, flags, user)) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001759 Slog.e(TAG, "Fail to bind to: " + intent);
Dianne Hackborn221ea892013-08-04 16:50:16 -07001760 return false;
1761 }
1762 return true;
1763 }
1764
Zhihai Xu401202b2012-12-03 11:36:21 -08001765 private void handleDisable() {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001766 try {
1767 mBluetoothLock.readLock().lock();
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001768 if (mBluetooth != null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001769 if (DBG) Slog.d(TAG,"Sending off request.");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001770 if (!mBluetooth.disable()) {
1771 Slog.e(TAG,"IBluetooth.disable() returned false");
Matthew Xiecdce0b92012-07-12 19:06:15 -07001772 }
1773 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001774 } catch (RemoteException e) {
1775 Slog.e(TAG,"Unable to call disable()",e);
1776 } finally {
1777 mBluetoothLock.readLock().unlock();
Matthew Xiecdce0b92012-07-12 19:06:15 -07001778 }
1779 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001780
1781 private boolean checkIfCallerIsForegroundUser() {
1782 int foregroundUser;
1783 int callingUser = UserHandle.getCallingUserId();
Martijn Coenen8385c5a2012-11-29 10:14:16 -08001784 int callingUid = Binder.getCallingUid();
Zhihai Xu40874a02012-10-08 17:57:03 -07001785 long callingIdentity = Binder.clearCallingIdentity();
Benjamin Franze8b98922014-11-12 15:57:54 +00001786 UserManager um = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
1787 UserInfo ui = um.getProfileParent(callingUser);
1788 int parentUser = (ui != null) ? ui.id : UserHandle.USER_NULL;
Martijn Coenen8385c5a2012-11-29 10:14:16 -08001789 int callingAppId = UserHandle.getAppId(callingUid);
Zhihai Xu40874a02012-10-08 17:57:03 -07001790 boolean valid = false;
1791 try {
1792 foregroundUser = ActivityManager.getCurrentUser();
Martijn Coenen8385c5a2012-11-29 10:14:16 -08001793 valid = (callingUser == foregroundUser) ||
Benjamin Franze8b98922014-11-12 15:57:54 +00001794 parentUser == foregroundUser ||
Adrian Roosbd9a9a52014-08-18 15:31:57 +02001795 callingAppId == Process.NFC_UID ||
1796 callingAppId == mSystemUiUid;
Marie Janssencb21ad72016-12-13 10:51:02 -08001797 if (DBG && !valid) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001798 Slog.d(TAG, "checkIfCallerIsForegroundUser: valid=" + valid
Zhihai Xu40874a02012-10-08 17:57:03 -07001799 + " callingUser=" + callingUser
Benjamin Franze8b98922014-11-12 15:57:54 +00001800 + " parentUser=" + parentUser
Zhihai Xu40874a02012-10-08 17:57:03 -07001801 + " foregroundUser=" + foregroundUser);
1802 }
1803 } finally {
1804 Binder.restoreCallingIdentity(callingIdentity);
1805 }
1806 return valid;
1807 }
1808
Nitin Arorad055adb2015-03-02 15:03:51 -08001809 private void sendBleStateChanged(int prevState, int newState) {
Marie Janssencb21ad72016-12-13 10:51:02 -08001810 if (DBG) Slog.d(TAG,"Sending BLE State Change: " + BluetoothAdapter.nameForState(prevState) +
1811 " > " + BluetoothAdapter.nameForState(newState));
Nitin Arorad055adb2015-03-02 15:03:51 -08001812 // Send broadcast message to everyone else
1813 Intent intent = new Intent(BluetoothAdapter.ACTION_BLE_STATE_CHANGED);
1814 intent.putExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE, prevState);
1815 intent.putExtra(BluetoothAdapter.EXTRA_STATE, newState);
1816 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1817 mContext.sendBroadcastAsUser(intent, UserHandle.ALL, BLUETOOTH_PERM);
1818 }
1819
Zhihai Xu40874a02012-10-08 17:57:03 -07001820 private void bluetoothStateChangeHandler(int prevState, int newState) {
Nitin Arorad055adb2015-03-02 15:03:51 -08001821 boolean isStandardBroadcast = true;
Marie Janssencb21ad72016-12-13 10:51:02 -08001822 if (prevState == newState) { // No change. Nothing to do.
1823 return;
1824 }
1825 // Notify all proxy objects first of adapter state change
1826 if (newState == BluetoothAdapter.STATE_BLE_ON ||
1827 newState == BluetoothAdapter.STATE_OFF) {
1828 boolean intermediate_off = (prevState == BluetoothAdapter.STATE_TURNING_OFF
1829 && newState == BluetoothAdapter.STATE_BLE_ON);
Zhihai Xu40874a02012-10-08 17:57:03 -07001830
Marie Janssencb21ad72016-12-13 10:51:02 -08001831 if (newState == BluetoothAdapter.STATE_OFF) {
1832 // If Bluetooth is off, send service down event to proxy objects, and unbind
1833 if (DBG) Slog.d(TAG, "Bluetooth is complete send Service Down");
1834 sendBluetoothServiceDownCallback();
1835 unbindAndFinish();
Nitin Arorad055adb2015-03-02 15:03:51 -08001836 sendBleStateChanged(prevState, newState);
Marie Janssencb21ad72016-12-13 10:51:02 -08001837 // Don't broadcast as it has already been broadcast before
Nitin Arorad055adb2015-03-02 15:03:51 -08001838 isStandardBroadcast = false;
1839
Marie Janssencb21ad72016-12-13 10:51:02 -08001840 } else if (!intermediate_off) {
1841 // connect to GattService
1842 if (DBG) Slog.d(TAG, "Bluetooth is in LE only mode");
1843 if (mBluetoothGatt != null) {
1844 if (DBG) Slog.d(TAG, "Calling BluetoothGattServiceUp");
1845 onBluetoothGattServiceUp();
1846 } else {
1847 if (DBG) Slog.d(TAG, "Binding Bluetooth GATT service");
1848 if (mContext.getPackageManager().hasSystemFeature(
1849 PackageManager.FEATURE_BLUETOOTH_LE)) {
1850 Intent i = new Intent(IBluetoothGatt.class.getName());
1851 doBind(i, mConnection, Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT, UserHandle.CURRENT);
1852 }
Nitin Arorad055adb2015-03-02 15:03:51 -08001853 }
Marie Janssencb21ad72016-12-13 10:51:02 -08001854 sendBleStateChanged(prevState, newState);
1855 //Don't broadcase this as std intent
1856 isStandardBroadcast = false;
1857
1858 } else if (intermediate_off) {
1859 if (DBG) Slog.d(TAG, "Intermediate off, back to LE only mode");
1860 // For LE only mode, broadcast as is
1861 sendBleStateChanged(prevState, newState);
1862 sendBluetoothStateCallback(false); // BT is OFF for general users
1863 // Broadcast as STATE_OFF
1864 newState = BluetoothAdapter.STATE_OFF;
1865 sendBrEdrDownCallback();
Nitin Arorad055adb2015-03-02 15:03:51 -08001866 }
Marie Janssencb21ad72016-12-13 10:51:02 -08001867 } else if (newState == BluetoothAdapter.STATE_ON) {
1868 boolean isUp = (newState == BluetoothAdapter.STATE_ON);
1869 sendBluetoothStateCallback(isUp);
1870 sendBleStateChanged(prevState, newState);
1871
1872 } else if (newState == BluetoothAdapter.STATE_BLE_TURNING_ON ||
1873 newState == BluetoothAdapter.STATE_BLE_TURNING_OFF ) {
1874 sendBleStateChanged(prevState, newState);
1875 isStandardBroadcast = false;
1876
1877 } else if (newState == BluetoothAdapter.STATE_TURNING_ON ||
1878 newState == BluetoothAdapter.STATE_TURNING_OFF) {
1879 sendBleStateChanged(prevState, newState);
1880 }
1881
1882 if (isStandardBroadcast) {
1883 if (prevState == BluetoothAdapter.STATE_BLE_ON) {
1884 // Show prevState of BLE_ON as OFF to standard users
1885 prevState = BluetoothAdapter.STATE_OFF;
1886 }
1887 Intent intent = new Intent(BluetoothAdapter.ACTION_STATE_CHANGED);
1888 intent.putExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE, prevState);
1889 intent.putExtra(BluetoothAdapter.EXTRA_STATE, newState);
1890 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1891 mContext.sendBroadcastAsUser(intent, UserHandle.ALL, BLUETOOTH_PERM);
Zhihai Xu40874a02012-10-08 17:57:03 -07001892 }
1893 }
1894
1895 /**
1896 * if on is true, wait for state become ON
1897 * if off is true, wait for state become OFF
1898 * if both on and off are false, wait for state not ON
1899 */
1900 private boolean waitForOnOff(boolean on, boolean off) {
1901 int i = 0;
1902 while (i < 10) {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001903 try {
1904 mBluetoothLock.readLock().lock();
1905 if (mBluetooth == null) break;
1906 if (on) {
1907 if (mBluetooth.getState() == BluetoothAdapter.STATE_ON) return true;
1908 } else if (off) {
1909 if (mBluetooth.getState() == BluetoothAdapter.STATE_OFF) return true;
1910 } else {
1911 if (mBluetooth.getState() != BluetoothAdapter.STATE_ON) return true;
Zhihai Xu40874a02012-10-08 17:57:03 -07001912 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001913 } catch (RemoteException e) {
1914 Slog.e(TAG, "getState()", e);
1915 break;
1916 } finally {
1917 mBluetoothLock.readLock().unlock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001918 }
1919 if (on || off) {
1920 SystemClock.sleep(300);
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07001921 } else {
Zhihai Xu40874a02012-10-08 17:57:03 -07001922 SystemClock.sleep(50);
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07001923 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001924 i++;
1925 }
Jeff Sharkey67609c72016-03-05 14:29:13 -07001926 Slog.e(TAG,"waitForOnOff time out");
Zhihai Xu40874a02012-10-08 17:57:03 -07001927 return false;
1928 }
Zhihai Xu681ae7f2012-11-12 15:14:18 -08001929
Marie Janssen59804562016-12-28 14:13:21 -08001930 private void sendDisableMsg(String packageName) {
Zhihai Xu401202b2012-12-03 11:36:21 -08001931 mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_DISABLE));
Marie Janssen59804562016-12-28 14:13:21 -08001932 addActiveLog(packageName, false);
Zhihai Xu401202b2012-12-03 11:36:21 -08001933 }
1934
Marie Janssen59804562016-12-28 14:13:21 -08001935 private void sendEnableMsg(boolean quietMode, String packageName) {
Zhihai Xu401202b2012-12-03 11:36:21 -08001936 mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_ENABLE,
1937 quietMode ? 1 : 0, 0));
Marie Janssen59804562016-12-28 14:13:21 -08001938 addActiveLog(packageName, true);
1939 }
1940
1941 private void addActiveLog(String packageName, boolean enable) {
1942 synchronized (mActiveLogs) {
1943 if (mActiveLogs.size() > 10) {
1944 mActiveLogs.remove();
1945 }
1946 mActiveLogs.add(new ActiveLog(packageName, enable, System.currentTimeMillis()));
1947 }
Zhihai Xu401202b2012-12-03 11:36:21 -08001948 }
1949
Marie Janssen2977c3e2016-11-09 12:01:24 -08001950 private void recoverBluetoothServiceFromError(boolean clearBle) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001951 Slog.e(TAG,"recoverBluetoothServiceFromError");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001952 try {
1953 mBluetoothLock.readLock().lock();
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001954 if (mBluetooth != null) {
1955 //Unregister callback object
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001956 mBluetooth.unregisterCallback(mBluetoothCallback);
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001957 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001958 } catch (RemoteException re) {
1959 Slog.e(TAG, "Unable to unregister", re);
1960 } finally {
1961 mBluetoothLock.readLock().unlock();
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001962 }
1963
1964 SystemClock.sleep(500);
1965
1966 // disable
1967 handleDisable();
1968
1969 waitForOnOff(false, true);
1970
1971 sendBluetoothServiceDownCallback();
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001972
Pavlin Radoslavove957a8a2016-05-24 15:28:41 -07001973 try {
1974 mBluetoothLock.writeLock().lock();
1975 if (mBluetooth != null) {
1976 mBluetooth = null;
1977 // Unbind
1978 mContext.unbindService(mConnection);
1979 }
1980 mBluetoothGatt = null;
1981 } finally {
1982 mBluetoothLock.writeLock().unlock();
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001983 }
1984
1985 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
1986 mState = BluetoothAdapter.STATE_OFF;
1987
Marie Janssen2977c3e2016-11-09 12:01:24 -08001988 if (clearBle) {
1989 clearBleApps();
1990 }
1991
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001992 mEnable = false;
1993
1994 if (mErrorRecoveryRetryCounter++ < MAX_ERROR_RESTART_RETRIES) {
1995 // Send a Bluetooth Restart message to reenable bluetooth
1996 Message restartMsg = mHandler.obtainMessage(
1997 MESSAGE_RESTART_BLUETOOTH_SERVICE);
1998 mHandler.sendMessageDelayed(restartMsg, ERROR_RESTART_TIME_MS);
1999 } else {
2000 // todo: notify user to power down and power up phone to make bluetooth work.
2001 }
2002 }
Mike Lockwood726d4de2014-10-28 14:06:28 -07002003
Lenka Trochtova13a05192016-12-02 12:19:39 +01002004 private boolean isBluetoothDisallowed() {
2005 long callingIdentity = Binder.clearCallingIdentity();
2006 try {
2007 return mContext.getSystemService(UserManager.class)
2008 .hasUserRestriction(UserManager.DISALLOW_BLUETOOTH, UserHandle.SYSTEM);
2009 } finally {
2010 Binder.restoreCallingIdentity(callingIdentity);
2011 }
2012 }
2013
Mike Lockwood726d4de2014-10-28 14:06:28 -07002014 @Override
Pavlin Radoslavov6e8faff2016-02-23 11:54:37 -08002015 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2016 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DUMP, TAG);
2017 String errorMsg = null;
Marie Janssen59804562016-12-28 14:13:21 -08002018
2019 boolean protoOut = (args.length > 0) && args[0].startsWith("--proto");
2020
2021 if (!protoOut) {
2022 writer.println("Bluetooth Status");
2023 writer.println(" enabled: " + isEnabled());
2024 writer.println(" state: " + BluetoothAdapter.nameForState(mState));
2025 writer.println(" address: " + mAddress);
2026 writer.println(" name: " + mName);
2027 if (mEnable) {
2028 long onDuration = System.currentTimeMillis() - mActiveLogs.getLast().getTime();
2029 String onDurationString = String.format("%02d:%02d:%02d.%03d",
2030 (int)(onDuration / (1000 * 60 * 60)),
2031 (int)((onDuration / (1000 * 60)) % 60),
2032 (int)((onDuration / 1000) % 60),
2033 (int)(onDuration % 1000));
2034 writer.println(" time since enabled: " + onDurationString + "\n");
2035 }
2036
2037 writer.println("Enable log:");
2038 for (ActiveLog log : mActiveLogs) {
2039 writer.println(log);
2040 }
2041
2042 writer.println("\n" + mBleApps.size() + " BLE Apps registered:");
2043 for (ClientDeathRecipient app : mBleApps.values()) {
2044 writer.println(app.getPackageName());
2045 }
2046
2047 writer.flush();
Marie Janssenf5ec5382017-01-03 11:37:38 -08002048 if (args.length == 0) {
2049 // Add arg to produce output
2050 args = new String[1];
2051 args[0] = "--print";
2052 }
Marie Janssen59804562016-12-28 14:13:21 -08002053 }
2054
Pavlin Radoslavov6e8faff2016-02-23 11:54:37 -08002055 if (mBluetoothBinder == null) {
2056 errorMsg = "Bluetooth Service not connected";
2057 } else {
2058 try {
2059 mBluetoothBinder.dump(fd, args);
2060 } catch (RemoteException re) {
Marie Janssen59804562016-12-28 14:13:21 -08002061 errorMsg = "RemoteException while dumping Bluetooth Service";
Pavlin Radoslavov6e8faff2016-02-23 11:54:37 -08002062 }
Mike Lockwood726d4de2014-10-28 14:06:28 -07002063 }
Pavlin Radoslavov6e8faff2016-02-23 11:54:37 -08002064 if (errorMsg != null) {
2065 // Silently return if we are extracting metrics in Protobuf format
Marie Janssen59804562016-12-28 14:13:21 -08002066 if (protoOut) return;
Pavlin Radoslavov6e8faff2016-02-23 11:54:37 -08002067 writer.println(errorMsg);
2068 }
Mike Lockwood726d4de2014-10-28 14:06:28 -07002069 }
fredc0f420372012-04-12 00:02:00 -07002070}