blob: 9154b8eced4a9911318a27380c7321a6a0079dc9 [file] [log] [blame]
fredc0f420372012-04-12 00:02:00 -07001/*
Zhihai Xufa0fd392012-10-23 17:31:56 -07002 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
fredc0f420372012-04-12 00:02:00 -070015 */
16
17package com.android.server;
18
Svet Ganov408abf72015-05-12 19:13:36 -070019import android.Manifest;
Zhihai Xu40874a02012-10-08 17:57:03 -070020import android.app.ActivityManager;
fredc0f420372012-04-12 00:02:00 -070021import android.bluetooth.BluetoothAdapter;
Benjamin Franze8b98922014-11-12 15:57:54 +000022import android.bluetooth.BluetoothProfile;
fredc0f420372012-04-12 00:02:00 -070023import android.bluetooth.IBluetooth;
fredcbf072a72012-05-09 16:52:50 -070024import android.bluetooth.IBluetoothCallback;
Wei Wange4a744b2015-06-11 17:50:29 -070025import android.bluetooth.IBluetoothGatt;
Benjamin Franze8b98922014-11-12 15:57:54 +000026import android.bluetooth.IBluetoothHeadset;
fredc0f420372012-04-12 00:02:00 -070027import android.bluetooth.IBluetoothManager;
28import android.bluetooth.IBluetoothManagerCallback;
Benjamin Franze8b98922014-11-12 15:57:54 +000029import android.bluetooth.IBluetoothProfileServiceConnection;
fredc0f420372012-04-12 00:02:00 -070030import android.bluetooth.IBluetoothStateChangeCallback;
fredc0f420372012-04-12 00:02:00 -070031import android.content.BroadcastReceiver;
32import android.content.ComponentName;
33import android.content.ContentResolver;
34import android.content.Context;
35import android.content.Intent;
36import android.content.IntentFilter;
37import android.content.ServiceConnection;
Matthew Xie32ab77b2013-05-08 19:26:57 -070038import android.content.pm.PackageManager;
Benjamin Franze8b98922014-11-12 15:57:54 +000039import android.content.pm.UserInfo;
Wei Wange4a744b2015-06-11 17:50:29 -070040import android.database.ContentObserver;
Zhihai Xu40874a02012-10-08 17:57:03 -070041import android.os.Binder;
fredc0f420372012-04-12 00:02:00 -070042import android.os.Handler;
fredc0f420372012-04-12 00:02:00 -070043import android.os.IBinder;
Zhihai Xu40874a02012-10-08 17:57:03 -070044import android.os.Looper;
fredc0f420372012-04-12 00:02:00 -070045import android.os.Message;
Zhihai Xu40874a02012-10-08 17:57:03 -070046import android.os.Process;
fredcd6883532012-04-25 17:46:13 -070047import android.os.RemoteCallbackList;
fredc0f420372012-04-12 00:02:00 -070048import android.os.RemoteException;
Zhihai Xu40874a02012-10-08 17:57:03 -070049import android.os.SystemClock;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070050import android.os.UserHandle;
Benjamin Franze8b98922014-11-12 15:57:54 +000051import android.os.UserManager;
fredc0f420372012-04-12 00:02:00 -070052import android.provider.Settings;
Wei Wang67d84162015-04-26 17:04:29 -070053import android.provider.Settings.SettingNotFoundException;
Jeff Sharkey67609c72016-03-05 14:29:13 -070054import android.util.Slog;
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -070055import java.util.concurrent.locks.ReentrantReadWriteLock;
Mike Lockwood726d4de2014-10-28 14:06:28 -070056
57import java.io.FileDescriptor;
58import java.io.PrintWriter;
Benjamin Franze8b98922014-11-12 15:57:54 +000059import java.util.HashMap;
60import java.util.Map;
Miao Chou658bf2f2015-06-26 17:14:35 -070061
fredc0f420372012-04-12 00:02:00 -070062class BluetoothManagerService extends IBluetoothManager.Stub {
63 private static final String TAG = "BluetoothManagerService";
Pavlin Radoslavovb5a479c2015-06-20 22:55:04 -070064 private static final boolean DBG = false;
fredc0f420372012-04-12 00:02:00 -070065
fredc0f420372012-04-12 00:02:00 -070066 private static final String BLUETOOTH_ADMIN_PERM = android.Manifest.permission.BLUETOOTH_ADMIN;
67 private static final String BLUETOOTH_PERM = android.Manifest.permission.BLUETOOTH;
fredc0f420372012-04-12 00:02:00 -070068 private static final String ACTION_SERVICE_STATE_CHANGED="com.android.bluetooth.btservice.action.STATE_CHANGED";
69 private static final String EXTRA_ACTION="action";
Zhihai Xud31c3222012-10-31 16:08:57 -070070 private static final String SECURE_SETTINGS_BLUETOOTH_ADDR_VALID="bluetooth_addr_valid";
fredc0f420372012-04-12 00:02:00 -070071 private static final String SECURE_SETTINGS_BLUETOOTH_ADDRESS="bluetooth_address";
72 private static final String SECURE_SETTINGS_BLUETOOTH_NAME="bluetooth_name";
fredc0f420372012-04-12 00:02:00 -070073 private static final int TIMEOUT_BIND_MS = 3000; //Maximum msec to wait for a bind
74 private static final int TIMEOUT_SAVE_MS = 500; //Maximum msec to wait for a save
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +053075 //Maximum msec to wait for service restart
76 private static final int SERVICE_RESTART_TIME_MS = 200;
Zhihai Xudd9d17d2013-01-08 17:05:58 -080077 //Maximum msec to wait for restart due to error
78 private static final int ERROR_RESTART_TIME_MS = 3000;
Zhihai Xu40874a02012-10-08 17:57:03 -070079 //Maximum msec to delay MESSAGE_USER_SWITCHED
80 private static final int USER_SWITCHED_TIME_MS = 200;
Benjamin Franze8b98922014-11-12 15:57:54 +000081 // Delay for the addProxy function in msec
82 private static final int ADD_PROXY_DELAY_MS = 100;
fredc0f420372012-04-12 00:02:00 -070083
84 private static final int MESSAGE_ENABLE = 1;
85 private static final int MESSAGE_DISABLE = 2;
fredc649fe492012-04-19 01:07:18 -070086 private static final int MESSAGE_REGISTER_ADAPTER = 20;
87 private static final int MESSAGE_UNREGISTER_ADAPTER = 21;
88 private static final int MESSAGE_REGISTER_STATE_CHANGE_CALLBACK = 30;
89 private static final int MESSAGE_UNREGISTER_STATE_CHANGE_CALLBACK = 31;
90 private static final int MESSAGE_BLUETOOTH_SERVICE_CONNECTED = 40;
91 private static final int MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED = 41;
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +053092 private static final int MESSAGE_RESTART_BLUETOOTH_SERVICE = 42;
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -070093 private static final int MESSAGE_BLUETOOTH_STATE_CHANGE = 60;
94 private static final int MESSAGE_TIMEOUT_BIND = 100;
95 private static final int MESSAGE_TIMEOUT_UNBIND = 101;
Ajay Panicker4bb48302016-03-31 14:14:27 -070096 private static final int MESSAGE_GET_NAME_AND_ADDRESS = 200;
Zhihai Xu40874a02012-10-08 17:57:03 -070097 private static final int MESSAGE_USER_SWITCHED = 300;
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -070098 private static final int MESSAGE_USER_UNLOCKED = 301;
Benjamin Franze8b98922014-11-12 15:57:54 +000099 private static final int MESSAGE_ADD_PROXY_DELAYED = 400;
100 private static final int MESSAGE_BIND_PROFILE_SERVICE = 401;
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -0700101 private static final int MAX_SAVE_RETRIES = 3;
102 private static final int MAX_ERROR_RESTART_RETRIES = 6;
Zhihai Xudd9d17d2013-01-08 17:05:58 -0800103
Zhihai Xu401202b2012-12-03 11:36:21 -0800104 // Bluetooth persisted setting is off
105 private static final int BLUETOOTH_OFF=0;
106 // Bluetooth persisted setting is on
107 // and Airplane mode won't affect Bluetooth state at start up
108 private static final int BLUETOOTH_ON_BLUETOOTH=1;
109 // Bluetooth persisted setting is on
110 // but Airplane mode will affect Bluetooth state at start up
111 // and Airplane mode will have higher priority.
112 private static final int BLUETOOTH_ON_AIRPLANE=2;
fredc0f420372012-04-12 00:02:00 -0700113
Matthew Xieddf7e472013-03-01 18:41:02 -0800114 private static final int SERVICE_IBLUETOOTH = 1;
115 private static final int SERVICE_IBLUETOOTHGATT = 2;
116
fredc0f420372012-04-12 00:02:00 -0700117 private final Context mContext;
Nitin Arorad055adb2015-03-02 15:03:51 -0800118 private static int mBleAppCount = 0;
Matthew Xiecdce0b92012-07-12 19:06:15 -0700119
120 // Locks are not provided for mName and mAddress.
121 // They are accessed in handler or broadcast receiver, same thread context.
fredc0f420372012-04-12 00:02:00 -0700122 private String mAddress;
123 private String mName;
Matthew Xie6fde3092012-07-11 17:10:07 -0700124 private final ContentResolver mContentResolver;
125 private final RemoteCallbackList<IBluetoothManagerCallback> mCallbacks;
126 private final RemoteCallbackList<IBluetoothStateChangeCallback> mStateChangeCallbacks;
Marie Janssen9db28eb2016-01-12 16:05:15 -0800127 private IBinder mBluetoothBinder;
fredc649fe492012-04-19 01:07:18 -0700128 private IBluetooth mBluetooth;
Matthew Xieddf7e472013-03-01 18:41:02 -0800129 private IBluetoothGatt mBluetoothGatt;
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700130 private final ReentrantReadWriteLock mBluetoothLock =
131 new ReentrantReadWriteLock();
fredc649fe492012-04-19 01:07:18 -0700132 private boolean mBinding;
133 private boolean mUnbinding;
Zhihai Xu401202b2012-12-03 11:36:21 -0800134 // used inside handler thread
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700135 private boolean mQuietEnable = false;
Zhihai Xu401202b2012-12-03 11:36:21 -0800136 // configuarion from external IBinder call which is used to
137 // synchronize with broadcast receiver.
138 private boolean mQuietEnableExternal;
139 // configuarion from external IBinder call which is used to
140 // synchronize with broadcast receiver.
141 private boolean mEnableExternal;
142 // used inside handler thread
Zhihai Xu40874a02012-10-08 17:57:03 -0700143 private boolean mEnable;
144 private int mState;
Zhihai Xu40874a02012-10-08 17:57:03 -0700145 private final BluetoothHandler mHandler;
Zhihai Xudd9d17d2013-01-08 17:05:58 -0800146 private int mErrorRecoveryRetryCounter;
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200147 private final int mSystemUiUid;
fredc0f420372012-04-12 00:02:00 -0700148
Benjamin Franze8b98922014-11-12 15:57:54 +0000149 // Save a ProfileServiceConnections object for each of the bound
150 // bluetooth profile services
151 private final Map <Integer, ProfileServiceConnections> mProfileServices =
152 new HashMap <Integer, ProfileServiceConnections>();
153
fredc649fe492012-04-19 01:07:18 -0700154 private void registerForAirplaneMode(IntentFilter filter) {
155 final ContentResolver resolver = mContext.getContentResolver();
Christopher Tatec09cdce2012-09-10 16:50:14 -0700156 final String airplaneModeRadios = Settings.Global.getString(resolver,
157 Settings.Global.AIRPLANE_MODE_RADIOS);
158 final String toggleableRadios = Settings.Global.getString(resolver,
159 Settings.Global.AIRPLANE_MODE_TOGGLEABLE_RADIOS);
fredc649fe492012-04-19 01:07:18 -0700160 boolean mIsAirplaneSensitive = airplaneModeRadios == null ? true :
Christopher Tatec09cdce2012-09-10 16:50:14 -0700161 airplaneModeRadios.contains(Settings.Global.RADIO_BLUETOOTH);
fredc649fe492012-04-19 01:07:18 -0700162 if (mIsAirplaneSensitive) {
163 filter.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED);
164 }
165 }
166
fredcbf072a72012-05-09 16:52:50 -0700167 private final IBluetoothCallback mBluetoothCallback = new IBluetoothCallback.Stub() {
168 @Override
169 public void onBluetoothStateChange(int prevState, int newState) throws RemoteException {
170 Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_STATE_CHANGE,prevState,newState);
171 mHandler.sendMessage(msg);
172 }
173 };
174
175 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
fredc0f420372012-04-12 00:02:00 -0700176 @Override
177 public void onReceive(Context context, Intent intent) {
178 String action = intent.getAction();
fredcbf072a72012-05-09 16:52:50 -0700179 if (BluetoothAdapter.ACTION_LOCAL_NAME_CHANGED.equals(action)) {
fredc0f420372012-04-12 00:02:00 -0700180 String newName = intent.getStringExtra(BluetoothAdapter.EXTRA_LOCAL_NAME);
Jeff Sharkey67609c72016-03-05 14:29:13 -0700181 if (DBG) Slog.d(TAG, "Bluetooth Adapter name changed to " + newName);
fredc0f420372012-04-12 00:02:00 -0700182 if (newName != null) {
183 storeNameAndAddress(newName, null);
184 }
fredc649fe492012-04-19 01:07:18 -0700185 } else if (Intent.ACTION_AIRPLANE_MODE_CHANGED.equals(action)) {
Zhihai Xu401202b2012-12-03 11:36:21 -0800186 synchronized(mReceiver) {
187 if (isBluetoothPersistedStateOn()) {
188 if (isAirplaneModeOn()) {
189 persistBluetoothSetting(BLUETOOTH_ON_AIRPLANE);
190 } else {
191 persistBluetoothSetting(BLUETOOTH_ON_BLUETOOTH);
192 }
193 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800194
195 int st = BluetoothAdapter.STATE_OFF;
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700196 try {
197 mBluetoothLock.readLock().lock();
198 if (mBluetooth != null) {
Nitin Arorad055adb2015-03-02 15:03:51 -0800199 st = mBluetooth.getState();
Nitin Arorad055adb2015-03-02 15:03:51 -0800200 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700201 } catch (RemoteException e) {
202 Slog.e(TAG, "Unable to call getState", e);
203 } finally {
204 mBluetoothLock.readLock().unlock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800205 }
Jeff Sharkey67609c72016-03-05 14:29:13 -0700206 Slog.d(TAG, "state" + st);
Nitin Arorad055adb2015-03-02 15:03:51 -0800207
Zhihai Xu401202b2012-12-03 11:36:21 -0800208 if (isAirplaneModeOn()) {
Nitin Arorad055adb2015-03-02 15:03:51 -0800209 // Clear registered LE apps to force shut-off
210 synchronized (this) {
211 mBleAppCount = 0;
Nitin Arora11f83882015-05-07 18:45:44 -0700212 mBleApps.clear();
Nitin Arorad055adb2015-03-02 15:03:51 -0800213 }
214 if (st == BluetoothAdapter.STATE_BLE_ON) {
215 //if state is BLE_ON make sure you trigger disableBLE part
216 try {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700217 mBluetoothLock.readLock().lock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800218 if (mBluetooth != null) {
219 mBluetooth.onBrEdrDown();
220 mEnableExternal = false;
221 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700222 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700223 Slog.e(TAG,"Unable to call onBrEdrDown", e);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700224 } finally {
Pavlin Radoslavov7ee53be2016-06-09 12:58:07 -0700225 mBluetoothLock.readLock().unlock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800226 }
227 } else if (st == BluetoothAdapter.STATE_ON){
228 // disable without persisting the setting
Jeff Sharkey67609c72016-03-05 14:29:13 -0700229 Slog.d(TAG, "Calling disable");
Nitin Arorad055adb2015-03-02 15:03:51 -0800230 sendDisableMsg();
231 }
Zhihai Xu401202b2012-12-03 11:36:21 -0800232 } else if (mEnableExternal) {
233 // enable without persisting the setting
Jeff Sharkey67609c72016-03-05 14:29:13 -0700234 Slog.d(TAG, "Calling enable");
Zhihai Xu401202b2012-12-03 11:36:21 -0800235 sendEnableMsg(mQuietEnableExternal);
236 }
fredc649fe492012-04-19 01:07:18 -0700237 }
fredc0f420372012-04-12 00:02:00 -0700238 }
239 }
240 };
241
242 BluetoothManagerService(Context context) {
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700243 mHandler = new BluetoothHandler(IoThread.get().getLooper());
Zhihai Xu40874a02012-10-08 17:57:03 -0700244
fredc0f420372012-04-12 00:02:00 -0700245 mContext = context;
246 mBluetooth = null;
Marie Janssen9db28eb2016-01-12 16:05:15 -0800247 mBluetoothBinder = null;
Nitin Arorad055adb2015-03-02 15:03:51 -0800248 mBluetoothGatt = null;
fredc0f420372012-04-12 00:02:00 -0700249 mBinding = false;
250 mUnbinding = false;
Zhihai Xu40874a02012-10-08 17:57:03 -0700251 mEnable = false;
252 mState = BluetoothAdapter.STATE_OFF;
Zhihai Xu401202b2012-12-03 11:36:21 -0800253 mQuietEnableExternal = false;
254 mEnableExternal = false;
fredc0f420372012-04-12 00:02:00 -0700255 mAddress = null;
256 mName = null;
Zhihai Xudd9d17d2013-01-08 17:05:58 -0800257 mErrorRecoveryRetryCounter = 0;
fredc0f420372012-04-12 00:02:00 -0700258 mContentResolver = context.getContentResolver();
Wei Wange4a744b2015-06-11 17:50:29 -0700259 // Observe BLE scan only mode settings change.
260 registerForBleScanModeChange();
fredcd6883532012-04-25 17:46:13 -0700261 mCallbacks = new RemoteCallbackList<IBluetoothManagerCallback>();
262 mStateChangeCallbacks = new RemoteCallbackList<IBluetoothStateChangeCallback>();
Miao Chou658bf2f2015-06-26 17:14:35 -0700263 IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_LOCAL_NAME_CHANGED);
Matthew Xie6fde3092012-07-11 17:10:07 -0700264 registerForAirplaneMode(filter);
Dianne Hackbornd83a0962014-05-02 16:28:33 -0700265 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
Matthew Xie6fde3092012-07-11 17:10:07 -0700266 mContext.registerReceiver(mReceiver, filter);
fredc0f420372012-04-12 00:02:00 -0700267 loadStoredNameAndAddress();
Zhihai Xu401202b2012-12-03 11:36:21 -0800268 if (isBluetoothPersistedStateOn()) {
269 mEnableExternal = true;
fredc0f420372012-04-12 00:02:00 -0700270 }
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200271
272 int sysUiUid = -1;
273 try {
Jeff Sharkeye06b4d12016-01-06 14:51:50 -0700274 sysUiUid = mContext.getPackageManager().getPackageUidAsUser("com.android.systemui",
Jeff Sharkeyc5967e92016-01-07 18:50:29 -0700275 PackageManager.MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM);
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200276 } catch (PackageManager.NameNotFoundException e) {
Joe LaPennaacddf2b2015-09-04 12:52:42 -0700277 // Some platforms, such as wearables do not have a system ui.
Jeff Sharkey67609c72016-03-05 14:29:13 -0700278 Slog.w(TAG, "Unable to resolve SystemUI's UID.", e);
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200279 }
280 mSystemUiUid = sysUiUid;
fredc0f420372012-04-12 00:02:00 -0700281 }
282
fredc649fe492012-04-19 01:07:18 -0700283 /**
284 * Returns true if airplane mode is currently on
285 */
286 private final boolean isAirplaneModeOn() {
Christopher Tatec09cdce2012-09-10 16:50:14 -0700287 return Settings.Global.getInt(mContext.getContentResolver(),
288 Settings.Global.AIRPLANE_MODE_ON, 0) == 1;
fredc649fe492012-04-19 01:07:18 -0700289 }
290
291 /**
292 * Returns true if the Bluetooth saved state is "on"
293 */
294 private final boolean isBluetoothPersistedStateOn() {
Jeff Brownbf6f6f92012-09-25 15:03:20 -0700295 return Settings.Global.getInt(mContentResolver,
Zhihai Xu401202b2012-12-03 11:36:21 -0800296 Settings.Global.BLUETOOTH_ON, 0) != BLUETOOTH_OFF;
297 }
298
299 /**
300 * Returns true if the Bluetooth saved state is BLUETOOTH_ON_BLUETOOTH
301 */
302 private final boolean isBluetoothPersistedStateOnBluetooth() {
303 return Settings.Global.getInt(mContentResolver,
304 Settings.Global.BLUETOOTH_ON, 0) == BLUETOOTH_ON_BLUETOOTH;
fredc649fe492012-04-19 01:07:18 -0700305 }
306
307 /**
308 * Save the Bluetooth on/off state
309 *
310 */
Zhihai Xu401202b2012-12-03 11:36:21 -0800311 private void persistBluetoothSetting(int value) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -0700312 Settings.Global.putInt(mContext.getContentResolver(),
313 Settings.Global.BLUETOOTH_ON,
Zhihai Xu401202b2012-12-03 11:36:21 -0800314 value);
fredc649fe492012-04-19 01:07:18 -0700315 }
316
317 /**
318 * Returns true if the Bluetooth Adapter's name and address is
319 * locally cached
320 * @return
321 */
fredc0f420372012-04-12 00:02:00 -0700322 private boolean isNameAndAddressSet() {
323 return mName !=null && mAddress!= null && mName.length()>0 && mAddress.length()>0;
324 }
325
fredc649fe492012-04-19 01:07:18 -0700326 /**
327 * Retrieve the Bluetooth Adapter's name and address and save it in
328 * in the local cache
329 */
fredc0f420372012-04-12 00:02:00 -0700330 private void loadStoredNameAndAddress() {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700331 if (DBG) Slog.d(TAG, "Loading stored name and address");
Zhihai Xud31c3222012-10-31 16:08:57 -0700332 if (mContext.getResources().getBoolean
333 (com.android.internal.R.bool.config_bluetooth_address_validation) &&
334 Settings.Secure.getInt(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDR_VALID, 0) == 0) {
335 // if the valid flag is not set, don't load the address and name
Jeff Sharkey67609c72016-03-05 14:29:13 -0700336 if (DBG) Slog.d(TAG, "invalid bluetooth name and address stored");
Zhihai Xud31c3222012-10-31 16:08:57 -0700337 return;
338 }
fredc0f420372012-04-12 00:02:00 -0700339 mName = Settings.Secure.getString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_NAME);
340 mAddress = Settings.Secure.getString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDRESS);
Jeff Sharkey67609c72016-03-05 14:29:13 -0700341 if (DBG) Slog.d(TAG, "Stored bluetooth Name=" + mName + ",Address=" + mAddress);
fredc0f420372012-04-12 00:02:00 -0700342 }
343
fredc649fe492012-04-19 01:07:18 -0700344 /**
345 * Save the Bluetooth name and address in the persistent store.
346 * Only non-null values will be saved.
347 * @param name
348 * @param address
349 */
fredc0f420372012-04-12 00:02:00 -0700350 private void storeNameAndAddress(String name, String address) {
351 if (name != null) {
352 Settings.Secure.putString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_NAME, name);
fredc0f420372012-04-12 00:02:00 -0700353 mName = name;
Jeff Sharkey67609c72016-03-05 14:29:13 -0700354 if (DBG) Slog.d(TAG,"Stored Bluetooth name: " +
fredc649fe492012-04-19 01:07:18 -0700355 Settings.Secure.getString(mContentResolver,SECURE_SETTINGS_BLUETOOTH_NAME));
fredc0f420372012-04-12 00:02:00 -0700356 }
357
358 if (address != null) {
359 Settings.Secure.putString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDRESS, address);
fredc0f420372012-04-12 00:02:00 -0700360 mAddress=address;
Jeff Sharkey67609c72016-03-05 14:29:13 -0700361 if (DBG) Slog.d(TAG,"Stored Bluetoothaddress: " +
fredc649fe492012-04-19 01:07:18 -0700362 Settings.Secure.getString(mContentResolver,SECURE_SETTINGS_BLUETOOTH_ADDRESS));
fredc0f420372012-04-12 00:02:00 -0700363 }
Zhihai Xud31c3222012-10-31 16:08:57 -0700364
365 if ((name != null) && (address != null)) {
366 Settings.Secure.putInt(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDR_VALID, 1);
367 }
fredc0f420372012-04-12 00:02:00 -0700368 }
369
370 public IBluetooth registerAdapter(IBluetoothManagerCallback callback){
Natalie Silvanovich55db6462014-05-01 16:12:23 -0700371 if (callback == null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700372 Slog.w(TAG, "Callback is null in registerAdapter");
Natalie Silvanovich55db6462014-05-01 16:12:23 -0700373 return null;
374 }
fredc0f420372012-04-12 00:02:00 -0700375 Message msg = mHandler.obtainMessage(MESSAGE_REGISTER_ADAPTER);
376 msg.obj = callback;
377 mHandler.sendMessage(msg);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700378
379 return mBluetooth;
fredc0f420372012-04-12 00:02:00 -0700380 }
381
382 public void unregisterAdapter(IBluetoothManagerCallback callback) {
Natalie Silvanovich55db6462014-05-01 16:12:23 -0700383 if (callback == null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700384 Slog.w(TAG, "Callback is null in unregisterAdapter");
Natalie Silvanovich55db6462014-05-01 16:12:23 -0700385 return;
386 }
fredc0f420372012-04-12 00:02:00 -0700387 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
388 "Need BLUETOOTH permission");
389 Message msg = mHandler.obtainMessage(MESSAGE_UNREGISTER_ADAPTER);
390 msg.obj = callback;
391 mHandler.sendMessage(msg);
392 }
393
394 public void registerStateChangeCallback(IBluetoothStateChangeCallback callback) {
395 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
396 "Need BLUETOOTH permission");
397 Message msg = mHandler.obtainMessage(MESSAGE_REGISTER_STATE_CHANGE_CALLBACK);
398 msg.obj = callback;
399 mHandler.sendMessage(msg);
400 }
401
402 public void unregisterStateChangeCallback(IBluetoothStateChangeCallback callback) {
403 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
404 "Need BLUETOOTH permission");
405 Message msg = mHandler.obtainMessage(MESSAGE_UNREGISTER_STATE_CHANGE_CALLBACK);
406 msg.obj = callback;
407 mHandler.sendMessage(msg);
408 }
409
410 public boolean isEnabled() {
Zhihai Xu6eb76522012-11-29 15:41:04 -0800411 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
412 (!checkIfCallerIsForegroundUser())) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700413 Slog.w(TAG,"isEnabled(): not allowed for non-active and non system user");
Zhihai Xu40874a02012-10-08 17:57:03 -0700414 return false;
415 }
416
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700417 try {
418 mBluetoothLock.readLock().lock();
419 if (mBluetooth != null) return mBluetooth.isEnabled();
420 } catch (RemoteException e) {
421 Slog.e(TAG, "isEnabled()", e);
422 } finally {
423 mBluetoothLock.readLock().unlock();
fredc0f420372012-04-12 00:02:00 -0700424 }
425 return false;
426 }
427
Nitin Arorad055adb2015-03-02 15:03:51 -0800428 class ClientDeathRecipient implements IBinder.DeathRecipient {
429 public void binderDied() {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700430 if (DBG) Slog.d(TAG, "Binder is dead - unregister Ble App");
Nitin Arorad055adb2015-03-02 15:03:51 -0800431 if (mBleAppCount > 0) --mBleAppCount;
432
433 if (mBleAppCount == 0) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700434 if (DBG) Slog.d(TAG, "Disabling LE only mode after application crash");
Nitin Arorad055adb2015-03-02 15:03:51 -0800435 try {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700436 mBluetoothLock.readLock().lock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800437 if (mBluetooth != null) {
438 mBluetooth.onBrEdrDown();
439 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700440 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700441 Slog.e(TAG,"Unable to call onBrEdrDown", e);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700442 } finally {
443 mBluetoothLock.readLock().unlock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800444 }
445 }
446 }
447 }
448
449 /** Internal death rec list */
450 Map<IBinder, ClientDeathRecipient> mBleApps = new HashMap<IBinder, ClientDeathRecipient>();
451
Wei Wang67d84162015-04-26 17:04:29 -0700452 @Override
453 public boolean isBleScanAlwaysAvailable() {
454 try {
455 return (Settings.Global.getInt(mContentResolver,
456 Settings.Global.BLE_SCAN_ALWAYS_AVAILABLE)) != 0;
457 } catch (SettingNotFoundException e) {
458 }
459 return false;
460 }
461
Wei Wange4a744b2015-06-11 17:50:29 -0700462 // Monitor change of BLE scan only mode settings.
463 private void registerForBleScanModeChange() {
464 ContentObserver contentObserver = new ContentObserver(null) {
465 @Override
466 public void onChange(boolean selfChange) {
467 if (!isBleScanAlwaysAvailable()) {
468 disableBleScanMode();
469 clearBleApps();
470 try {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700471 mBluetoothLock.readLock().lock();
Wei Wange4a744b2015-06-11 17:50:29 -0700472 if (mBluetooth != null) mBluetooth.onBrEdrDown();
473 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700474 Slog.e(TAG, "error when disabling bluetooth", e);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700475 } finally {
476 mBluetoothLock.readLock().unlock();
Wei Wange4a744b2015-06-11 17:50:29 -0700477 }
478 }
479 }
480 };
481
482 mContentResolver.registerContentObserver(
483 Settings.Global.getUriFor(Settings.Global.BLE_SCAN_ALWAYS_AVAILABLE),
484 false, contentObserver);
485 }
486
487 // Disable ble scan only mode.
488 private void disableBleScanMode() {
489 try {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700490 mBluetoothLock.writeLock().lock();
Wei Wange4a744b2015-06-11 17:50:29 -0700491 if (mBluetooth != null && (mBluetooth.getState() != BluetoothAdapter.STATE_ON)) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700492 if (DBG) Slog.d(TAG, "Reseting the mEnable flag for clean disable");
Wei Wange4a744b2015-06-11 17:50:29 -0700493 mEnable = false;
494 }
495 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700496 Slog.e(TAG, "getState()", e);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700497 } finally {
498 mBluetoothLock.writeLock().unlock();
Wei Wange4a744b2015-06-11 17:50:29 -0700499 }
500 }
501
Nitin Arorad055adb2015-03-02 15:03:51 -0800502 public int updateBleAppCount(IBinder token, boolean enable) {
503 if (enable) {
504 ClientDeathRecipient r = mBleApps.get(token);
505 if (r == null) {
506 ClientDeathRecipient deathRec = new ClientDeathRecipient();
507 try {
508 token.linkToDeath(deathRec, 0);
509 } catch (RemoteException ex) {
510 throw new IllegalArgumentException("Wake lock is already dead.");
511 }
512 mBleApps.put(token, deathRec);
513 synchronized (this) {
514 ++mBleAppCount;
515 }
Jeff Sharkey67609c72016-03-05 14:29:13 -0700516 if (DBG) Slog.d(TAG, "Registered for death Notification");
Nitin Arorad055adb2015-03-02 15:03:51 -0800517 }
518
519 } else {
520 ClientDeathRecipient r = mBleApps.get(token);
521 if (r != null) {
Wei Wange4a744b2015-06-11 17:50:29 -0700522 // Unregister death recipient as the app goes away.
523 token.unlinkToDeath(r, 0);
Nitin Arorad055adb2015-03-02 15:03:51 -0800524 mBleApps.remove(token);
525 synchronized (this) {
526 if (mBleAppCount > 0) --mBleAppCount;
527 }
Jeff Sharkey67609c72016-03-05 14:29:13 -0700528 if (DBG) Slog.d(TAG, "Unregistered for death Notification");
Nitin Arorad055adb2015-03-02 15:03:51 -0800529 }
530 }
Jeff Sharkey67609c72016-03-05 14:29:13 -0700531 if (DBG) Slog.d(TAG, "Updated BleAppCount" + mBleAppCount);
Nitin Arorad055adb2015-03-02 15:03:51 -0800532 if (mBleAppCount == 0 && mEnable) {
Wei Wange4a744b2015-06-11 17:50:29 -0700533 disableBleScanMode();
Nitin Arorad055adb2015-03-02 15:03:51 -0800534 }
535 return mBleAppCount;
536 }
537
Wei Wange4a744b2015-06-11 17:50:29 -0700538 // Clear all apps using BLE scan only mode.
539 private void clearBleApps() {
540 synchronized (this) {
541 mBleApps.clear();
542 mBleAppCount = 0;
543 }
544 }
545
Nitin Arorad055adb2015-03-02 15:03:51 -0800546 /** @hide*/
547 public boolean isBleAppPresent() {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700548 if (DBG) Slog.d(TAG, "isBleAppPresent() count: " + mBleAppCount);
Nitin Arorad055adb2015-03-02 15:03:51 -0800549 return (mBleAppCount > 0);
550 }
551
552 /**
553 * Action taken when GattService is turned off
554 */
555 private void onBluetoothGattServiceUp() {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700556 if (DBG) Slog.d(TAG,"BluetoothGatt Service is Up");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700557 try {
558 mBluetoothLock.readLock().lock();
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700559 if (isBleAppPresent() == false && mBluetooth != null
560 && mBluetooth.getState() == BluetoothAdapter.STATE_BLE_ON) {
Nitin Arorad055adb2015-03-02 15:03:51 -0800561 mBluetooth.onLeServiceUp();
562
563 // waive WRITE_SECURE_SETTINGS permission check
564 long callingIdentity = Binder.clearCallingIdentity();
565 persistBluetoothSetting(BLUETOOTH_ON_BLUETOOTH);
566 Binder.restoreCallingIdentity(callingIdentity);
567 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700568 } catch (RemoteException e) {
569 Slog.e(TAG,"Unable to call onServiceUp", e);
570 } finally {
571 mBluetoothLock.readLock().unlock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800572 }
573 }
574
575 /**
576 * Inform BluetoothAdapter instances that BREDR part is down
577 * and turn off all service and stack if no LE app needs it
578 */
579 private void sendBrEdrDownCallback() {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700580 if (DBG) Slog.d(TAG,"Calling sendBrEdrDownCallback callbacks");
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700581
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700582 if (mBluetooth == null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700583 Slog.w(TAG, "Bluetooth handle is null");
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700584 return;
585 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800586
587 if (isBleAppPresent() == false) {
588 try {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700589 mBluetoothLock.readLock().lock();
590 if (mBluetooth != null) mBluetooth.onBrEdrDown();
591 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700592 Slog.e(TAG, "Call to onBrEdrDown() failed.", e);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700593 } finally {
594 mBluetoothLock.readLock().unlock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800595 }
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700596 } else {
597 // Need to stay at BLE ON. Disconnect all Gatt connections
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700598 try {
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700599 mBluetoothGatt.unregAll();
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700600 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700601 Slog.e(TAG, "Unable to disconnect all apps.", e);
Nitin Arorad055adb2015-03-02 15:03:51 -0800602 }
603 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800604 }
605
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700606 public boolean enableNoAutoConnect()
607 {
608 mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
609 "Need BLUETOOTH ADMIN permission");
Zhihai Xu40874a02012-10-08 17:57:03 -0700610
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700611 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700612 Slog.d(TAG,"enableNoAutoConnect(): mBluetooth =" + mBluetooth +
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700613 " mBinding = " + mBinding);
614 }
Martijn Coenen8385c5a2012-11-29 10:14:16 -0800615 int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
616
617 if (callingAppId != Process.NFC_UID) {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700618 throw new SecurityException("no permission to enable Bluetooth quietly");
619 }
Martijn Coenen8385c5a2012-11-29 10:14:16 -0800620
Zhihai Xu401202b2012-12-03 11:36:21 -0800621 synchronized(mReceiver) {
622 mQuietEnableExternal = true;
623 mEnableExternal = true;
624 sendEnableMsg(true);
625 }
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700626 return true;
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700627 }
Ajay Panicker4bb48302016-03-31 14:14:27 -0700628
fredc0f420372012-04-12 00:02:00 -0700629 public boolean enable() {
Zhihai Xu6eb76522012-11-29 15:41:04 -0800630 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
631 (!checkIfCallerIsForegroundUser())) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700632 Slog.w(TAG,"enable(): not allowed for non-active and non system user");
Zhihai Xu40874a02012-10-08 17:57:03 -0700633 return false;
fredcf2458862012-04-16 15:18:27 -0700634 }
635
Zhihai Xu401202b2012-12-03 11:36:21 -0800636 mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
637 "Need BLUETOOTH ADMIN permission");
638 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700639 Slog.d(TAG,"enable(): mBluetooth =" + mBluetooth +
Sanket Agarwal090bf552016-04-21 14:10:55 -0700640 " mBinding = " + mBinding + " mState = " + mState);
641 }
Zhihai Xu401202b2012-12-03 11:36:21 -0800642
643 synchronized(mReceiver) {
644 mQuietEnableExternal = false;
645 mEnableExternal = true;
646 // waive WRITE_SECURE_SETTINGS permission check
Zhihai Xu401202b2012-12-03 11:36:21 -0800647 sendEnableMsg(false);
648 }
Jeff Sharkey67609c72016-03-05 14:29:13 -0700649 if (DBG) Slog.d(TAG, "enable returning");
Zhihai Xu401202b2012-12-03 11:36:21 -0800650 return true;
fredc0f420372012-04-12 00:02:00 -0700651 }
652
653 public boolean disable(boolean persist) {
654 mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
655 "Need BLUETOOTH ADMIN permissicacheNameAndAddresson");
Zhihai Xu40874a02012-10-08 17:57:03 -0700656
Zhihai Xu6eb76522012-11-29 15:41:04 -0800657 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
658 (!checkIfCallerIsForegroundUser())) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700659 Slog.w(TAG,"disable(): not allowed for non-active and non system user");
Zhihai Xu40874a02012-10-08 17:57:03 -0700660 return false;
661 }
662
fredcf2458862012-04-16 15:18:27 -0700663 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700664 Slog.d(TAG,"disable(): mBluetooth = " + mBluetooth +
Matthew Xiecdce0b92012-07-12 19:06:15 -0700665 " mBinding = " + mBinding);
666 }
fredcf2458862012-04-16 15:18:27 -0700667
Zhihai Xu401202b2012-12-03 11:36:21 -0800668 synchronized(mReceiver) {
669 if (persist) {
670 // waive WRITE_SECURE_SETTINGS permission check
671 long callingIdentity = Binder.clearCallingIdentity();
672 persistBluetoothSetting(BLUETOOTH_OFF);
673 Binder.restoreCallingIdentity(callingIdentity);
674 }
675 mEnableExternal = false;
676 sendDisableMsg();
677 }
fredc0f420372012-04-12 00:02:00 -0700678 return true;
679 }
680
fredc649fe492012-04-19 01:07:18 -0700681 public void unbindAndFinish() {
fredcf2458862012-04-16 15:18:27 -0700682 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700683 Slog.d(TAG,"unbindAndFinish(): " + mBluetooth +
Matthew Xiecdce0b92012-07-12 19:06:15 -0700684 " mBinding = " + mBinding);
fredcf2458862012-04-16 15:18:27 -0700685 }
686
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700687 try {
688 mBluetoothLock.writeLock().lock();
fredc0f420372012-04-12 00:02:00 -0700689 if (mUnbinding) return;
690 mUnbinding = true;
Pavlin Radoslavove47ec142016-06-01 22:25:18 -0700691 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
Zhihai Xu40874a02012-10-08 17:57:03 -0700692 if (mBluetooth != null) {
Andre Eisenbach305fdab2015-11-11 21:43:26 -0800693 //Unregister callback object
694 try {
695 mBluetooth.unregisterCallback(mBluetoothCallback);
696 } catch (RemoteException re) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700697 Slog.e(TAG, "Unable to unregister BluetoothCallback",re);
fredcbf072a72012-05-09 16:52:50 -0700698 }
Andre Eisenbach305fdab2015-11-11 21:43:26 -0800699
Jeff Sharkey67609c72016-03-05 14:29:13 -0700700 if (DBG) Slog.d(TAG, "Sending unbind request.");
Marie Janssen9db28eb2016-01-12 16:05:15 -0800701 mBluetoothBinder = null;
fredcd6883532012-04-25 17:46:13 -0700702 mBluetooth = null;
703 //Unbind
fredc0f420372012-04-12 00:02:00 -0700704 mContext.unbindService(mConnection);
fredcd6883532012-04-25 17:46:13 -0700705 mUnbinding = false;
Zhihai Xu40874a02012-10-08 17:57:03 -0700706 mBinding = false;
fredcf2458862012-04-16 15:18:27 -0700707 } else {
708 mUnbinding=false;
fredc0f420372012-04-12 00:02:00 -0700709 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800710 mBluetoothGatt = null;
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700711 } finally {
712 mBluetoothLock.writeLock().unlock();
fredc0f420372012-04-12 00:02:00 -0700713 }
714 }
715
Matthew Xieddf7e472013-03-01 18:41:02 -0800716 public IBluetoothGatt getBluetoothGatt() {
717 // sync protection
718 return mBluetoothGatt;
719 }
720
Benjamin Franze8b98922014-11-12 15:57:54 +0000721 @Override
722 public boolean bindBluetoothProfileService(int bluetoothProfile,
723 IBluetoothProfileServiceConnection proxy) {
724 if (!mEnable) {
725 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700726 Slog.d(TAG, "Trying to bind to profile: " + bluetoothProfile +
Benjamin Franze8b98922014-11-12 15:57:54 +0000727 ", while Bluetooth was disabled");
728 }
729 return false;
730 }
731 synchronized (mProfileServices) {
732 ProfileServiceConnections psc = mProfileServices.get(new Integer(bluetoothProfile));
733 if (psc == null) {
734 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700735 Slog.d(TAG, "Creating new ProfileServiceConnections object for"
Benjamin Franze8b98922014-11-12 15:57:54 +0000736 + " profile: " + bluetoothProfile);
737 }
Benjamin Franz5b614592014-12-09 18:58:45 +0000738
739 if (bluetoothProfile != BluetoothProfile.HEADSET) return false;
740
741 Intent intent = new Intent(IBluetoothHeadset.class.getName());
Benjamin Franze8b98922014-11-12 15:57:54 +0000742 psc = new ProfileServiceConnections(intent);
Benjamin Franz5b614592014-12-09 18:58:45 +0000743 if (!psc.bindService()) return false;
744
Benjamin Franze8b98922014-11-12 15:57:54 +0000745 mProfileServices.put(new Integer(bluetoothProfile), psc);
Benjamin Franze8b98922014-11-12 15:57:54 +0000746 }
747 }
748
749 // Introducing a delay to give the client app time to prepare
750 Message addProxyMsg = mHandler.obtainMessage(MESSAGE_ADD_PROXY_DELAYED);
751 addProxyMsg.arg1 = bluetoothProfile;
752 addProxyMsg.obj = proxy;
753 mHandler.sendMessageDelayed(addProxyMsg, ADD_PROXY_DELAY_MS);
754 return true;
755 }
756
757 @Override
758 public void unbindBluetoothProfileService(int bluetoothProfile,
759 IBluetoothProfileServiceConnection proxy) {
760 synchronized (mProfileServices) {
761 ProfileServiceConnections psc = mProfileServices.get(new Integer(bluetoothProfile));
762 if (psc == null) {
763 return;
764 }
765 psc.removeProxy(proxy);
766 }
767 }
768
769 private void unbindAllBluetoothProfileServices() {
770 synchronized (mProfileServices) {
771 for (Integer i : mProfileServices.keySet()) {
772 ProfileServiceConnections psc = mProfileServices.get(i);
Benjamin Franz5b614592014-12-09 18:58:45 +0000773 try {
774 mContext.unbindService(psc);
775 } catch (IllegalArgumentException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700776 Slog.e(TAG, "Unable to unbind service with intent: " + psc.mIntent, e);
Benjamin Franz5b614592014-12-09 18:58:45 +0000777 }
Benjamin Franze8b98922014-11-12 15:57:54 +0000778 psc.removeAllProxies();
779 }
780 mProfileServices.clear();
781 }
782 }
783
784 /**
Miao Chou658bf2f2015-06-26 17:14:35 -0700785 * Send enable message and set adapter name and address. Called when the boot phase becomes
786 * PHASE_SYSTEM_SERVICES_READY.
787 */
788 public void handleOnBootPhase() {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700789 if (DBG) Slog.d(TAG, "Bluetooth boot completed");
Miao Chou658bf2f2015-06-26 17:14:35 -0700790 if (mEnableExternal && isBluetoothPersistedStateOnBluetooth()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700791 if (DBG) Slog.d(TAG, "Auto-enabling Bluetooth.");
Miao Chou658bf2f2015-06-26 17:14:35 -0700792 sendEnableMsg(mQuietEnableExternal);
Ajay Panickerbf796d82016-03-11 13:47:20 -0800793 } else if (!isNameAndAddressSet()) {
794 if (DBG) Slog.d(TAG, "Getting adapter name and address");
Ajay Panicker4bb48302016-03-31 14:14:27 -0700795 Message getMsg = mHandler.obtainMessage(MESSAGE_GET_NAME_AND_ADDRESS);
796 mHandler.sendMessage(getMsg);
Miao Chou658bf2f2015-06-26 17:14:35 -0700797 }
Miao Chou658bf2f2015-06-26 17:14:35 -0700798 }
799
800 /**
801 * Called when switching to a different foreground user.
802 */
803 public void handleOnSwitchUser(int userHandle) {
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -0700804 if (DBG) Slog.d(TAG, "User " + userHandle + " switched");
805 mHandler.obtainMessage(MESSAGE_USER_SWITCHED, userHandle, 0).sendToTarget();
806 }
807
808 /**
809 * Called when user is unlocked.
810 */
811 public void handleOnUnlockUser(int userHandle) {
812 if (DBG) Slog.d(TAG, "User " + userHandle + " unlocked");
813 mHandler.obtainMessage(MESSAGE_USER_UNLOCKED, userHandle, 0).sendToTarget();
Miao Chou658bf2f2015-06-26 17:14:35 -0700814 }
815
816 /**
Benjamin Franze8b98922014-11-12 15:57:54 +0000817 * This class manages the clients connected to a given ProfileService
818 * and maintains the connection with that service.
819 */
820 final private class ProfileServiceConnections implements ServiceConnection,
821 IBinder.DeathRecipient {
822 final RemoteCallbackList<IBluetoothProfileServiceConnection> mProxies =
823 new RemoteCallbackList <IBluetoothProfileServiceConnection>();
824 IBinder mService;
825 ComponentName mClassName;
826 Intent mIntent;
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700827 boolean mInvokingProxyCallbacks = false;
Benjamin Franze8b98922014-11-12 15:57:54 +0000828
829 ProfileServiceConnections(Intent intent) {
830 mService = null;
831 mClassName = null;
832 mIntent = intent;
833 }
834
Benjamin Franz5b614592014-12-09 18:58:45 +0000835 private boolean bindService() {
836 if (mIntent != null && mService == null &&
837 doBind(mIntent, this, 0, UserHandle.CURRENT_OR_SELF)) {
Benjamin Franze8b98922014-11-12 15:57:54 +0000838 Message msg = mHandler.obtainMessage(MESSAGE_BIND_PROFILE_SERVICE);
839 msg.obj = this;
840 mHandler.sendMessageDelayed(msg, TIMEOUT_BIND_MS);
Benjamin Franz5b614592014-12-09 18:58:45 +0000841 return true;
Benjamin Franze8b98922014-11-12 15:57:54 +0000842 }
Jeff Sharkey67609c72016-03-05 14:29:13 -0700843 Slog.w(TAG, "Unable to bind with intent: " + mIntent);
Benjamin Franz5b614592014-12-09 18:58:45 +0000844 return false;
Benjamin Franze8b98922014-11-12 15:57:54 +0000845 }
846
847 private void addProxy(IBluetoothProfileServiceConnection proxy) {
848 mProxies.register(proxy);
849 if (mService != null) {
850 try{
851 proxy.onServiceConnected(mClassName, mService);
852 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700853 Slog.e(TAG, "Unable to connect to proxy", e);
Benjamin Franze8b98922014-11-12 15:57:54 +0000854 }
855 } else {
856 if (!mHandler.hasMessages(MESSAGE_BIND_PROFILE_SERVICE, this)) {
857 Message msg = mHandler.obtainMessage(MESSAGE_BIND_PROFILE_SERVICE);
858 msg.obj = this;
859 mHandler.sendMessage(msg);
860 }
861 }
862 }
863
864 private void removeProxy(IBluetoothProfileServiceConnection proxy) {
865 if (proxy != null) {
866 if (mProxies.unregister(proxy)) {
867 try {
868 proxy.onServiceDisconnected(mClassName);
869 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700870 Slog.e(TAG, "Unable to disconnect proxy", e);
Benjamin Franze8b98922014-11-12 15:57:54 +0000871 }
872 }
873 } else {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700874 Slog.w(TAG, "Trying to remove a null proxy");
Benjamin Franze8b98922014-11-12 15:57:54 +0000875 }
876 }
877
878 private void removeAllProxies() {
879 onServiceDisconnected(mClassName);
880 mProxies.kill();
881 }
882
883 @Override
884 public void onServiceConnected(ComponentName className, IBinder service) {
885 // remove timeout message
886 mHandler.removeMessages(MESSAGE_BIND_PROFILE_SERVICE, this);
887 mService = service;
888 mClassName = className;
889 try {
890 mService.linkToDeath(this, 0);
891 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700892 Slog.e(TAG, "Unable to linkToDeath", e);
Benjamin Franze8b98922014-11-12 15:57:54 +0000893 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700894
895 if (mInvokingProxyCallbacks) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700896 Slog.e(TAG, "Proxy callbacks already in progress.");
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700897 return;
Benjamin Franze8b98922014-11-12 15:57:54 +0000898 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700899 mInvokingProxyCallbacks = true;
900
901 final int n = mProxies.beginBroadcast();
902 try {
903 for (int i = 0; i < n; i++) {
904 try {
905 mProxies.getBroadcastItem(i).onServiceConnected(className, service);
906 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700907 Slog.e(TAG, "Unable to connect to proxy", e);
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700908 }
909 }
910 } finally {
911 mProxies.finishBroadcast();
912 mInvokingProxyCallbacks = false;
913 }
Benjamin Franze8b98922014-11-12 15:57:54 +0000914 }
915
916 @Override
917 public void onServiceDisconnected(ComponentName className) {
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700918 if (mService == null) return;
Benjamin Franze8b98922014-11-12 15:57:54 +0000919 mService.unlinkToDeath(this, 0);
920 mService = null;
921 mClassName = null;
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700922
923 if (mInvokingProxyCallbacks) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700924 Slog.e(TAG, "Proxy callbacks already in progress.");
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700925 return;
Benjamin Franze8b98922014-11-12 15:57:54 +0000926 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700927 mInvokingProxyCallbacks = true;
928
929 final int n = mProxies.beginBroadcast();
930 try {
931 for (int i = 0; i < n; i++) {
932 try {
933 mProxies.getBroadcastItem(i).onServiceDisconnected(className);
934 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700935 Slog.e(TAG, "Unable to disconnect from proxy", e);
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700936 }
937 }
938 } finally {
939 mProxies.finishBroadcast();
940 mInvokingProxyCallbacks = false;
941 }
Benjamin Franze8b98922014-11-12 15:57:54 +0000942 }
943
944 @Override
945 public void binderDied() {
946 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700947 Slog.w(TAG, "Profile service for profile: " + mClassName
Benjamin Franze8b98922014-11-12 15:57:54 +0000948 + " died.");
949 }
950 onServiceDisconnected(mClassName);
951 // Trigger rebind
952 Message msg = mHandler.obtainMessage(MESSAGE_BIND_PROFILE_SERVICE);
953 msg.obj = this;
954 mHandler.sendMessageDelayed(msg, TIMEOUT_BIND_MS);
955 }
956 }
957
fredcbf072a72012-05-09 16:52:50 -0700958 private void sendBluetoothStateCallback(boolean isUp) {
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700959 try {
960 int n = mStateChangeCallbacks.beginBroadcast();
Jeff Sharkey67609c72016-03-05 14:29:13 -0700961 if (DBG) Slog.d(TAG,"Broadcasting onBluetoothStateChange("+isUp+") to " + n + " receivers.");
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700962 for (int i=0; i <n;i++) {
963 try {
964 mStateChangeCallbacks.getBroadcastItem(i).onBluetoothStateChange(isUp);
965 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700966 Slog.e(TAG, "Unable to call onBluetoothStateChange() on callback #" + i , e);
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700967 }
fredcbf072a72012-05-09 16:52:50 -0700968 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700969 } finally {
970 mStateChangeCallbacks.finishBroadcast();
fredcbf072a72012-05-09 16:52:50 -0700971 }
fredcbf072a72012-05-09 16:52:50 -0700972 }
973
974 /**
Zhihai Xu40874a02012-10-08 17:57:03 -0700975 * Inform BluetoothAdapter instances that Adapter service is up
976 */
977 private void sendBluetoothServiceUpCallback() {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700978 if (DBG) Slog.d(TAG,"Calling onBluetoothServiceUp callbacks");
Andre Eisenbach305fdab2015-11-11 21:43:26 -0800979 try {
980 int n = mCallbacks.beginBroadcast();
Jeff Sharkey67609c72016-03-05 14:29:13 -0700981 Slog.d(TAG,"Broadcasting onBluetoothServiceUp() to " + n + " receivers.");
Andre Eisenbach305fdab2015-11-11 21:43:26 -0800982 for (int i=0; i <n;i++) {
983 try {
984 mCallbacks.getBroadcastItem(i).onBluetoothServiceUp(mBluetooth);
985 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700986 Slog.e(TAG, "Unable to call onBluetoothServiceUp() on callback #" + i, e);
Zhihai Xu40874a02012-10-08 17:57:03 -0700987 }
988 }
Andre Eisenbach305fdab2015-11-11 21:43:26 -0800989 } finally {
990 mCallbacks.finishBroadcast();
Zhihai Xu40874a02012-10-08 17:57:03 -0700991 }
992 }
993 /**
fredcbf072a72012-05-09 16:52:50 -0700994 * Inform BluetoothAdapter instances that Adapter service is down
995 */
996 private void sendBluetoothServiceDownCallback() {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700997 if (DBG) Slog.d(TAG,"Calling onBluetoothServiceDown callbacks");
Andre Eisenbach305fdab2015-11-11 21:43:26 -0800998 try {
999 int n = mCallbacks.beginBroadcast();
Jeff Sharkey67609c72016-03-05 14:29:13 -07001000 Slog.d(TAG,"Broadcasting onBluetoothServiceDown() to " + n + " receivers.");
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001001 for (int i=0; i <n;i++) {
1002 try {
1003 mCallbacks.getBroadcastItem(i).onBluetoothServiceDown();
1004 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001005 Slog.e(TAG, "Unable to call onBluetoothServiceDown() on callback #" + i, e);
fredcd6883532012-04-25 17:46:13 -07001006 }
1007 }
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001008 } finally {
1009 mCallbacks.finishBroadcast();
fredcd6883532012-04-25 17:46:13 -07001010 }
1011 }
Svet Ganov408abf72015-05-12 19:13:36 -07001012
fredc0f420372012-04-12 00:02:00 -07001013 public String getAddress() {
Matthew Xieaf5ddbf2012-12-04 10:47:43 -08001014 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
Svet Ganov408abf72015-05-12 19:13:36 -07001015 "Need BLUETOOTH permission");
Zhihai Xu40874a02012-10-08 17:57:03 -07001016
Zhihai Xu6eb76522012-11-29 15:41:04 -08001017 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
Svet Ganov408abf72015-05-12 19:13:36 -07001018 (!checkIfCallerIsForegroundUser())) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001019 Slog.w(TAG,"getAddress(): not allowed for non-active and non system user");
Zhihai Xu6eb76522012-11-29 15:41:04 -08001020 return null;
Zhihai Xu40874a02012-10-08 17:57:03 -07001021 }
1022
Svet Ganov408abf72015-05-12 19:13:36 -07001023 if (mContext.checkCallingOrSelfPermission(Manifest.permission.LOCAL_MAC_ADDRESS)
1024 != PackageManager.PERMISSION_GRANTED) {
1025 return BluetoothAdapter.DEFAULT_MAC_ADDRESS;
1026 }
1027
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001028 try {
1029 mBluetoothLock.readLock().lock();
1030 if (mBluetooth != null) return mBluetooth.getAddress();
1031 } catch (RemoteException e) {
1032 Slog.e(TAG, "getAddress(): Unable to retrieve address remotely. Returning cached address", e);
1033 } finally {
1034 mBluetoothLock.readLock().unlock();
fredc116d1d462012-04-20 14:47:08 -07001035 }
Ajay Panickerbf796d82016-03-11 13:47:20 -08001036
Matthew Xiecdce0b92012-07-12 19:06:15 -07001037 // mAddress is accessed from outside.
1038 // It is alright without a lock. Here, bluetooth is off, no other thread is
1039 // changing mAddress
fredc0f420372012-04-12 00:02:00 -07001040 return mAddress;
1041 }
fredc649fe492012-04-19 01:07:18 -07001042
fredc0f420372012-04-12 00:02:00 -07001043 public String getName() {
Matthew Xieaf5ddbf2012-12-04 10:47:43 -08001044 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
1045 "Need BLUETOOTH permission");
Zhihai Xu40874a02012-10-08 17:57:03 -07001046
Zhihai Xu6eb76522012-11-29 15:41:04 -08001047 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
1048 (!checkIfCallerIsForegroundUser())) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001049 Slog.w(TAG,"getName(): not allowed for non-active and non system user");
Zhihai Xu6eb76522012-11-29 15:41:04 -08001050 return null;
Zhihai Xu40874a02012-10-08 17:57:03 -07001051 }
1052
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001053 try {
1054 mBluetoothLock.readLock().lock();
1055 if (mBluetooth != null) return mBluetooth.getName();
1056 } catch (RemoteException e) {
1057 Slog.e(TAG, "getName(): Unable to retrieve name remotely. Returning cached name", e);
1058 } finally {
1059 mBluetoothLock.readLock().unlock();
fredc116d1d462012-04-20 14:47:08 -07001060 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001061
Matthew Xiecdce0b92012-07-12 19:06:15 -07001062 // mName is accessed from outside.
1063 // It alright without a lock. Here, bluetooth is off, no other thread is
1064 // changing mName
fredc0f420372012-04-12 00:02:00 -07001065 return mName;
1066 }
1067
fredc0f420372012-04-12 00:02:00 -07001068 private class BluetoothServiceConnection implements ServiceConnection {
fredc0f420372012-04-12 00:02:00 -07001069 public void onServiceConnected(ComponentName className, IBinder service) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001070 if (DBG) Slog.d(TAG, "BluetoothServiceConnection: " + className.getClassName());
fredc0f420372012-04-12 00:02:00 -07001071 Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_SERVICE_CONNECTED);
Matthew Xieddf7e472013-03-01 18:41:02 -08001072 // TBD if (className.getClassName().equals(IBluetooth.class.getName())) {
1073 if (className.getClassName().equals("com.android.bluetooth.btservice.AdapterService")) {
1074 msg.arg1 = SERVICE_IBLUETOOTH;
1075 // } else if (className.getClassName().equals(IBluetoothGatt.class.getName())) {
1076 } else if (className.getClassName().equals("com.android.bluetooth.gatt.GattService")) {
1077 msg.arg1 = SERVICE_IBLUETOOTHGATT;
1078 } else {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001079 Slog.e(TAG, "Unknown service connected: " + className.getClassName());
Matthew Xieddf7e472013-03-01 18:41:02 -08001080 return;
1081 }
fredc0f420372012-04-12 00:02:00 -07001082 msg.obj = service;
1083 mHandler.sendMessage(msg);
1084 }
1085
1086 public void onServiceDisconnected(ComponentName className) {
fredc0f420372012-04-12 00:02:00 -07001087 // Called if we unexpected disconnected.
Jeff Sharkey67609c72016-03-05 14:29:13 -07001088 if (DBG) Slog.d(TAG, "BluetoothServiceConnection, disconnected: " +
Matthew Xieddf7e472013-03-01 18:41:02 -08001089 className.getClassName());
fredc0f420372012-04-12 00:02:00 -07001090 Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED);
Matthew Xieddf7e472013-03-01 18:41:02 -08001091 if (className.getClassName().equals("com.android.bluetooth.btservice.AdapterService")) {
1092 msg.arg1 = SERVICE_IBLUETOOTH;
1093 } else if (className.getClassName().equals("com.android.bluetooth.gatt.GattService")) {
1094 msg.arg1 = SERVICE_IBLUETOOTHGATT;
1095 } else {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001096 Slog.e(TAG, "Unknown service disconnected: " + className.getClassName());
Matthew Xieddf7e472013-03-01 18:41:02 -08001097 return;
1098 }
fredc0f420372012-04-12 00:02:00 -07001099 mHandler.sendMessage(msg);
1100 }
1101 }
1102
1103 private BluetoothServiceConnection mConnection = new BluetoothServiceConnection();
1104
Zhihai Xu40874a02012-10-08 17:57:03 -07001105 private class BluetoothHandler extends Handler {
Ajay Panicker4bb48302016-03-31 14:14:27 -07001106 boolean mGetNameAddressOnly = false;
1107
Zhihai Xu40874a02012-10-08 17:57:03 -07001108 public BluetoothHandler(Looper looper) {
1109 super(looper);
1110 }
1111
fredc0f420372012-04-12 00:02:00 -07001112 @Override
1113 public void handleMessage(Message msg) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001114 if (DBG) Slog.d (TAG, "Message: " + msg.what);
fredc0f420372012-04-12 00:02:00 -07001115 switch (msg.what) {
Ajay Panicker4bb48302016-03-31 14:14:27 -07001116 case MESSAGE_GET_NAME_AND_ADDRESS:
1117 if (DBG) Slog.d(TAG, "MESSAGE_GET_NAME_AND_ADDRESS");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001118 try {
1119 mBluetoothLock.writeLock().lock();
Ajay Panicker4bb48302016-03-31 14:14:27 -07001120 if ((mBluetooth == null) && (!mBinding)) {
1121 if (DBG) Slog.d(TAG, "Binding to service to get name and address");
1122 mGetNameAddressOnly = true;
1123 Message timeoutMsg = mHandler.obtainMessage(MESSAGE_TIMEOUT_BIND);
1124 mHandler.sendMessageDelayed(timeoutMsg, TIMEOUT_BIND_MS);
1125 Intent i = new Intent(IBluetooth.class.getName());
1126 if (!doBind(i, mConnection,
1127 Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT,
1128 UserHandle.CURRENT)) {
1129 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
1130 } else {
1131 mBinding = true;
1132 }
1133 } else if (mBluetooth != null) {
1134 try {
1135 storeNameAndAddress(mBluetooth.getName(),
1136 mBluetooth.getAddress());
1137 } catch (RemoteException re) {
1138 Slog.e(TAG, "Unable to grab names", re);
1139 }
1140 if (mGetNameAddressOnly && !mEnable) {
1141 unbindAndFinish();
1142 }
1143 mGetNameAddressOnly = false;
1144 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001145 } finally {
1146 mBluetoothLock.writeLock().unlock();
Ajay Panicker4bb48302016-03-31 14:14:27 -07001147 }
1148 break;
1149
Matthew Xiecdce0b92012-07-12 19:06:15 -07001150 case MESSAGE_ENABLE:
fredcf2458862012-04-16 15:18:27 -07001151 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001152 Slog.d(TAG, "MESSAGE_ENABLE: mBluetooth = " + mBluetooth);
fredc649fe492012-04-19 01:07:18 -07001153 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001154 mHandler.removeMessages(MESSAGE_RESTART_BLUETOOTH_SERVICE);
1155 mEnable = true;
Pavlin Radoslavove47ec142016-06-01 22:25:18 -07001156 if (mBluetooth == null) {
1157 handleEnable(msg.arg1 == 1);
1158 } else {
1159 //
1160 // We need to wait until transitioned to STATE_OFF and
1161 // the previous Bluetooth process has exited. The
1162 // waiting period has three components:
1163 // (a) Wait until the local state is STATE_OFF. This
1164 // is accomplished by "waitForOnOff(false, true)".
1165 // (b) Wait until the STATE_OFF state is updated to
1166 // all components.
1167 // (c) Wait until the Bluetooth process exits, and
1168 // ActivityManager detects it.
1169 // The waiting for (b) and (c) is accomplished by
1170 // delaying the MESSAGE_RESTART_BLUETOOTH_SERVICE
1171 // message. On slower devices, that delay needs to be
1172 // on the order of (2 * SERVICE_RESTART_TIME_MS).
1173 //
1174 waitForOnOff(false, true);
1175 mQuietEnable = (msg.arg1 == 1);
1176 Message restartMsg = mHandler.obtainMessage(
1177 MESSAGE_RESTART_BLUETOOTH_SERVICE);
1178 mHandler.sendMessageDelayed(restartMsg,
1179 2 * SERVICE_RESTART_TIME_MS);
1180 }
fredc649fe492012-04-19 01:07:18 -07001181 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001182
fredc0f420372012-04-12 00:02:00 -07001183 case MESSAGE_DISABLE:
Zhihai Xu40874a02012-10-08 17:57:03 -07001184 mHandler.removeMessages(MESSAGE_RESTART_BLUETOOTH_SERVICE);
1185 if (mEnable && mBluetooth != null) {
1186 waitForOnOff(true, false);
1187 mEnable = false;
Zhihai Xu401202b2012-12-03 11:36:21 -08001188 handleDisable();
Zhihai Xu40874a02012-10-08 17:57:03 -07001189 waitForOnOff(false, false);
1190 } else {
1191 mEnable = false;
Zhihai Xu401202b2012-12-03 11:36:21 -08001192 handleDisable();
Zhihai Xu40874a02012-10-08 17:57:03 -07001193 }
fredc0f420372012-04-12 00:02:00 -07001194 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001195
fredc0f420372012-04-12 00:02:00 -07001196 case MESSAGE_REGISTER_ADAPTER:
1197 {
1198 IBluetoothManagerCallback callback = (IBluetoothManagerCallback) msg.obj;
fredcd6883532012-04-25 17:46:13 -07001199 boolean added = mCallbacks.register(callback);
Jeff Sharkey67609c72016-03-05 14:29:13 -07001200 Slog.d(TAG,"Added callback: " + (callback == null? "null": callback) +":" +added );
fredc0f420372012-04-12 00:02:00 -07001201 }
1202 break;
1203 case MESSAGE_UNREGISTER_ADAPTER:
1204 {
1205 IBluetoothManagerCallback callback = (IBluetoothManagerCallback) msg.obj;
fredcd6883532012-04-25 17:46:13 -07001206 boolean removed = mCallbacks.unregister(callback);
Jeff Sharkey67609c72016-03-05 14:29:13 -07001207 Slog.d(TAG,"Removed callback: " + (callback == null? "null": callback) +":" + removed);
fredc0f420372012-04-12 00:02:00 -07001208 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001209 }
fredc0f420372012-04-12 00:02:00 -07001210 case MESSAGE_REGISTER_STATE_CHANGE_CALLBACK:
1211 {
1212 IBluetoothStateChangeCallback callback = (IBluetoothStateChangeCallback) msg.obj;
Matthew Xie9b693992013-10-10 11:21:40 -07001213 if (callback != null) {
1214 mStateChangeCallbacks.register(callback);
1215 }
fredc0f420372012-04-12 00:02:00 -07001216 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001217 }
fredc0f420372012-04-12 00:02:00 -07001218 case MESSAGE_UNREGISTER_STATE_CHANGE_CALLBACK:
1219 {
1220 IBluetoothStateChangeCallback callback = (IBluetoothStateChangeCallback) msg.obj;
Matthew Xie9b693992013-10-10 11:21:40 -07001221 if (callback != null) {
1222 mStateChangeCallbacks.unregister(callback);
1223 }
fredc0f420372012-04-12 00:02:00 -07001224 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001225 }
Benjamin Franze8b98922014-11-12 15:57:54 +00001226 case MESSAGE_ADD_PROXY_DELAYED:
1227 {
1228 ProfileServiceConnections psc = mProfileServices.get(
1229 new Integer(msg.arg1));
1230 if (psc == null) {
1231 break;
1232 }
1233 IBluetoothProfileServiceConnection proxy =
1234 (IBluetoothProfileServiceConnection) msg.obj;
1235 psc.addProxy(proxy);
1236 break;
1237 }
1238 case MESSAGE_BIND_PROFILE_SERVICE:
1239 {
1240 ProfileServiceConnections psc = (ProfileServiceConnections) msg.obj;
1241 removeMessages(MESSAGE_BIND_PROFILE_SERVICE, msg.obj);
1242 if (psc == null) {
1243 break;
1244 }
1245 psc.bindService();
1246 break;
1247 }
fredc0f420372012-04-12 00:02:00 -07001248 case MESSAGE_BLUETOOTH_SERVICE_CONNECTED:
1249 {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001250 if (DBG) Slog.d(TAG,"MESSAGE_BLUETOOTH_SERVICE_CONNECTED: " + msg.arg1);
fredc0f420372012-04-12 00:02:00 -07001251
1252 IBinder service = (IBinder) msg.obj;
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001253 try {
1254 mBluetoothLock.writeLock().lock();
Matthew Xieddf7e472013-03-01 18:41:02 -08001255 if (msg.arg1 == SERVICE_IBLUETOOTHGATT) {
1256 mBluetoothGatt = IBluetoothGatt.Stub.asInterface(service);
Nitin Arorad055adb2015-03-02 15:03:51 -08001257 onBluetoothGattServiceUp();
Matthew Xieddf7e472013-03-01 18:41:02 -08001258 break;
1259 } // else must be SERVICE_IBLUETOOTH
1260
1261 //Remove timeout
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001262 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
Matthew Xieddf7e472013-03-01 18:41:02 -08001263
fredc0f420372012-04-12 00:02:00 -07001264 mBinding = false;
Marie Janssen9db28eb2016-01-12 16:05:15 -08001265 mBluetoothBinder = service;
fredc0f420372012-04-12 00:02:00 -07001266 mBluetooth = IBluetooth.Stub.asInterface(service);
fredc0f420372012-04-12 00:02:00 -07001267
Ajay Panicker4bb48302016-03-31 14:14:27 -07001268 if (!isNameAndAddressSet()) {
1269 Message getMsg = mHandler.obtainMessage(MESSAGE_GET_NAME_AND_ADDRESS);
1270 mHandler.sendMessage(getMsg);
1271 if (mGetNameAddressOnly) return;
1272 }
1273
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001274 try {
1275 boolean enableHciSnoopLog = (Settings.Secure.getInt(mContentResolver,
1276 Settings.Secure.BLUETOOTH_HCI_LOG, 0) == 1);
1277 if (!mBluetooth.configHciSnoopLog(enableHciSnoopLog)) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001278 Slog.e(TAG,"IBluetooth.configHciSnoopLog return false");
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001279 }
1280 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001281 Slog.e(TAG,"Unable to call configHciSnoopLog", e);
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001282 }
1283
Matthew Xiecdce0b92012-07-12 19:06:15 -07001284 //Register callback object
fredcbf072a72012-05-09 16:52:50 -07001285 try {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001286 mBluetooth.registerCallback(mBluetoothCallback);
1287 } catch (RemoteException re) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001288 Slog.e(TAG, "Unable to register BluetoothCallback",re);
fredcbf072a72012-05-09 16:52:50 -07001289 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001290 //Inform BluetoothAdapter instances that service is up
Zhihai Xu40874a02012-10-08 17:57:03 -07001291 sendBluetoothServiceUpCallback();
1292
Matthew Xiecdce0b92012-07-12 19:06:15 -07001293 //Do enable request
1294 try {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001295 if (mQuietEnable == false) {
1296 if(!mBluetooth.enable()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001297 Slog.e(TAG,"IBluetooth.enable() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001298 }
1299 }
1300 else
1301 {
1302 if(!mBluetooth.enableNoAutoConnect()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001303 Slog.e(TAG,"IBluetooth.enableNoAutoConnect() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001304 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001305 }
1306 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001307 Slog.e(TAG,"Unable to call enable()",e);
Matthew Xiecdce0b92012-07-12 19:06:15 -07001308 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001309 } finally {
1310 mBluetoothLock.writeLock().unlock();
Freda8c6df02012-07-11 10:25:23 -07001311 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001312
1313 if (!mEnable) {
1314 waitForOnOff(true, false);
Zhihai Xu401202b2012-12-03 11:36:21 -08001315 handleDisable();
Zhihai Xu40874a02012-10-08 17:57:03 -07001316 waitForOnOff(false, false);
1317 }
fredc649fe492012-04-19 01:07:18 -07001318 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001319 }
fredc649fe492012-04-19 01:07:18 -07001320 case MESSAGE_TIMEOUT_BIND: {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001321 Slog.e(TAG, "MESSAGE_TIMEOUT_BIND");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001322 mBluetoothLock.writeLock().lock();
1323 mBinding = false;
1324 mBluetoothLock.writeLock().unlock();
1325
fredc649fe492012-04-19 01:07:18 -07001326 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001327 }
fredcbf072a72012-05-09 16:52:50 -07001328 case MESSAGE_BLUETOOTH_STATE_CHANGE:
fredc0f420372012-04-12 00:02:00 -07001329 {
fredcbf072a72012-05-09 16:52:50 -07001330 int prevState = msg.arg1;
1331 int newState = msg.arg2;
Jeff Sharkey67609c72016-03-05 14:29:13 -07001332 if (DBG) Slog.d(TAG, "MESSAGE_BLUETOOTH_STATE_CHANGE: prevState = " + prevState + ", newState=" + newState);
Zhihai Xu40874a02012-10-08 17:57:03 -07001333 mState = newState;
1334 bluetoothStateChangeHandler(prevState, newState);
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001335 // handle error state transition case from TURNING_ON to OFF
1336 // unbind and rebind bluetooth service and enable bluetooth
Nitin Arorad055adb2015-03-02 15:03:51 -08001337 if ((prevState == BluetoothAdapter.STATE_BLE_TURNING_ON) &&
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001338 (newState == BluetoothAdapter.STATE_OFF) &&
1339 (mBluetooth != null) && mEnable) {
1340 recoverBluetoothServiceFromError();
1341 }
Nitin Arorad055adb2015-03-02 15:03:51 -08001342 if ((prevState == BluetoothAdapter.STATE_TURNING_ON) &&
1343 (newState == BluetoothAdapter.STATE_BLE_ON) &&
1344 (mBluetooth != null) && mEnable) {
1345 recoverBluetoothServiceFromError();
1346 }
1347 if (newState == BluetoothAdapter.STATE_ON ||
1348 newState == BluetoothAdapter.STATE_BLE_ON) {
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001349 // bluetooth is working, reset the counter
1350 if (mErrorRecoveryRetryCounter != 0) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001351 Slog.w(TAG, "bluetooth is recovered from error");
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001352 mErrorRecoveryRetryCounter = 0;
1353 }
1354 }
fredc649fe492012-04-19 01:07:18 -07001355 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001356 }
fredc0f420372012-04-12 00:02:00 -07001357 case MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED:
1358 {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001359 Slog.e(TAG, "MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED: " + msg.arg1);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001360 try {
1361 mBluetoothLock.writeLock().lock();
Matthew Xieddf7e472013-03-01 18:41:02 -08001362 if (msg.arg1 == SERVICE_IBLUETOOTH) {
1363 // if service is unbinded already, do nothing and return
1364 if (mBluetooth == null) break;
1365 mBluetooth = null;
1366 } else if (msg.arg1 == SERVICE_IBLUETOOTHGATT) {
1367 mBluetoothGatt = null;
1368 break;
1369 } else {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001370 Slog.e(TAG, "Bad msg.arg1: " + msg.arg1);
Matthew Xieddf7e472013-03-01 18:41:02 -08001371 break;
1372 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001373 } finally {
1374 mBluetoothLock.writeLock().unlock();
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301375 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001376
1377 if (mEnable) {
1378 mEnable = false;
1379 // Send a Bluetooth Restart message
1380 Message restartMsg = mHandler.obtainMessage(
1381 MESSAGE_RESTART_BLUETOOTH_SERVICE);
1382 mHandler.sendMessageDelayed(restartMsg,
1383 SERVICE_RESTART_TIME_MS);
1384 }
1385
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001386 sendBluetoothServiceDownCallback();
Zhihai Xu40874a02012-10-08 17:57:03 -07001387
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001388 // Send BT state broadcast to update
1389 // the BT icon correctly
1390 if ((mState == BluetoothAdapter.STATE_TURNING_ON) ||
1391 (mState == BluetoothAdapter.STATE_ON)) {
1392 bluetoothStateChangeHandler(BluetoothAdapter.STATE_ON,
1393 BluetoothAdapter.STATE_TURNING_OFF);
1394 mState = BluetoothAdapter.STATE_TURNING_OFF;
Zhihai Xu40874a02012-10-08 17:57:03 -07001395 }
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001396 if (mState == BluetoothAdapter.STATE_TURNING_OFF) {
1397 bluetoothStateChangeHandler(BluetoothAdapter.STATE_TURNING_OFF,
1398 BluetoothAdapter.STATE_OFF);
1399 }
1400
1401 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
1402 mState = BluetoothAdapter.STATE_OFF;
fredc649fe492012-04-19 01:07:18 -07001403 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001404 }
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301405 case MESSAGE_RESTART_BLUETOOTH_SERVICE:
1406 {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001407 Slog.d(TAG, "MESSAGE_RESTART_BLUETOOTH_SERVICE:"
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301408 +" Restart IBluetooth service");
1409 /* Enable without persisting the setting as
1410 it doesnt change when IBluetooth
1411 service restarts */
Zhihai Xu40874a02012-10-08 17:57:03 -07001412 mEnable = true;
Zhihai Xu401202b2012-12-03 11:36:21 -08001413 handleEnable(mQuietEnable);
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301414 break;
1415 }
1416
fredc0f420372012-04-12 00:02:00 -07001417 case MESSAGE_TIMEOUT_UNBIND:
1418 {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001419 Slog.e(TAG, "MESSAGE_TIMEOUT_UNBIND");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001420 mBluetoothLock.writeLock().lock();
1421 mUnbinding = false;
1422 mBluetoothLock.writeLock().unlock();
fredc649fe492012-04-19 01:07:18 -07001423 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001424 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001425
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001426 case MESSAGE_USER_SWITCHED: {
1427 if (DBG) Slog.d(TAG, "MESSAGE_USER_SWITCHED");
Zhihai Xu40874a02012-10-08 17:57:03 -07001428 mHandler.removeMessages(MESSAGE_USER_SWITCHED);
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001429
Zhihai Xu40874a02012-10-08 17:57:03 -07001430 /* disable and enable BT when detect a user switch */
1431 if (mEnable && mBluetooth != null) {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001432 try {
1433 mBluetoothLock.readLock().lock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001434 if (mBluetooth != null) {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001435 mBluetooth.unregisterCallback(mBluetoothCallback);
Zhihai Xu40874a02012-10-08 17:57:03 -07001436 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001437 } catch (RemoteException re) {
1438 Slog.e(TAG, "Unable to unregister", re);
1439 } finally {
1440 mBluetoothLock.readLock().unlock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001441 }
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001442
1443 if (mState == BluetoothAdapter.STATE_TURNING_OFF) {
1444 // MESSAGE_USER_SWITCHED happened right after MESSAGE_ENABLE
1445 bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_OFF);
1446 mState = BluetoothAdapter.STATE_OFF;
1447 }
1448 if (mState == BluetoothAdapter.STATE_OFF) {
1449 bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_TURNING_ON);
1450 mState = BluetoothAdapter.STATE_TURNING_ON;
1451 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001452
1453 waitForOnOff(true, false);
1454
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001455 if (mState == BluetoothAdapter.STATE_TURNING_ON) {
1456 bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_ON);
1457 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001458
Benjamin Franze8b98922014-11-12 15:57:54 +00001459 unbindAllBluetoothProfileServices();
Zhihai Xu40874a02012-10-08 17:57:03 -07001460 // disable
Zhihai Xu401202b2012-12-03 11:36:21 -08001461 handleDisable();
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001462 // Pbap service need receive STATE_TURNING_OFF intent to close
1463 bluetoothStateChangeHandler(BluetoothAdapter.STATE_ON,
1464 BluetoothAdapter.STATE_TURNING_OFF);
Zhihai Xu40874a02012-10-08 17:57:03 -07001465
1466 waitForOnOff(false, true);
1467
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001468 bluetoothStateChangeHandler(BluetoothAdapter.STATE_TURNING_OFF,
Zhihai Xu40874a02012-10-08 17:57:03 -07001469 BluetoothAdapter.STATE_OFF);
Zhihai Xu40874a02012-10-08 17:57:03 -07001470 sendBluetoothServiceDownCallback();
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001471
Pavlin Radoslavove957a8a2016-05-24 15:28:41 -07001472 try {
1473 mBluetoothLock.writeLock().lock();
1474 if (mBluetooth != null) {
1475 mBluetooth = null;
1476 // Unbind
1477 mContext.unbindService(mConnection);
1478 }
1479 mBluetoothGatt = null;
1480 } finally {
1481 mBluetoothLock.writeLock().unlock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001482 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001483
Zhihai Xu40874a02012-10-08 17:57:03 -07001484 SystemClock.sleep(100);
1485
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001486 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
1487 mState = BluetoothAdapter.STATE_OFF;
Zhihai Xu40874a02012-10-08 17:57:03 -07001488 // enable
Zhihai Xu401202b2012-12-03 11:36:21 -08001489 handleEnable(mQuietEnable);
John Spurlock8a985d22014-02-25 09:40:05 -05001490 } else if (mBinding || mBluetooth != null) {
Zhihai Xu40874a02012-10-08 17:57:03 -07001491 Message userMsg = mHandler.obtainMessage(MESSAGE_USER_SWITCHED);
1492 userMsg.arg2 = 1 + msg.arg2;
1493 // if user is switched when service is being binding
1494 // delay sending MESSAGE_USER_SWITCHED
1495 mHandler.sendMessageDelayed(userMsg, USER_SWITCHED_TIME_MS);
1496 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001497 Slog.d(TAG, "delay MESSAGE_USER_SWITCHED " + userMsg.arg2);
Zhihai Xu40874a02012-10-08 17:57:03 -07001498 }
John Spurlock8a985d22014-02-25 09:40:05 -05001499 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001500 break;
1501 }
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001502 case MESSAGE_USER_UNLOCKED: {
1503 if (DBG) Slog.d(TAG, "MESSAGE_USER_UNLOCKED");
1504 mHandler.removeMessages(MESSAGE_USER_SWITCHED);
1505
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001506 if (mEnable && !mBinding && (mBluetooth == null)) {
1507 // We should be connected, but we gave up for some
1508 // reason; maybe the Bluetooth service wasn't encryption
1509 // aware, so try binding again.
1510 if (DBG) Slog.d(TAG, "Enabled but not bound; retrying after unlock");
1511 handleEnable(mQuietEnable);
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001512 }
1513 }
fredc0f420372012-04-12 00:02:00 -07001514 }
1515 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001516 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001517
Zhihai Xu401202b2012-12-03 11:36:21 -08001518 private void handleEnable(boolean quietMode) {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001519 mQuietEnable = quietMode;
1520
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001521 try {
1522 mBluetoothLock.writeLock().lock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001523 if ((mBluetooth == null) && (!mBinding)) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001524 //Start bind timeout and bind
1525 Message timeoutMsg=mHandler.obtainMessage(MESSAGE_TIMEOUT_BIND);
1526 mHandler.sendMessageDelayed(timeoutMsg,TIMEOUT_BIND_MS);
Matthew Xiecdce0b92012-07-12 19:06:15 -07001527 Intent i = new Intent(IBluetooth.class.getName());
Dianne Hackbornce09f5a2014-10-10 15:03:13 -07001528 if (!doBind(i, mConnection,Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT,
1529 UserHandle.CURRENT)) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001530 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
Zhihai Xu40874a02012-10-08 17:57:03 -07001531 } else {
1532 mBinding = true;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001533 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001534 } else if (mBluetooth != null) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001535 //Enable bluetooth
1536 try {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001537 if (!mQuietEnable) {
1538 if(!mBluetooth.enable()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001539 Slog.e(TAG,"IBluetooth.enable() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001540 }
1541 }
1542 else {
1543 if(!mBluetooth.enableNoAutoConnect()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001544 Slog.e(TAG,"IBluetooth.enableNoAutoConnect() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001545 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001546 }
1547 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001548 Slog.e(TAG,"Unable to call enable()",e);
Matthew Xiecdce0b92012-07-12 19:06:15 -07001549 }
1550 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001551 } finally {
1552 mBluetoothLock.writeLock().unlock();
Matthew Xiecdce0b92012-07-12 19:06:15 -07001553 }
1554 }
1555
Dianne Hackborn221ea892013-08-04 16:50:16 -07001556 boolean doBind(Intent intent, ServiceConnection conn, int flags, UserHandle user) {
1557 ComponentName comp = intent.resolveSystemService(mContext.getPackageManager(), 0);
1558 intent.setComponent(comp);
1559 if (comp == null || !mContext.bindServiceAsUser(intent, conn, flags, user)) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001560 Slog.e(TAG, "Fail to bind to: " + intent);
Dianne Hackborn221ea892013-08-04 16:50:16 -07001561 return false;
1562 }
1563 return true;
1564 }
1565
Zhihai Xu401202b2012-12-03 11:36:21 -08001566 private void handleDisable() {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001567 try {
1568 mBluetoothLock.readLock().lock();
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001569 if (mBluetooth != null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001570 if (DBG) Slog.d(TAG,"Sending off request.");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001571 if (!mBluetooth.disable()) {
1572 Slog.e(TAG,"IBluetooth.disable() returned false");
Matthew Xiecdce0b92012-07-12 19:06:15 -07001573 }
1574 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001575 } catch (RemoteException e) {
1576 Slog.e(TAG,"Unable to call disable()",e);
1577 } finally {
1578 mBluetoothLock.readLock().unlock();
Matthew Xiecdce0b92012-07-12 19:06:15 -07001579 }
1580 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001581
1582 private boolean checkIfCallerIsForegroundUser() {
1583 int foregroundUser;
1584 int callingUser = UserHandle.getCallingUserId();
Martijn Coenen8385c5a2012-11-29 10:14:16 -08001585 int callingUid = Binder.getCallingUid();
Zhihai Xu40874a02012-10-08 17:57:03 -07001586 long callingIdentity = Binder.clearCallingIdentity();
Benjamin Franze8b98922014-11-12 15:57:54 +00001587 UserManager um = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
1588 UserInfo ui = um.getProfileParent(callingUser);
1589 int parentUser = (ui != null) ? ui.id : UserHandle.USER_NULL;
Martijn Coenen8385c5a2012-11-29 10:14:16 -08001590 int callingAppId = UserHandle.getAppId(callingUid);
Zhihai Xu40874a02012-10-08 17:57:03 -07001591 boolean valid = false;
1592 try {
1593 foregroundUser = ActivityManager.getCurrentUser();
Martijn Coenen8385c5a2012-11-29 10:14:16 -08001594 valid = (callingUser == foregroundUser) ||
Benjamin Franze8b98922014-11-12 15:57:54 +00001595 parentUser == foregroundUser ||
Adrian Roosbd9a9a52014-08-18 15:31:57 +02001596 callingAppId == Process.NFC_UID ||
1597 callingAppId == mSystemUiUid;
Zhihai Xu40874a02012-10-08 17:57:03 -07001598 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001599 Slog.d(TAG, "checkIfCallerIsForegroundUser: valid=" + valid
Zhihai Xu40874a02012-10-08 17:57:03 -07001600 + " callingUser=" + callingUser
Benjamin Franze8b98922014-11-12 15:57:54 +00001601 + " parentUser=" + parentUser
Zhihai Xu40874a02012-10-08 17:57:03 -07001602 + " foregroundUser=" + foregroundUser);
1603 }
1604 } finally {
1605 Binder.restoreCallingIdentity(callingIdentity);
1606 }
1607 return valid;
1608 }
1609
Nitin Arorad055adb2015-03-02 15:03:51 -08001610 private void sendBleStateChanged(int prevState, int newState) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001611 if (DBG) Slog.d(TAG,"BLE State Change Intent: " + prevState + " -> " + newState);
Nitin Arorad055adb2015-03-02 15:03:51 -08001612 // Send broadcast message to everyone else
1613 Intent intent = new Intent(BluetoothAdapter.ACTION_BLE_STATE_CHANGED);
1614 intent.putExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE, prevState);
1615 intent.putExtra(BluetoothAdapter.EXTRA_STATE, newState);
1616 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1617 mContext.sendBroadcastAsUser(intent, UserHandle.ALL, BLUETOOTH_PERM);
1618 }
1619
Zhihai Xu40874a02012-10-08 17:57:03 -07001620 private void bluetoothStateChangeHandler(int prevState, int newState) {
Nitin Arorad055adb2015-03-02 15:03:51 -08001621 boolean isStandardBroadcast = true;
Zhihai Xu40874a02012-10-08 17:57:03 -07001622 if (prevState != newState) {
1623 //Notify all proxy objects first of adapter state change
Nitin Arorad055adb2015-03-02 15:03:51 -08001624 if (newState == BluetoothAdapter.STATE_BLE_ON
1625 || newState == BluetoothAdapter.STATE_OFF) {
1626 boolean intermediate_off = (prevState == BluetoothAdapter.STATE_TURNING_OFF
1627 && newState == BluetoothAdapter.STATE_BLE_ON);
Zhihai Xu40874a02012-10-08 17:57:03 -07001628
Nitin Arorad055adb2015-03-02 15:03:51 -08001629 if (newState == BluetoothAdapter.STATE_OFF) {
1630 // If Bluetooth is off, send service down event to proxy objects, and unbind
Jeff Sharkey67609c72016-03-05 14:29:13 -07001631 if (DBG) Slog.d(TAG, "Bluetooth is complete turn off");
Pavlin Radoslavove47ec142016-06-01 22:25:18 -07001632 sendBluetoothServiceDownCallback();
1633 unbindAndFinish();
1634 sendBleStateChanged(prevState, newState);
1635 // Don't broadcast as it has already been broadcast before
1636 isStandardBroadcast = false;
Nitin Arorad055adb2015-03-02 15:03:51 -08001637
1638 } else if (!intermediate_off) {
1639 // connect to GattService
Jeff Sharkey67609c72016-03-05 14:29:13 -07001640 if (DBG) Slog.d(TAG, "Bluetooth is in LE only mode");
Nitin Arorad055adb2015-03-02 15:03:51 -08001641 if (mBluetoothGatt != null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001642 if (DBG) Slog.d(TAG, "Calling BluetoothGattServiceUp");
Nitin Arorad055adb2015-03-02 15:03:51 -08001643 onBluetoothGattServiceUp();
1644 } else {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001645 if (DBG) Slog.d(TAG, "Binding Bluetooth GATT service");
Nitin Arorad055adb2015-03-02 15:03:51 -08001646 if (mContext.getPackageManager().hasSystemFeature(
1647 PackageManager.FEATURE_BLUETOOTH_LE)) {
1648 Intent i = new Intent(IBluetoothGatt.class.getName());
1649 doBind(i, mConnection, Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT, UserHandle.CURRENT);
1650 }
1651 }
1652 sendBleStateChanged(prevState, newState);
1653 //Don't broadcase this as std intent
1654 isStandardBroadcast = false;
1655
1656 } else if (intermediate_off){
Jeff Sharkey67609c72016-03-05 14:29:13 -07001657 if (DBG) Slog.d(TAG, "Intermediate off, back to LE only mode");
Nitin Arorad055adb2015-03-02 15:03:51 -08001658 // For LE only mode, broadcast as is
1659 sendBleStateChanged(prevState, newState);
1660 sendBluetoothStateCallback(false); // BT is OFF for general users
1661 // Broadcast as STATE_OFF
1662 newState = BluetoothAdapter.STATE_OFF;
1663 sendBrEdrDownCallback();
Zhihai Xu40874a02012-10-08 17:57:03 -07001664 }
Nitin Arorad055adb2015-03-02 15:03:51 -08001665 } else if (newState == BluetoothAdapter.STATE_ON) {
1666 boolean isUp = (newState==BluetoothAdapter.STATE_ON);
1667 sendBluetoothStateCallback(isUp);
1668 sendBleStateChanged(prevState, newState);
1669
1670 } else if (newState == BluetoothAdapter.STATE_BLE_TURNING_ON
1671 || newState == BluetoothAdapter.STATE_BLE_TURNING_OFF ) {
1672 sendBleStateChanged(prevState, newState);
1673 isStandardBroadcast = false;
1674
1675 } else if (newState == BluetoothAdapter.STATE_TURNING_ON
1676 || newState == BluetoothAdapter.STATE_TURNING_OFF) {
1677 sendBleStateChanged(prevState, newState);
Zhihai Xu40874a02012-10-08 17:57:03 -07001678 }
1679
Nitin Arorad055adb2015-03-02 15:03:51 -08001680 if (isStandardBroadcast) {
1681 if (prevState == BluetoothAdapter.STATE_BLE_ON) {
1682 // Show prevState of BLE_ON as OFF to standard users
1683 prevState = BluetoothAdapter.STATE_OFF;
1684 }
1685 Intent intent = new Intent(BluetoothAdapter.ACTION_STATE_CHANGED);
1686 intent.putExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE, prevState);
1687 intent.putExtra(BluetoothAdapter.EXTRA_STATE, newState);
1688 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1689 mContext.sendBroadcastAsUser(intent, UserHandle.ALL, BLUETOOTH_PERM);
1690 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001691 }
1692 }
1693
1694 /**
1695 * if on is true, wait for state become ON
1696 * if off is true, wait for state become OFF
1697 * if both on and off are false, wait for state not ON
1698 */
1699 private boolean waitForOnOff(boolean on, boolean off) {
1700 int i = 0;
1701 while (i < 10) {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001702 try {
1703 mBluetoothLock.readLock().lock();
1704 if (mBluetooth == null) break;
1705 if (on) {
1706 if (mBluetooth.getState() == BluetoothAdapter.STATE_ON) return true;
1707 } else if (off) {
1708 if (mBluetooth.getState() == BluetoothAdapter.STATE_OFF) return true;
1709 } else {
1710 if (mBluetooth.getState() != BluetoothAdapter.STATE_ON) return true;
Zhihai Xu40874a02012-10-08 17:57:03 -07001711 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001712 } catch (RemoteException e) {
1713 Slog.e(TAG, "getState()", e);
1714 break;
1715 } finally {
1716 mBluetoothLock.readLock().unlock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001717 }
1718 if (on || off) {
1719 SystemClock.sleep(300);
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07001720 } else {
Zhihai Xu40874a02012-10-08 17:57:03 -07001721 SystemClock.sleep(50);
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07001722 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001723 i++;
1724 }
Jeff Sharkey67609c72016-03-05 14:29:13 -07001725 Slog.e(TAG,"waitForOnOff time out");
Zhihai Xu40874a02012-10-08 17:57:03 -07001726 return false;
1727 }
Zhihai Xu681ae7f2012-11-12 15:14:18 -08001728
Zhihai Xu401202b2012-12-03 11:36:21 -08001729 private void sendDisableMsg() {
1730 mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_DISABLE));
1731 }
1732
1733 private void sendEnableMsg(boolean quietMode) {
1734 mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_ENABLE,
1735 quietMode ? 1 : 0, 0));
1736 }
1737
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001738 private void recoverBluetoothServiceFromError() {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001739 Slog.e(TAG,"recoverBluetoothServiceFromError");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001740 try {
1741 mBluetoothLock.readLock().lock();
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001742 if (mBluetooth != null) {
1743 //Unregister callback object
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001744 mBluetooth.unregisterCallback(mBluetoothCallback);
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001745 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001746 } catch (RemoteException re) {
1747 Slog.e(TAG, "Unable to unregister", re);
1748 } finally {
1749 mBluetoothLock.readLock().unlock();
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001750 }
1751
1752 SystemClock.sleep(500);
1753
1754 // disable
1755 handleDisable();
1756
1757 waitForOnOff(false, true);
1758
1759 sendBluetoothServiceDownCallback();
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001760
Pavlin Radoslavove957a8a2016-05-24 15:28:41 -07001761 try {
1762 mBluetoothLock.writeLock().lock();
1763 if (mBluetooth != null) {
1764 mBluetooth = null;
1765 // Unbind
1766 mContext.unbindService(mConnection);
1767 }
1768 mBluetoothGatt = null;
1769 } finally {
1770 mBluetoothLock.writeLock().unlock();
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001771 }
1772
1773 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
1774 mState = BluetoothAdapter.STATE_OFF;
1775
1776 mEnable = false;
1777
1778 if (mErrorRecoveryRetryCounter++ < MAX_ERROR_RESTART_RETRIES) {
1779 // Send a Bluetooth Restart message to reenable bluetooth
1780 Message restartMsg = mHandler.obtainMessage(
1781 MESSAGE_RESTART_BLUETOOTH_SERVICE);
1782 mHandler.sendMessageDelayed(restartMsg, ERROR_RESTART_TIME_MS);
1783 } else {
1784 // todo: notify user to power down and power up phone to make bluetooth work.
1785 }
1786 }
Mike Lockwood726d4de2014-10-28 14:06:28 -07001787
1788 @Override
Pavlin Radoslavov6e8faff2016-02-23 11:54:37 -08001789 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1790 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DUMP, TAG);
1791 String errorMsg = null;
1792 if (mBluetoothBinder == null) {
1793 errorMsg = "Bluetooth Service not connected";
1794 } else {
1795 try {
1796 mBluetoothBinder.dump(fd, args);
1797 } catch (RemoteException re) {
1798 errorMsg = "RemoteException while calling Bluetooth Service";
1799 }
Mike Lockwood726d4de2014-10-28 14:06:28 -07001800 }
Pavlin Radoslavov6e8faff2016-02-23 11:54:37 -08001801 if (errorMsg != null) {
1802 // Silently return if we are extracting metrics in Protobuf format
1803 if ((args.length > 0) && args[0].startsWith("--proto"))
1804 return;
1805 writer.println(errorMsg);
1806 }
Mike Lockwood726d4de2014-10-28 14:06:28 -07001807 }
fredc0f420372012-04-12 00:02:00 -07001808}