blob: f30a126ba60ed14f3cb82ec5a20b1e8c608ad0cc [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 {
225 mBluetoothLock.readLock().lock();
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 }
642 // We do not honor ON requests when the adapter is already turned ON or in the process of
643 // turning ON.
644 // As a protective mechanism to make sure that the native stack gets cleaned up properly
645 // before turning it back ON we ignore requests while the bluetooth is turning OFF.
646 // Bug: b/28318203
647 if (mState == BluetoothAdapter.STATE_BLE_TURNING_OFF ||
648 mState == BluetoothAdapter.STATE_TURNING_OFF ||
649 mState == BluetoothAdapter.STATE_ON ||
650 mState == BluetoothAdapter.STATE_BLE_ON ||
651 mState == BluetoothAdapter.STATE_TURNING_ON ||
652 mState == BluetoothAdapter.STATE_BLE_TURNING_ON) {
653 return false;
Zhihai Xu401202b2012-12-03 11:36:21 -0800654 }
655
656 synchronized(mReceiver) {
657 mQuietEnableExternal = false;
658 mEnableExternal = true;
659 // waive WRITE_SECURE_SETTINGS permission check
Zhihai Xu401202b2012-12-03 11:36:21 -0800660 sendEnableMsg(false);
661 }
Jeff Sharkey67609c72016-03-05 14:29:13 -0700662 if (DBG) Slog.d(TAG, "enable returning");
Zhihai Xu401202b2012-12-03 11:36:21 -0800663 return true;
fredc0f420372012-04-12 00:02:00 -0700664 }
665
666 public boolean disable(boolean persist) {
667 mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
668 "Need BLUETOOTH ADMIN permissicacheNameAndAddresson");
Zhihai Xu40874a02012-10-08 17:57:03 -0700669
Zhihai Xu6eb76522012-11-29 15:41:04 -0800670 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
671 (!checkIfCallerIsForegroundUser())) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700672 Slog.w(TAG,"disable(): not allowed for non-active and non system user");
Zhihai Xu40874a02012-10-08 17:57:03 -0700673 return false;
674 }
675
fredcf2458862012-04-16 15:18:27 -0700676 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700677 Slog.d(TAG,"disable(): mBluetooth = " + mBluetooth +
Matthew Xiecdce0b92012-07-12 19:06:15 -0700678 " mBinding = " + mBinding);
679 }
fredcf2458862012-04-16 15:18:27 -0700680
Zhihai Xu401202b2012-12-03 11:36:21 -0800681 synchronized(mReceiver) {
682 if (persist) {
683 // waive WRITE_SECURE_SETTINGS permission check
684 long callingIdentity = Binder.clearCallingIdentity();
685 persistBluetoothSetting(BLUETOOTH_OFF);
686 Binder.restoreCallingIdentity(callingIdentity);
687 }
688 mEnableExternal = false;
689 sendDisableMsg();
690 }
fredc0f420372012-04-12 00:02:00 -0700691 return true;
692 }
693
fredc649fe492012-04-19 01:07:18 -0700694 public void unbindAndFinish() {
fredcf2458862012-04-16 15:18:27 -0700695 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700696 Slog.d(TAG,"unbindAndFinish(): " + mBluetooth +
Matthew Xiecdce0b92012-07-12 19:06:15 -0700697 " mBinding = " + mBinding);
fredcf2458862012-04-16 15:18:27 -0700698 }
699
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700700 try {
701 mBluetoothLock.writeLock().lock();
fredc0f420372012-04-12 00:02:00 -0700702 if (mUnbinding) return;
703 mUnbinding = true;
Zhihai Xu40874a02012-10-08 17:57:03 -0700704 if (mBluetooth != null) {
Andre Eisenbach305fdab2015-11-11 21:43:26 -0800705 //Unregister callback object
706 try {
707 mBluetooth.unregisterCallback(mBluetoothCallback);
708 } catch (RemoteException re) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700709 Slog.e(TAG, "Unable to unregister BluetoothCallback",re);
fredcbf072a72012-05-09 16:52:50 -0700710 }
Andre Eisenbach305fdab2015-11-11 21:43:26 -0800711
Jeff Sharkey67609c72016-03-05 14:29:13 -0700712 if (DBG) Slog.d(TAG, "Sending unbind request.");
Marie Janssen9db28eb2016-01-12 16:05:15 -0800713 mBluetoothBinder = null;
fredcd6883532012-04-25 17:46:13 -0700714 mBluetooth = null;
715 //Unbind
fredc0f420372012-04-12 00:02:00 -0700716 mContext.unbindService(mConnection);
fredcd6883532012-04-25 17:46:13 -0700717 mUnbinding = false;
Zhihai Xu40874a02012-10-08 17:57:03 -0700718 mBinding = false;
fredcf2458862012-04-16 15:18:27 -0700719 } else {
720 mUnbinding=false;
fredc0f420372012-04-12 00:02:00 -0700721 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800722 mBluetoothGatt = null;
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700723 } finally {
724 mBluetoothLock.writeLock().unlock();
fredc0f420372012-04-12 00:02:00 -0700725 }
726 }
727
Matthew Xieddf7e472013-03-01 18:41:02 -0800728 public IBluetoothGatt getBluetoothGatt() {
729 // sync protection
730 return mBluetoothGatt;
731 }
732
Benjamin Franze8b98922014-11-12 15:57:54 +0000733 @Override
734 public boolean bindBluetoothProfileService(int bluetoothProfile,
735 IBluetoothProfileServiceConnection proxy) {
736 if (!mEnable) {
737 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700738 Slog.d(TAG, "Trying to bind to profile: " + bluetoothProfile +
Benjamin Franze8b98922014-11-12 15:57:54 +0000739 ", while Bluetooth was disabled");
740 }
741 return false;
742 }
743 synchronized (mProfileServices) {
744 ProfileServiceConnections psc = mProfileServices.get(new Integer(bluetoothProfile));
745 if (psc == null) {
746 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700747 Slog.d(TAG, "Creating new ProfileServiceConnections object for"
Benjamin Franze8b98922014-11-12 15:57:54 +0000748 + " profile: " + bluetoothProfile);
749 }
Benjamin Franz5b614592014-12-09 18:58:45 +0000750
751 if (bluetoothProfile != BluetoothProfile.HEADSET) return false;
752
753 Intent intent = new Intent(IBluetoothHeadset.class.getName());
Benjamin Franze8b98922014-11-12 15:57:54 +0000754 psc = new ProfileServiceConnections(intent);
Benjamin Franz5b614592014-12-09 18:58:45 +0000755 if (!psc.bindService()) return false;
756
Benjamin Franze8b98922014-11-12 15:57:54 +0000757 mProfileServices.put(new Integer(bluetoothProfile), psc);
Benjamin Franze8b98922014-11-12 15:57:54 +0000758 }
759 }
760
761 // Introducing a delay to give the client app time to prepare
762 Message addProxyMsg = mHandler.obtainMessage(MESSAGE_ADD_PROXY_DELAYED);
763 addProxyMsg.arg1 = bluetoothProfile;
764 addProxyMsg.obj = proxy;
765 mHandler.sendMessageDelayed(addProxyMsg, ADD_PROXY_DELAY_MS);
766 return true;
767 }
768
769 @Override
770 public void unbindBluetoothProfileService(int bluetoothProfile,
771 IBluetoothProfileServiceConnection proxy) {
772 synchronized (mProfileServices) {
773 ProfileServiceConnections psc = mProfileServices.get(new Integer(bluetoothProfile));
774 if (psc == null) {
775 return;
776 }
777 psc.removeProxy(proxy);
778 }
779 }
780
781 private void unbindAllBluetoothProfileServices() {
782 synchronized (mProfileServices) {
783 for (Integer i : mProfileServices.keySet()) {
784 ProfileServiceConnections psc = mProfileServices.get(i);
Benjamin Franz5b614592014-12-09 18:58:45 +0000785 try {
786 mContext.unbindService(psc);
787 } catch (IllegalArgumentException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700788 Slog.e(TAG, "Unable to unbind service with intent: " + psc.mIntent, e);
Benjamin Franz5b614592014-12-09 18:58:45 +0000789 }
Benjamin Franze8b98922014-11-12 15:57:54 +0000790 psc.removeAllProxies();
791 }
792 mProfileServices.clear();
793 }
794 }
795
796 /**
Miao Chou658bf2f2015-06-26 17:14:35 -0700797 * Send enable message and set adapter name and address. Called when the boot phase becomes
798 * PHASE_SYSTEM_SERVICES_READY.
799 */
800 public void handleOnBootPhase() {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700801 if (DBG) Slog.d(TAG, "Bluetooth boot completed");
Miao Chou658bf2f2015-06-26 17:14:35 -0700802 if (mEnableExternal && isBluetoothPersistedStateOnBluetooth()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700803 if (DBG) Slog.d(TAG, "Auto-enabling Bluetooth.");
Miao Chou658bf2f2015-06-26 17:14:35 -0700804 sendEnableMsg(mQuietEnableExternal);
Ajay Panickerbf796d82016-03-11 13:47:20 -0800805 } else if (!isNameAndAddressSet()) {
806 if (DBG) Slog.d(TAG, "Getting adapter name and address");
Ajay Panicker4bb48302016-03-31 14:14:27 -0700807 Message getMsg = mHandler.obtainMessage(MESSAGE_GET_NAME_AND_ADDRESS);
808 mHandler.sendMessage(getMsg);
Miao Chou658bf2f2015-06-26 17:14:35 -0700809 }
Miao Chou658bf2f2015-06-26 17:14:35 -0700810 }
811
812 /**
813 * Called when switching to a different foreground user.
814 */
815 public void handleOnSwitchUser(int userHandle) {
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -0700816 if (DBG) Slog.d(TAG, "User " + userHandle + " switched");
817 mHandler.obtainMessage(MESSAGE_USER_SWITCHED, userHandle, 0).sendToTarget();
818 }
819
820 /**
821 * Called when user is unlocked.
822 */
823 public void handleOnUnlockUser(int userHandle) {
824 if (DBG) Slog.d(TAG, "User " + userHandle + " unlocked");
825 mHandler.obtainMessage(MESSAGE_USER_UNLOCKED, userHandle, 0).sendToTarget();
Miao Chou658bf2f2015-06-26 17:14:35 -0700826 }
827
828 /**
Benjamin Franze8b98922014-11-12 15:57:54 +0000829 * This class manages the clients connected to a given ProfileService
830 * and maintains the connection with that service.
831 */
832 final private class ProfileServiceConnections implements ServiceConnection,
833 IBinder.DeathRecipient {
834 final RemoteCallbackList<IBluetoothProfileServiceConnection> mProxies =
835 new RemoteCallbackList <IBluetoothProfileServiceConnection>();
836 IBinder mService;
837 ComponentName mClassName;
838 Intent mIntent;
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700839 boolean mInvokingProxyCallbacks = false;
Benjamin Franze8b98922014-11-12 15:57:54 +0000840
841 ProfileServiceConnections(Intent intent) {
842 mService = null;
843 mClassName = null;
844 mIntent = intent;
845 }
846
Benjamin Franz5b614592014-12-09 18:58:45 +0000847 private boolean bindService() {
848 if (mIntent != null && mService == null &&
849 doBind(mIntent, this, 0, UserHandle.CURRENT_OR_SELF)) {
Benjamin Franze8b98922014-11-12 15:57:54 +0000850 Message msg = mHandler.obtainMessage(MESSAGE_BIND_PROFILE_SERVICE);
851 msg.obj = this;
852 mHandler.sendMessageDelayed(msg, TIMEOUT_BIND_MS);
Benjamin Franz5b614592014-12-09 18:58:45 +0000853 return true;
Benjamin Franze8b98922014-11-12 15:57:54 +0000854 }
Jeff Sharkey67609c72016-03-05 14:29:13 -0700855 Slog.w(TAG, "Unable to bind with intent: " + mIntent);
Benjamin Franz5b614592014-12-09 18:58:45 +0000856 return false;
Benjamin Franze8b98922014-11-12 15:57:54 +0000857 }
858
859 private void addProxy(IBluetoothProfileServiceConnection proxy) {
860 mProxies.register(proxy);
861 if (mService != null) {
862 try{
863 proxy.onServiceConnected(mClassName, mService);
864 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700865 Slog.e(TAG, "Unable to connect to proxy", e);
Benjamin Franze8b98922014-11-12 15:57:54 +0000866 }
867 } else {
868 if (!mHandler.hasMessages(MESSAGE_BIND_PROFILE_SERVICE, this)) {
869 Message msg = mHandler.obtainMessage(MESSAGE_BIND_PROFILE_SERVICE);
870 msg.obj = this;
871 mHandler.sendMessage(msg);
872 }
873 }
874 }
875
876 private void removeProxy(IBluetoothProfileServiceConnection proxy) {
877 if (proxy != null) {
878 if (mProxies.unregister(proxy)) {
879 try {
880 proxy.onServiceDisconnected(mClassName);
881 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700882 Slog.e(TAG, "Unable to disconnect proxy", e);
Benjamin Franze8b98922014-11-12 15:57:54 +0000883 }
884 }
885 } else {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700886 Slog.w(TAG, "Trying to remove a null proxy");
Benjamin Franze8b98922014-11-12 15:57:54 +0000887 }
888 }
889
890 private void removeAllProxies() {
891 onServiceDisconnected(mClassName);
892 mProxies.kill();
893 }
894
895 @Override
896 public void onServiceConnected(ComponentName className, IBinder service) {
897 // remove timeout message
898 mHandler.removeMessages(MESSAGE_BIND_PROFILE_SERVICE, this);
899 mService = service;
900 mClassName = className;
901 try {
902 mService.linkToDeath(this, 0);
903 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700904 Slog.e(TAG, "Unable to linkToDeath", e);
Benjamin Franze8b98922014-11-12 15:57:54 +0000905 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700906
907 if (mInvokingProxyCallbacks) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700908 Slog.e(TAG, "Proxy callbacks already in progress.");
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700909 return;
Benjamin Franze8b98922014-11-12 15:57:54 +0000910 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700911 mInvokingProxyCallbacks = true;
912
913 final int n = mProxies.beginBroadcast();
914 try {
915 for (int i = 0; i < n; i++) {
916 try {
917 mProxies.getBroadcastItem(i).onServiceConnected(className, service);
918 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700919 Slog.e(TAG, "Unable to connect to proxy", e);
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700920 }
921 }
922 } finally {
923 mProxies.finishBroadcast();
924 mInvokingProxyCallbacks = false;
925 }
Benjamin Franze8b98922014-11-12 15:57:54 +0000926 }
927
928 @Override
929 public void onServiceDisconnected(ComponentName className) {
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700930 if (mService == null) return;
Benjamin Franze8b98922014-11-12 15:57:54 +0000931 mService.unlinkToDeath(this, 0);
932 mService = null;
933 mClassName = null;
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700934
935 if (mInvokingProxyCallbacks) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700936 Slog.e(TAG, "Proxy callbacks already in progress.");
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700937 return;
Benjamin Franze8b98922014-11-12 15:57:54 +0000938 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700939 mInvokingProxyCallbacks = true;
940
941 final int n = mProxies.beginBroadcast();
942 try {
943 for (int i = 0; i < n; i++) {
944 try {
945 mProxies.getBroadcastItem(i).onServiceDisconnected(className);
946 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700947 Slog.e(TAG, "Unable to disconnect from proxy", e);
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700948 }
949 }
950 } finally {
951 mProxies.finishBroadcast();
952 mInvokingProxyCallbacks = false;
953 }
Benjamin Franze8b98922014-11-12 15:57:54 +0000954 }
955
956 @Override
957 public void binderDied() {
958 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700959 Slog.w(TAG, "Profile service for profile: " + mClassName
Benjamin Franze8b98922014-11-12 15:57:54 +0000960 + " died.");
961 }
962 onServiceDisconnected(mClassName);
963 // Trigger rebind
964 Message msg = mHandler.obtainMessage(MESSAGE_BIND_PROFILE_SERVICE);
965 msg.obj = this;
966 mHandler.sendMessageDelayed(msg, TIMEOUT_BIND_MS);
967 }
968 }
969
fredcbf072a72012-05-09 16:52:50 -0700970 private void sendBluetoothStateCallback(boolean isUp) {
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700971 try {
972 int n = mStateChangeCallbacks.beginBroadcast();
Jeff Sharkey67609c72016-03-05 14:29:13 -0700973 if (DBG) Slog.d(TAG,"Broadcasting onBluetoothStateChange("+isUp+") to " + n + " receivers.");
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700974 for (int i=0; i <n;i++) {
975 try {
976 mStateChangeCallbacks.getBroadcastItem(i).onBluetoothStateChange(isUp);
977 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700978 Slog.e(TAG, "Unable to call onBluetoothStateChange() on callback #" + i , e);
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700979 }
fredcbf072a72012-05-09 16:52:50 -0700980 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700981 } finally {
982 mStateChangeCallbacks.finishBroadcast();
fredcbf072a72012-05-09 16:52:50 -0700983 }
fredcbf072a72012-05-09 16:52:50 -0700984 }
985
986 /**
Zhihai Xu40874a02012-10-08 17:57:03 -0700987 * Inform BluetoothAdapter instances that Adapter service is up
988 */
989 private void sendBluetoothServiceUpCallback() {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700990 if (DBG) Slog.d(TAG,"Calling onBluetoothServiceUp callbacks");
Andre Eisenbach305fdab2015-11-11 21:43:26 -0800991 try {
992 int n = mCallbacks.beginBroadcast();
Jeff Sharkey67609c72016-03-05 14:29:13 -0700993 Slog.d(TAG,"Broadcasting onBluetoothServiceUp() to " + n + " receivers.");
Andre Eisenbach305fdab2015-11-11 21:43:26 -0800994 for (int i=0; i <n;i++) {
995 try {
996 mCallbacks.getBroadcastItem(i).onBluetoothServiceUp(mBluetooth);
997 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700998 Slog.e(TAG, "Unable to call onBluetoothServiceUp() on callback #" + i, e);
Zhihai Xu40874a02012-10-08 17:57:03 -0700999 }
1000 }
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001001 } finally {
1002 mCallbacks.finishBroadcast();
Zhihai Xu40874a02012-10-08 17:57:03 -07001003 }
1004 }
1005 /**
fredcbf072a72012-05-09 16:52:50 -07001006 * Inform BluetoothAdapter instances that Adapter service is down
1007 */
1008 private void sendBluetoothServiceDownCallback() {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001009 if (DBG) Slog.d(TAG,"Calling onBluetoothServiceDown callbacks");
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001010 try {
1011 int n = mCallbacks.beginBroadcast();
Jeff Sharkey67609c72016-03-05 14:29:13 -07001012 Slog.d(TAG,"Broadcasting onBluetoothServiceDown() to " + n + " receivers.");
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001013 for (int i=0; i <n;i++) {
1014 try {
1015 mCallbacks.getBroadcastItem(i).onBluetoothServiceDown();
1016 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001017 Slog.e(TAG, "Unable to call onBluetoothServiceDown() on callback #" + i, e);
fredcd6883532012-04-25 17:46:13 -07001018 }
1019 }
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001020 } finally {
1021 mCallbacks.finishBroadcast();
fredcd6883532012-04-25 17:46:13 -07001022 }
1023 }
Svet Ganov408abf72015-05-12 19:13:36 -07001024
fredc0f420372012-04-12 00:02:00 -07001025 public String getAddress() {
Matthew Xieaf5ddbf2012-12-04 10:47:43 -08001026 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
Svet Ganov408abf72015-05-12 19:13:36 -07001027 "Need BLUETOOTH permission");
Zhihai Xu40874a02012-10-08 17:57:03 -07001028
Zhihai Xu6eb76522012-11-29 15:41:04 -08001029 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
Svet Ganov408abf72015-05-12 19:13:36 -07001030 (!checkIfCallerIsForegroundUser())) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001031 Slog.w(TAG,"getAddress(): not allowed for non-active and non system user");
Zhihai Xu6eb76522012-11-29 15:41:04 -08001032 return null;
Zhihai Xu40874a02012-10-08 17:57:03 -07001033 }
1034
Svet Ganov408abf72015-05-12 19:13:36 -07001035 if (mContext.checkCallingOrSelfPermission(Manifest.permission.LOCAL_MAC_ADDRESS)
1036 != PackageManager.PERMISSION_GRANTED) {
1037 return BluetoothAdapter.DEFAULT_MAC_ADDRESS;
1038 }
1039
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001040 try {
1041 mBluetoothLock.readLock().lock();
1042 if (mBluetooth != null) return mBluetooth.getAddress();
1043 } catch (RemoteException e) {
1044 Slog.e(TAG, "getAddress(): Unable to retrieve address remotely. Returning cached address", e);
1045 } finally {
1046 mBluetoothLock.readLock().unlock();
fredc116d1d462012-04-20 14:47:08 -07001047 }
Ajay Panickerbf796d82016-03-11 13:47:20 -08001048
Matthew Xiecdce0b92012-07-12 19:06:15 -07001049 // mAddress is accessed from outside.
1050 // It is alright without a lock. Here, bluetooth is off, no other thread is
1051 // changing mAddress
fredc0f420372012-04-12 00:02:00 -07001052 return mAddress;
1053 }
fredc649fe492012-04-19 01:07:18 -07001054
fredc0f420372012-04-12 00:02:00 -07001055 public String getName() {
Matthew Xieaf5ddbf2012-12-04 10:47:43 -08001056 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
1057 "Need BLUETOOTH permission");
Zhihai Xu40874a02012-10-08 17:57:03 -07001058
Zhihai Xu6eb76522012-11-29 15:41:04 -08001059 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
1060 (!checkIfCallerIsForegroundUser())) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001061 Slog.w(TAG,"getName(): not allowed for non-active and non system user");
Zhihai Xu6eb76522012-11-29 15:41:04 -08001062 return null;
Zhihai Xu40874a02012-10-08 17:57:03 -07001063 }
1064
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001065 try {
1066 mBluetoothLock.readLock().lock();
1067 if (mBluetooth != null) return mBluetooth.getName();
1068 } catch (RemoteException e) {
1069 Slog.e(TAG, "getName(): Unable to retrieve name remotely. Returning cached name", e);
1070 } finally {
1071 mBluetoothLock.readLock().unlock();
fredc116d1d462012-04-20 14:47:08 -07001072 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001073
Matthew Xiecdce0b92012-07-12 19:06:15 -07001074 // mName is accessed from outside.
1075 // It alright without a lock. Here, bluetooth is off, no other thread is
1076 // changing mName
fredc0f420372012-04-12 00:02:00 -07001077 return mName;
1078 }
1079
fredc0f420372012-04-12 00:02:00 -07001080 private class BluetoothServiceConnection implements ServiceConnection {
fredc0f420372012-04-12 00:02:00 -07001081 public void onServiceConnected(ComponentName className, IBinder service) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001082 if (DBG) Slog.d(TAG, "BluetoothServiceConnection: " + className.getClassName());
fredc0f420372012-04-12 00:02:00 -07001083 Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_SERVICE_CONNECTED);
Matthew Xieddf7e472013-03-01 18:41:02 -08001084 // TBD if (className.getClassName().equals(IBluetooth.class.getName())) {
1085 if (className.getClassName().equals("com.android.bluetooth.btservice.AdapterService")) {
1086 msg.arg1 = SERVICE_IBLUETOOTH;
1087 // } else if (className.getClassName().equals(IBluetoothGatt.class.getName())) {
1088 } else if (className.getClassName().equals("com.android.bluetooth.gatt.GattService")) {
1089 msg.arg1 = SERVICE_IBLUETOOTHGATT;
1090 } else {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001091 Slog.e(TAG, "Unknown service connected: " + className.getClassName());
Matthew Xieddf7e472013-03-01 18:41:02 -08001092 return;
1093 }
fredc0f420372012-04-12 00:02:00 -07001094 msg.obj = service;
1095 mHandler.sendMessage(msg);
1096 }
1097
1098 public void onServiceDisconnected(ComponentName className) {
fredc0f420372012-04-12 00:02:00 -07001099 // Called if we unexpected disconnected.
Jeff Sharkey67609c72016-03-05 14:29:13 -07001100 if (DBG) Slog.d(TAG, "BluetoothServiceConnection, disconnected: " +
Matthew Xieddf7e472013-03-01 18:41:02 -08001101 className.getClassName());
fredc0f420372012-04-12 00:02:00 -07001102 Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED);
Matthew Xieddf7e472013-03-01 18:41:02 -08001103 if (className.getClassName().equals("com.android.bluetooth.btservice.AdapterService")) {
1104 msg.arg1 = SERVICE_IBLUETOOTH;
1105 } else if (className.getClassName().equals("com.android.bluetooth.gatt.GattService")) {
1106 msg.arg1 = SERVICE_IBLUETOOTHGATT;
1107 } else {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001108 Slog.e(TAG, "Unknown service disconnected: " + className.getClassName());
Matthew Xieddf7e472013-03-01 18:41:02 -08001109 return;
1110 }
fredc0f420372012-04-12 00:02:00 -07001111 mHandler.sendMessage(msg);
1112 }
1113 }
1114
1115 private BluetoothServiceConnection mConnection = new BluetoothServiceConnection();
1116
Zhihai Xu40874a02012-10-08 17:57:03 -07001117 private class BluetoothHandler extends Handler {
Ajay Panicker4bb48302016-03-31 14:14:27 -07001118 boolean mGetNameAddressOnly = false;
1119
Zhihai Xu40874a02012-10-08 17:57:03 -07001120 public BluetoothHandler(Looper looper) {
1121 super(looper);
1122 }
1123
fredc0f420372012-04-12 00:02:00 -07001124 @Override
1125 public void handleMessage(Message msg) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001126 if (DBG) Slog.d (TAG, "Message: " + msg.what);
fredc0f420372012-04-12 00:02:00 -07001127 switch (msg.what) {
Ajay Panicker4bb48302016-03-31 14:14:27 -07001128 case MESSAGE_GET_NAME_AND_ADDRESS:
1129 if (DBG) Slog.d(TAG, "MESSAGE_GET_NAME_AND_ADDRESS");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001130 try {
1131 mBluetoothLock.writeLock().lock();
Ajay Panicker4bb48302016-03-31 14:14:27 -07001132 if ((mBluetooth == null) && (!mBinding)) {
1133 if (DBG) Slog.d(TAG, "Binding to service to get name and address");
1134 mGetNameAddressOnly = true;
1135 Message timeoutMsg = mHandler.obtainMessage(MESSAGE_TIMEOUT_BIND);
1136 mHandler.sendMessageDelayed(timeoutMsg, TIMEOUT_BIND_MS);
1137 Intent i = new Intent(IBluetooth.class.getName());
1138 if (!doBind(i, mConnection,
1139 Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT,
1140 UserHandle.CURRENT)) {
1141 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
1142 } else {
1143 mBinding = true;
1144 }
1145 } else if (mBluetooth != null) {
1146 try {
1147 storeNameAndAddress(mBluetooth.getName(),
1148 mBluetooth.getAddress());
1149 } catch (RemoteException re) {
1150 Slog.e(TAG, "Unable to grab names", re);
1151 }
1152 if (mGetNameAddressOnly && !mEnable) {
1153 unbindAndFinish();
1154 }
1155 mGetNameAddressOnly = false;
1156 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001157 } finally {
1158 mBluetoothLock.writeLock().unlock();
Ajay Panicker4bb48302016-03-31 14:14:27 -07001159 }
1160 break;
1161
Matthew Xiecdce0b92012-07-12 19:06:15 -07001162 case MESSAGE_ENABLE:
fredcf2458862012-04-16 15:18:27 -07001163 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001164 Slog.d(TAG, "MESSAGE_ENABLE: mBluetooth = " + mBluetooth);
fredc649fe492012-04-19 01:07:18 -07001165 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001166 mHandler.removeMessages(MESSAGE_RESTART_BLUETOOTH_SERVICE);
1167 mEnable = true;
Zhihai Xu401202b2012-12-03 11:36:21 -08001168 handleEnable(msg.arg1 == 1);
fredc649fe492012-04-19 01:07:18 -07001169 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001170
fredc0f420372012-04-12 00:02:00 -07001171 case MESSAGE_DISABLE:
Zhihai Xu40874a02012-10-08 17:57:03 -07001172 mHandler.removeMessages(MESSAGE_RESTART_BLUETOOTH_SERVICE);
1173 if (mEnable && mBluetooth != null) {
1174 waitForOnOff(true, false);
1175 mEnable = false;
Zhihai Xu401202b2012-12-03 11:36:21 -08001176 handleDisable();
Zhihai Xu40874a02012-10-08 17:57:03 -07001177 waitForOnOff(false, false);
1178 } else {
1179 mEnable = false;
Zhihai Xu401202b2012-12-03 11:36:21 -08001180 handleDisable();
Zhihai Xu40874a02012-10-08 17:57:03 -07001181 }
fredc0f420372012-04-12 00:02:00 -07001182 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001183
fredc0f420372012-04-12 00:02:00 -07001184 case MESSAGE_REGISTER_ADAPTER:
1185 {
1186 IBluetoothManagerCallback callback = (IBluetoothManagerCallback) msg.obj;
fredcd6883532012-04-25 17:46:13 -07001187 boolean added = mCallbacks.register(callback);
Jeff Sharkey67609c72016-03-05 14:29:13 -07001188 Slog.d(TAG,"Added callback: " + (callback == null? "null": callback) +":" +added );
fredc0f420372012-04-12 00:02:00 -07001189 }
1190 break;
1191 case MESSAGE_UNREGISTER_ADAPTER:
1192 {
1193 IBluetoothManagerCallback callback = (IBluetoothManagerCallback) msg.obj;
fredcd6883532012-04-25 17:46:13 -07001194 boolean removed = mCallbacks.unregister(callback);
Jeff Sharkey67609c72016-03-05 14:29:13 -07001195 Slog.d(TAG,"Removed callback: " + (callback == null? "null": callback) +":" + removed);
fredc0f420372012-04-12 00:02:00 -07001196 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001197 }
fredc0f420372012-04-12 00:02:00 -07001198 case MESSAGE_REGISTER_STATE_CHANGE_CALLBACK:
1199 {
1200 IBluetoothStateChangeCallback callback = (IBluetoothStateChangeCallback) msg.obj;
Matthew Xie9b693992013-10-10 11:21:40 -07001201 if (callback != null) {
1202 mStateChangeCallbacks.register(callback);
1203 }
fredc0f420372012-04-12 00:02:00 -07001204 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001205 }
fredc0f420372012-04-12 00:02:00 -07001206 case MESSAGE_UNREGISTER_STATE_CHANGE_CALLBACK:
1207 {
1208 IBluetoothStateChangeCallback callback = (IBluetoothStateChangeCallback) msg.obj;
Matthew Xie9b693992013-10-10 11:21:40 -07001209 if (callback != null) {
1210 mStateChangeCallbacks.unregister(callback);
1211 }
fredc0f420372012-04-12 00:02:00 -07001212 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001213 }
Benjamin Franze8b98922014-11-12 15:57:54 +00001214 case MESSAGE_ADD_PROXY_DELAYED:
1215 {
1216 ProfileServiceConnections psc = mProfileServices.get(
1217 new Integer(msg.arg1));
1218 if (psc == null) {
1219 break;
1220 }
1221 IBluetoothProfileServiceConnection proxy =
1222 (IBluetoothProfileServiceConnection) msg.obj;
1223 psc.addProxy(proxy);
1224 break;
1225 }
1226 case MESSAGE_BIND_PROFILE_SERVICE:
1227 {
1228 ProfileServiceConnections psc = (ProfileServiceConnections) msg.obj;
1229 removeMessages(MESSAGE_BIND_PROFILE_SERVICE, msg.obj);
1230 if (psc == null) {
1231 break;
1232 }
1233 psc.bindService();
1234 break;
1235 }
fredc0f420372012-04-12 00:02:00 -07001236 case MESSAGE_BLUETOOTH_SERVICE_CONNECTED:
1237 {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001238 if (DBG) Slog.d(TAG,"MESSAGE_BLUETOOTH_SERVICE_CONNECTED: " + msg.arg1);
fredc0f420372012-04-12 00:02:00 -07001239
1240 IBinder service = (IBinder) msg.obj;
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001241 try {
1242 mBluetoothLock.writeLock().lock();
Matthew Xieddf7e472013-03-01 18:41:02 -08001243 if (msg.arg1 == SERVICE_IBLUETOOTHGATT) {
1244 mBluetoothGatt = IBluetoothGatt.Stub.asInterface(service);
Nitin Arorad055adb2015-03-02 15:03:51 -08001245 onBluetoothGattServiceUp();
Matthew Xieddf7e472013-03-01 18:41:02 -08001246 break;
1247 } // else must be SERVICE_IBLUETOOTH
1248
1249 //Remove timeout
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001250 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
Matthew Xieddf7e472013-03-01 18:41:02 -08001251
fredc0f420372012-04-12 00:02:00 -07001252 mBinding = false;
Marie Janssen9db28eb2016-01-12 16:05:15 -08001253 mBluetoothBinder = service;
fredc0f420372012-04-12 00:02:00 -07001254 mBluetooth = IBluetooth.Stub.asInterface(service);
fredc0f420372012-04-12 00:02:00 -07001255
Ajay Panicker4bb48302016-03-31 14:14:27 -07001256 if (!isNameAndAddressSet()) {
1257 Message getMsg = mHandler.obtainMessage(MESSAGE_GET_NAME_AND_ADDRESS);
1258 mHandler.sendMessage(getMsg);
1259 if (mGetNameAddressOnly) return;
1260 }
1261
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001262 try {
1263 boolean enableHciSnoopLog = (Settings.Secure.getInt(mContentResolver,
1264 Settings.Secure.BLUETOOTH_HCI_LOG, 0) == 1);
1265 if (!mBluetooth.configHciSnoopLog(enableHciSnoopLog)) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001266 Slog.e(TAG,"IBluetooth.configHciSnoopLog return false");
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001267 }
1268 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001269 Slog.e(TAG,"Unable to call configHciSnoopLog", e);
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001270 }
1271
Matthew Xiecdce0b92012-07-12 19:06:15 -07001272 //Register callback object
fredcbf072a72012-05-09 16:52:50 -07001273 try {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001274 mBluetooth.registerCallback(mBluetoothCallback);
1275 } catch (RemoteException re) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001276 Slog.e(TAG, "Unable to register BluetoothCallback",re);
fredcbf072a72012-05-09 16:52:50 -07001277 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001278 //Inform BluetoothAdapter instances that service is up
Zhihai Xu40874a02012-10-08 17:57:03 -07001279 sendBluetoothServiceUpCallback();
1280
Matthew Xiecdce0b92012-07-12 19:06:15 -07001281 //Do enable request
1282 try {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001283 if (mQuietEnable == false) {
1284 if(!mBluetooth.enable()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001285 Slog.e(TAG,"IBluetooth.enable() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001286 }
1287 }
1288 else
1289 {
1290 if(!mBluetooth.enableNoAutoConnect()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001291 Slog.e(TAG,"IBluetooth.enableNoAutoConnect() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001292 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001293 }
1294 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001295 Slog.e(TAG,"Unable to call enable()",e);
Matthew Xiecdce0b92012-07-12 19:06:15 -07001296 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001297 } finally {
1298 mBluetoothLock.writeLock().unlock();
Freda8c6df02012-07-11 10:25:23 -07001299 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001300
1301 if (!mEnable) {
1302 waitForOnOff(true, false);
Zhihai Xu401202b2012-12-03 11:36:21 -08001303 handleDisable();
Zhihai Xu40874a02012-10-08 17:57:03 -07001304 waitForOnOff(false, false);
1305 }
fredc649fe492012-04-19 01:07:18 -07001306 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001307 }
fredc649fe492012-04-19 01:07:18 -07001308 case MESSAGE_TIMEOUT_BIND: {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001309 Slog.e(TAG, "MESSAGE_TIMEOUT_BIND");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001310 mBluetoothLock.writeLock().lock();
1311 mBinding = false;
1312 mBluetoothLock.writeLock().unlock();
1313
fredc649fe492012-04-19 01:07:18 -07001314 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001315 }
fredcbf072a72012-05-09 16:52:50 -07001316 case MESSAGE_BLUETOOTH_STATE_CHANGE:
fredc0f420372012-04-12 00:02:00 -07001317 {
fredcbf072a72012-05-09 16:52:50 -07001318 int prevState = msg.arg1;
1319 int newState = msg.arg2;
Jeff Sharkey67609c72016-03-05 14:29:13 -07001320 if (DBG) Slog.d(TAG, "MESSAGE_BLUETOOTH_STATE_CHANGE: prevState = " + prevState + ", newState=" + newState);
Zhihai Xu40874a02012-10-08 17:57:03 -07001321 mState = newState;
1322 bluetoothStateChangeHandler(prevState, newState);
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001323 // handle error state transition case from TURNING_ON to OFF
1324 // unbind and rebind bluetooth service and enable bluetooth
Nitin Arorad055adb2015-03-02 15:03:51 -08001325 if ((prevState == BluetoothAdapter.STATE_BLE_TURNING_ON) &&
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001326 (newState == BluetoothAdapter.STATE_OFF) &&
1327 (mBluetooth != null) && mEnable) {
1328 recoverBluetoothServiceFromError();
1329 }
Nitin Arorad055adb2015-03-02 15:03:51 -08001330 if ((prevState == BluetoothAdapter.STATE_TURNING_ON) &&
1331 (newState == BluetoothAdapter.STATE_BLE_ON) &&
1332 (mBluetooth != null) && mEnable) {
1333 recoverBluetoothServiceFromError();
1334 }
1335 if (newState == BluetoothAdapter.STATE_ON ||
1336 newState == BluetoothAdapter.STATE_BLE_ON) {
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001337 // bluetooth is working, reset the counter
1338 if (mErrorRecoveryRetryCounter != 0) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001339 Slog.w(TAG, "bluetooth is recovered from error");
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001340 mErrorRecoveryRetryCounter = 0;
1341 }
1342 }
fredc649fe492012-04-19 01:07:18 -07001343 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001344 }
fredc0f420372012-04-12 00:02:00 -07001345 case MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED:
1346 {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001347 Slog.e(TAG, "MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED: " + msg.arg1);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001348 try {
1349 mBluetoothLock.writeLock().lock();
Matthew Xieddf7e472013-03-01 18:41:02 -08001350 if (msg.arg1 == SERVICE_IBLUETOOTH) {
1351 // if service is unbinded already, do nothing and return
1352 if (mBluetooth == null) break;
1353 mBluetooth = null;
1354 } else if (msg.arg1 == SERVICE_IBLUETOOTHGATT) {
1355 mBluetoothGatt = null;
1356 break;
1357 } else {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001358 Slog.e(TAG, "Bad msg.arg1: " + msg.arg1);
Matthew Xieddf7e472013-03-01 18:41:02 -08001359 break;
1360 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001361 } finally {
1362 mBluetoothLock.writeLock().unlock();
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301363 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001364
1365 if (mEnable) {
1366 mEnable = false;
1367 // Send a Bluetooth Restart message
1368 Message restartMsg = mHandler.obtainMessage(
1369 MESSAGE_RESTART_BLUETOOTH_SERVICE);
1370 mHandler.sendMessageDelayed(restartMsg,
1371 SERVICE_RESTART_TIME_MS);
1372 }
1373
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001374 sendBluetoothServiceDownCallback();
Zhihai Xu40874a02012-10-08 17:57:03 -07001375
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001376 // Send BT state broadcast to update
1377 // the BT icon correctly
1378 if ((mState == BluetoothAdapter.STATE_TURNING_ON) ||
1379 (mState == BluetoothAdapter.STATE_ON)) {
1380 bluetoothStateChangeHandler(BluetoothAdapter.STATE_ON,
1381 BluetoothAdapter.STATE_TURNING_OFF);
1382 mState = BluetoothAdapter.STATE_TURNING_OFF;
Zhihai Xu40874a02012-10-08 17:57:03 -07001383 }
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001384 if (mState == BluetoothAdapter.STATE_TURNING_OFF) {
1385 bluetoothStateChangeHandler(BluetoothAdapter.STATE_TURNING_OFF,
1386 BluetoothAdapter.STATE_OFF);
1387 }
1388
1389 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
1390 mState = BluetoothAdapter.STATE_OFF;
fredc649fe492012-04-19 01:07:18 -07001391 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001392 }
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301393 case MESSAGE_RESTART_BLUETOOTH_SERVICE:
1394 {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001395 Slog.d(TAG, "MESSAGE_RESTART_BLUETOOTH_SERVICE:"
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301396 +" Restart IBluetooth service");
1397 /* Enable without persisting the setting as
1398 it doesnt change when IBluetooth
1399 service restarts */
Zhihai Xu40874a02012-10-08 17:57:03 -07001400 mEnable = true;
Zhihai Xu401202b2012-12-03 11:36:21 -08001401 handleEnable(mQuietEnable);
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301402 break;
1403 }
1404
fredc0f420372012-04-12 00:02:00 -07001405 case MESSAGE_TIMEOUT_UNBIND:
1406 {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001407 Slog.e(TAG, "MESSAGE_TIMEOUT_UNBIND");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001408 mBluetoothLock.writeLock().lock();
1409 mUnbinding = false;
1410 mBluetoothLock.writeLock().unlock();
fredc649fe492012-04-19 01:07:18 -07001411 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001412 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001413
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001414 case MESSAGE_USER_SWITCHED: {
1415 if (DBG) Slog.d(TAG, "MESSAGE_USER_SWITCHED");
Zhihai Xu40874a02012-10-08 17:57:03 -07001416 mHandler.removeMessages(MESSAGE_USER_SWITCHED);
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001417
Zhihai Xu40874a02012-10-08 17:57:03 -07001418 /* disable and enable BT when detect a user switch */
1419 if (mEnable && mBluetooth != null) {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001420 try {
1421 mBluetoothLock.readLock().lock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001422 if (mBluetooth != null) {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001423 mBluetooth.unregisterCallback(mBluetoothCallback);
Zhihai Xu40874a02012-10-08 17:57:03 -07001424 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001425 } catch (RemoteException re) {
1426 Slog.e(TAG, "Unable to unregister", re);
1427 } finally {
1428 mBluetoothLock.readLock().unlock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001429 }
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001430
1431 if (mState == BluetoothAdapter.STATE_TURNING_OFF) {
1432 // MESSAGE_USER_SWITCHED happened right after MESSAGE_ENABLE
1433 bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_OFF);
1434 mState = BluetoothAdapter.STATE_OFF;
1435 }
1436 if (mState == BluetoothAdapter.STATE_OFF) {
1437 bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_TURNING_ON);
1438 mState = BluetoothAdapter.STATE_TURNING_ON;
1439 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001440
1441 waitForOnOff(true, false);
1442
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001443 if (mState == BluetoothAdapter.STATE_TURNING_ON) {
1444 bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_ON);
1445 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001446
Benjamin Franze8b98922014-11-12 15:57:54 +00001447 unbindAllBluetoothProfileServices();
Zhihai Xu40874a02012-10-08 17:57:03 -07001448 // disable
Zhihai Xu401202b2012-12-03 11:36:21 -08001449 handleDisable();
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001450 // Pbap service need receive STATE_TURNING_OFF intent to close
1451 bluetoothStateChangeHandler(BluetoothAdapter.STATE_ON,
1452 BluetoothAdapter.STATE_TURNING_OFF);
Zhihai Xu40874a02012-10-08 17:57:03 -07001453
1454 waitForOnOff(false, true);
1455
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001456 bluetoothStateChangeHandler(BluetoothAdapter.STATE_TURNING_OFF,
Zhihai Xu40874a02012-10-08 17:57:03 -07001457 BluetoothAdapter.STATE_OFF);
Zhihai Xu40874a02012-10-08 17:57:03 -07001458 sendBluetoothServiceDownCallback();
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001459
1460 mBluetoothLock.writeLock().lock();
1461 if (mBluetooth != null) {
1462 mBluetooth = null;
1463 // Unbind
1464 mContext.unbindService(mConnection);
Zhihai Xu40874a02012-10-08 17:57:03 -07001465 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001466 mBluetoothGatt = null;
1467 mBluetoothLock.writeLock().unlock();
1468
Zhihai Xu40874a02012-10-08 17:57:03 -07001469 SystemClock.sleep(100);
1470
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001471 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
1472 mState = BluetoothAdapter.STATE_OFF;
Zhihai Xu40874a02012-10-08 17:57:03 -07001473 // enable
Zhihai Xu401202b2012-12-03 11:36:21 -08001474 handleEnable(mQuietEnable);
John Spurlock8a985d22014-02-25 09:40:05 -05001475 } else if (mBinding || mBluetooth != null) {
Zhihai Xu40874a02012-10-08 17:57:03 -07001476 Message userMsg = mHandler.obtainMessage(MESSAGE_USER_SWITCHED);
1477 userMsg.arg2 = 1 + msg.arg2;
1478 // if user is switched when service is being binding
1479 // delay sending MESSAGE_USER_SWITCHED
1480 mHandler.sendMessageDelayed(userMsg, USER_SWITCHED_TIME_MS);
1481 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001482 Slog.d(TAG, "delay MESSAGE_USER_SWITCHED " + userMsg.arg2);
Zhihai Xu40874a02012-10-08 17:57:03 -07001483 }
John Spurlock8a985d22014-02-25 09:40:05 -05001484 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001485 break;
1486 }
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001487 case MESSAGE_USER_UNLOCKED: {
1488 if (DBG) Slog.d(TAG, "MESSAGE_USER_UNLOCKED");
1489 mHandler.removeMessages(MESSAGE_USER_SWITCHED);
1490
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001491 if (mEnable && !mBinding && (mBluetooth == null)) {
1492 // We should be connected, but we gave up for some
1493 // reason; maybe the Bluetooth service wasn't encryption
1494 // aware, so try binding again.
1495 if (DBG) Slog.d(TAG, "Enabled but not bound; retrying after unlock");
1496 handleEnable(mQuietEnable);
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001497 }
1498 }
fredc0f420372012-04-12 00:02:00 -07001499 }
1500 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001501 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001502
Zhihai Xu401202b2012-12-03 11:36:21 -08001503 private void handleEnable(boolean quietMode) {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001504 mQuietEnable = quietMode;
1505
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001506 try {
1507 mBluetoothLock.writeLock().lock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001508 if ((mBluetooth == null) && (!mBinding)) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001509 //Start bind timeout and bind
1510 Message timeoutMsg=mHandler.obtainMessage(MESSAGE_TIMEOUT_BIND);
1511 mHandler.sendMessageDelayed(timeoutMsg,TIMEOUT_BIND_MS);
Matthew Xiecdce0b92012-07-12 19:06:15 -07001512 Intent i = new Intent(IBluetooth.class.getName());
Dianne Hackbornce09f5a2014-10-10 15:03:13 -07001513 if (!doBind(i, mConnection,Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT,
1514 UserHandle.CURRENT)) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001515 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
Zhihai Xu40874a02012-10-08 17:57:03 -07001516 } else {
1517 mBinding = true;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001518 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001519 } else if (mBluetooth != null) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001520 //Enable bluetooth
1521 try {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001522 if (!mQuietEnable) {
1523 if(!mBluetooth.enable()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001524 Slog.e(TAG,"IBluetooth.enable() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001525 }
1526 }
1527 else {
1528 if(!mBluetooth.enableNoAutoConnect()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001529 Slog.e(TAG,"IBluetooth.enableNoAutoConnect() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001530 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001531 }
1532 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001533 Slog.e(TAG,"Unable to call enable()",e);
Matthew Xiecdce0b92012-07-12 19:06:15 -07001534 }
1535 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001536 } finally {
1537 mBluetoothLock.writeLock().unlock();
Matthew Xiecdce0b92012-07-12 19:06:15 -07001538 }
1539 }
1540
Dianne Hackborn221ea892013-08-04 16:50:16 -07001541 boolean doBind(Intent intent, ServiceConnection conn, int flags, UserHandle user) {
1542 ComponentName comp = intent.resolveSystemService(mContext.getPackageManager(), 0);
1543 intent.setComponent(comp);
1544 if (comp == null || !mContext.bindServiceAsUser(intent, conn, flags, user)) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001545 Slog.e(TAG, "Fail to bind to: " + intent);
Dianne Hackborn221ea892013-08-04 16:50:16 -07001546 return false;
1547 }
1548 return true;
1549 }
1550
Zhihai Xu401202b2012-12-03 11:36:21 -08001551 private void handleDisable() {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001552 try {
1553 mBluetoothLock.readLock().lock();
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001554 if (mBluetooth != null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001555 if (DBG) Slog.d(TAG,"Sending off request.");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001556 if (!mBluetooth.disable()) {
1557 Slog.e(TAG,"IBluetooth.disable() returned false");
Matthew Xiecdce0b92012-07-12 19:06:15 -07001558 }
1559 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001560 } catch (RemoteException e) {
1561 Slog.e(TAG,"Unable to call disable()",e);
1562 } finally {
1563 mBluetoothLock.readLock().unlock();
Matthew Xiecdce0b92012-07-12 19:06:15 -07001564 }
1565 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001566
1567 private boolean checkIfCallerIsForegroundUser() {
1568 int foregroundUser;
1569 int callingUser = UserHandle.getCallingUserId();
Martijn Coenen8385c5a2012-11-29 10:14:16 -08001570 int callingUid = Binder.getCallingUid();
Zhihai Xu40874a02012-10-08 17:57:03 -07001571 long callingIdentity = Binder.clearCallingIdentity();
Benjamin Franze8b98922014-11-12 15:57:54 +00001572 UserManager um = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
1573 UserInfo ui = um.getProfileParent(callingUser);
1574 int parentUser = (ui != null) ? ui.id : UserHandle.USER_NULL;
Martijn Coenen8385c5a2012-11-29 10:14:16 -08001575 int callingAppId = UserHandle.getAppId(callingUid);
Zhihai Xu40874a02012-10-08 17:57:03 -07001576 boolean valid = false;
1577 try {
1578 foregroundUser = ActivityManager.getCurrentUser();
Martijn Coenen8385c5a2012-11-29 10:14:16 -08001579 valid = (callingUser == foregroundUser) ||
Benjamin Franze8b98922014-11-12 15:57:54 +00001580 parentUser == foregroundUser ||
Adrian Roosbd9a9a52014-08-18 15:31:57 +02001581 callingAppId == Process.NFC_UID ||
1582 callingAppId == mSystemUiUid;
Zhihai Xu40874a02012-10-08 17:57:03 -07001583 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001584 Slog.d(TAG, "checkIfCallerIsForegroundUser: valid=" + valid
Zhihai Xu40874a02012-10-08 17:57:03 -07001585 + " callingUser=" + callingUser
Benjamin Franze8b98922014-11-12 15:57:54 +00001586 + " parentUser=" + parentUser
Zhihai Xu40874a02012-10-08 17:57:03 -07001587 + " foregroundUser=" + foregroundUser);
1588 }
1589 } finally {
1590 Binder.restoreCallingIdentity(callingIdentity);
1591 }
1592 return valid;
1593 }
1594
Nitin Arorad055adb2015-03-02 15:03:51 -08001595 private void sendBleStateChanged(int prevState, int newState) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001596 if (DBG) Slog.d(TAG,"BLE State Change Intent: " + prevState + " -> " + newState);
Nitin Arorad055adb2015-03-02 15:03:51 -08001597 // Send broadcast message to everyone else
1598 Intent intent = new Intent(BluetoothAdapter.ACTION_BLE_STATE_CHANGED);
1599 intent.putExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE, prevState);
1600 intent.putExtra(BluetoothAdapter.EXTRA_STATE, newState);
1601 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1602 mContext.sendBroadcastAsUser(intent, UserHandle.ALL, BLUETOOTH_PERM);
1603 }
1604
Zhihai Xu40874a02012-10-08 17:57:03 -07001605 private void bluetoothStateChangeHandler(int prevState, int newState) {
Nitin Arorad055adb2015-03-02 15:03:51 -08001606 boolean isStandardBroadcast = true;
Zhihai Xu40874a02012-10-08 17:57:03 -07001607 if (prevState != newState) {
1608 //Notify all proxy objects first of adapter state change
Nitin Arorad055adb2015-03-02 15:03:51 -08001609 if (newState == BluetoothAdapter.STATE_BLE_ON
1610 || newState == BluetoothAdapter.STATE_OFF) {
1611 boolean intermediate_off = (prevState == BluetoothAdapter.STATE_TURNING_OFF
1612 && newState == BluetoothAdapter.STATE_BLE_ON);
Zhihai Xu40874a02012-10-08 17:57:03 -07001613
Nitin Arorad055adb2015-03-02 15:03:51 -08001614 if (newState == BluetoothAdapter.STATE_OFF) {
1615 // If Bluetooth is off, send service down event to proxy objects, and unbind
Jeff Sharkey67609c72016-03-05 14:29:13 -07001616 if (DBG) Slog.d(TAG, "Bluetooth is complete turn off");
Nitin Arorad055adb2015-03-02 15:03:51 -08001617 if (canUnbindBluetoothService()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001618 if (DBG) Slog.d(TAG, "Good to unbind!");
Matthew Xieddf7e472013-03-01 18:41:02 -08001619 sendBluetoothServiceDownCallback();
1620 unbindAndFinish();
Nitin Arorad055adb2015-03-02 15:03:51 -08001621 sendBleStateChanged(prevState, newState);
1622 // Don't broadcast as it has already been broadcast before
1623 isStandardBroadcast = false;
Matthew Xieddf7e472013-03-01 18:41:02 -08001624 }
Nitin Arorad055adb2015-03-02 15:03:51 -08001625
1626 } else if (!intermediate_off) {
1627 // connect to GattService
Jeff Sharkey67609c72016-03-05 14:29:13 -07001628 if (DBG) Slog.d(TAG, "Bluetooth is in LE only mode");
Nitin Arorad055adb2015-03-02 15:03:51 -08001629 if (mBluetoothGatt != null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001630 if (DBG) Slog.d(TAG, "Calling BluetoothGattServiceUp");
Nitin Arorad055adb2015-03-02 15:03:51 -08001631 onBluetoothGattServiceUp();
1632 } else {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001633 if (DBG) Slog.d(TAG, "Binding Bluetooth GATT service");
Nitin Arorad055adb2015-03-02 15:03:51 -08001634 if (mContext.getPackageManager().hasSystemFeature(
1635 PackageManager.FEATURE_BLUETOOTH_LE)) {
1636 Intent i = new Intent(IBluetoothGatt.class.getName());
1637 doBind(i, mConnection, Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT, UserHandle.CURRENT);
1638 }
1639 }
1640 sendBleStateChanged(prevState, newState);
1641 //Don't broadcase this as std intent
1642 isStandardBroadcast = false;
1643
1644 } else if (intermediate_off){
Jeff Sharkey67609c72016-03-05 14:29:13 -07001645 if (DBG) Slog.d(TAG, "Intermediate off, back to LE only mode");
Nitin Arorad055adb2015-03-02 15:03:51 -08001646 // For LE only mode, broadcast as is
1647 sendBleStateChanged(prevState, newState);
1648 sendBluetoothStateCallback(false); // BT is OFF for general users
1649 // Broadcast as STATE_OFF
1650 newState = BluetoothAdapter.STATE_OFF;
1651 sendBrEdrDownCallback();
Zhihai Xu40874a02012-10-08 17:57:03 -07001652 }
Nitin Arorad055adb2015-03-02 15:03:51 -08001653 } else if (newState == BluetoothAdapter.STATE_ON) {
1654 boolean isUp = (newState==BluetoothAdapter.STATE_ON);
1655 sendBluetoothStateCallback(isUp);
1656 sendBleStateChanged(prevState, newState);
1657
1658 } else if (newState == BluetoothAdapter.STATE_BLE_TURNING_ON
1659 || newState == BluetoothAdapter.STATE_BLE_TURNING_OFF ) {
1660 sendBleStateChanged(prevState, newState);
1661 isStandardBroadcast = false;
1662
1663 } else if (newState == BluetoothAdapter.STATE_TURNING_ON
1664 || newState == BluetoothAdapter.STATE_TURNING_OFF) {
1665 sendBleStateChanged(prevState, newState);
Zhihai Xu40874a02012-10-08 17:57:03 -07001666 }
1667
Nitin Arorad055adb2015-03-02 15:03:51 -08001668 if (isStandardBroadcast) {
1669 if (prevState == BluetoothAdapter.STATE_BLE_ON) {
1670 // Show prevState of BLE_ON as OFF to standard users
1671 prevState = BluetoothAdapter.STATE_OFF;
1672 }
1673 Intent intent = new Intent(BluetoothAdapter.ACTION_STATE_CHANGED);
1674 intent.putExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE, prevState);
1675 intent.putExtra(BluetoothAdapter.EXTRA_STATE, newState);
1676 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1677 mContext.sendBroadcastAsUser(intent, UserHandle.ALL, BLUETOOTH_PERM);
1678 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001679 }
1680 }
1681
1682 /**
1683 * if on is true, wait for state become ON
1684 * if off is true, wait for state become OFF
1685 * if both on and off are false, wait for state not ON
1686 */
1687 private boolean waitForOnOff(boolean on, boolean off) {
1688 int i = 0;
1689 while (i < 10) {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001690 try {
1691 mBluetoothLock.readLock().lock();
1692 if (mBluetooth == null) break;
1693 if (on) {
1694 if (mBluetooth.getState() == BluetoothAdapter.STATE_ON) return true;
1695 } else if (off) {
1696 if (mBluetooth.getState() == BluetoothAdapter.STATE_OFF) return true;
1697 } else {
1698 if (mBluetooth.getState() != BluetoothAdapter.STATE_ON) return true;
Zhihai Xu40874a02012-10-08 17:57:03 -07001699 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001700 } catch (RemoteException e) {
1701 Slog.e(TAG, "getState()", e);
1702 break;
1703 } finally {
1704 mBluetoothLock.readLock().unlock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001705 }
1706 if (on || off) {
1707 SystemClock.sleep(300);
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07001708 } else {
Zhihai Xu40874a02012-10-08 17:57:03 -07001709 SystemClock.sleep(50);
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07001710 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001711 i++;
1712 }
Jeff Sharkey67609c72016-03-05 14:29:13 -07001713 Slog.e(TAG,"waitForOnOff time out");
Zhihai Xu40874a02012-10-08 17:57:03 -07001714 return false;
1715 }
Zhihai Xu681ae7f2012-11-12 15:14:18 -08001716
Zhihai Xu401202b2012-12-03 11:36:21 -08001717 private void sendDisableMsg() {
1718 mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_DISABLE));
1719 }
1720
1721 private void sendEnableMsg(boolean quietMode) {
1722 mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_ENABLE,
1723 quietMode ? 1 : 0, 0));
1724 }
1725
Zhihai Xu681ae7f2012-11-12 15:14:18 -08001726 private boolean canUnbindBluetoothService() {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001727 try {
Zhihai Xu681ae7f2012-11-12 15:14:18 -08001728 //Only unbind with mEnable flag not set
1729 //For race condition: disable and enable back-to-back
1730 //Avoid unbind right after enable due to callback from disable
1731 //Only unbind with Bluetooth at OFF state
1732 //Only unbind without any MESSAGE_BLUETOOTH_STATE_CHANGE message
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001733 mBluetoothLock.readLock().lock();
1734 if (mEnable || (mBluetooth == null)) return false;
1735 if (mHandler.hasMessages(MESSAGE_BLUETOOTH_STATE_CHANGE)) return false;
1736 return (mBluetooth.getState() == BluetoothAdapter.STATE_OFF);
1737 } catch (RemoteException e) {
1738 Slog.e(TAG, "getState()", e);
1739 } finally {
1740 mBluetoothLock.readLock().unlock();
Zhihai Xu681ae7f2012-11-12 15:14:18 -08001741 }
1742 return false;
1743 }
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001744
1745 private void recoverBluetoothServiceFromError() {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001746 Slog.e(TAG,"recoverBluetoothServiceFromError");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001747 try {
1748 mBluetoothLock.readLock().lock();
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001749 if (mBluetooth != null) {
1750 //Unregister callback object
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001751 mBluetooth.unregisterCallback(mBluetoothCallback);
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001752 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001753 } catch (RemoteException re) {
1754 Slog.e(TAG, "Unable to unregister", re);
1755 } finally {
1756 mBluetoothLock.readLock().unlock();
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001757 }
1758
1759 SystemClock.sleep(500);
1760
1761 // disable
1762 handleDisable();
1763
1764 waitForOnOff(false, true);
1765
1766 sendBluetoothServiceDownCallback();
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001767
1768 mBluetoothLock.writeLock().lock();
1769 if (mBluetooth != null) {
1770 mBluetooth = null;
1771 // Unbind
1772 mContext.unbindService(mConnection);
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001773 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001774 mBluetoothGatt = null;
1775 mBluetoothLock.writeLock().unlock();
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001776
1777 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
1778 mState = BluetoothAdapter.STATE_OFF;
1779
1780 mEnable = false;
1781
1782 if (mErrorRecoveryRetryCounter++ < MAX_ERROR_RESTART_RETRIES) {
1783 // Send a Bluetooth Restart message to reenable bluetooth
1784 Message restartMsg = mHandler.obtainMessage(
1785 MESSAGE_RESTART_BLUETOOTH_SERVICE);
1786 mHandler.sendMessageDelayed(restartMsg, ERROR_RESTART_TIME_MS);
1787 } else {
1788 // todo: notify user to power down and power up phone to make bluetooth work.
1789 }
1790 }
Mike Lockwood726d4de2014-10-28 14:06:28 -07001791
1792 @Override
Pavlin Radoslavov6e8faff2016-02-23 11:54:37 -08001793 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1794 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DUMP, TAG);
1795 String errorMsg = null;
1796 if (mBluetoothBinder == null) {
1797 errorMsg = "Bluetooth Service not connected";
1798 } else {
1799 try {
1800 mBluetoothBinder.dump(fd, args);
1801 } catch (RemoteException re) {
1802 errorMsg = "RemoteException while calling Bluetooth Service";
1803 }
Mike Lockwood726d4de2014-10-28 14:06:28 -07001804 }
Pavlin Radoslavov6e8faff2016-02-23 11:54:37 -08001805 if (errorMsg != null) {
1806 // Silently return if we are extracting metrics in Protobuf format
1807 if ((args.length > 0) && args[0].startsWith("--proto"))
1808 return;
1809 writer.println(errorMsg);
1810 }
Mike Lockwood726d4de2014-10-28 14:06:28 -07001811 }
fredc0f420372012-04-12 00:02:00 -07001812}