blob: 7875cb86ee7818e46bc914b380692ee9b4f6c814 [file] [log] [blame]
fredc0f420372012-04-12 00:02:00 -07001/*
Zhihai Xufa0fd392012-10-23 17:31:56 -07002 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
fredc0f420372012-04-12 00:02:00 -070015 */
16
17package com.android.server;
18
Svet Ganov408abf72015-05-12 19:13:36 -070019import android.Manifest;
Zhihai Xu40874a02012-10-08 17:57:03 -070020import android.app.ActivityManager;
fredc0f420372012-04-12 00:02:00 -070021import android.bluetooth.BluetoothAdapter;
Benjamin Franze8b98922014-11-12 15:57:54 +000022import android.bluetooth.BluetoothProfile;
fredc0f420372012-04-12 00:02:00 -070023import android.bluetooth.IBluetooth;
fredcbf072a72012-05-09 16:52:50 -070024import android.bluetooth.IBluetoothCallback;
Wei Wange4a744b2015-06-11 17:50:29 -070025import android.bluetooth.IBluetoothGatt;
Benjamin Franze8b98922014-11-12 15:57:54 +000026import android.bluetooth.IBluetoothHeadset;
fredc0f420372012-04-12 00:02:00 -070027import android.bluetooth.IBluetoothManager;
28import android.bluetooth.IBluetoothManagerCallback;
Benjamin Franze8b98922014-11-12 15:57:54 +000029import android.bluetooth.IBluetoothProfileServiceConnection;
fredc0f420372012-04-12 00:02:00 -070030import android.bluetooth.IBluetoothStateChangeCallback;
fredc0f420372012-04-12 00:02:00 -070031import android.content.BroadcastReceiver;
32import android.content.ComponentName;
33import android.content.ContentResolver;
34import android.content.Context;
35import android.content.Intent;
36import android.content.IntentFilter;
37import android.content.ServiceConnection;
Svetoslav Ganovf9e2ad02016-06-29 17:31:44 -070038import android.content.pm.ApplicationInfo;
Matthew Xie32ab77b2013-05-08 19:26:57 -070039import android.content.pm.PackageManager;
Benjamin Franze8b98922014-11-12 15:57:54 +000040import android.content.pm.UserInfo;
Wei Wange4a744b2015-06-11 17:50:29 -070041import android.database.ContentObserver;
Zhihai Xu40874a02012-10-08 17:57:03 -070042import android.os.Binder;
Svetoslav Ganovf9e2ad02016-06-29 17:31:44 -070043import android.os.Build;
fredc0f420372012-04-12 00:02:00 -070044import android.os.Handler;
fredc0f420372012-04-12 00:02:00 -070045import android.os.IBinder;
Zhihai Xu40874a02012-10-08 17:57:03 -070046import android.os.Looper;
fredc0f420372012-04-12 00:02:00 -070047import android.os.Message;
Zhihai Xu40874a02012-10-08 17:57:03 -070048import android.os.Process;
fredcd6883532012-04-25 17:46:13 -070049import android.os.RemoteCallbackList;
fredc0f420372012-04-12 00:02:00 -070050import android.os.RemoteException;
Zhihai Xu40874a02012-10-08 17:57:03 -070051import android.os.SystemClock;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070052import android.os.UserHandle;
Benjamin Franze8b98922014-11-12 15:57:54 +000053import android.os.UserManager;
fredc0f420372012-04-12 00:02:00 -070054import android.provider.Settings;
Wei Wang67d84162015-04-26 17:04:29 -070055import android.provider.Settings.SettingNotFoundException;
Jeff Sharkey67609c72016-03-05 14:29:13 -070056import android.util.Slog;
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -070057import java.util.concurrent.locks.ReentrantReadWriteLock;
Mike Lockwood726d4de2014-10-28 14:06:28 -070058
59import java.io.FileDescriptor;
60import java.io.PrintWriter;
Benjamin Franze8b98922014-11-12 15:57:54 +000061import java.util.HashMap;
62import java.util.Map;
Miao Chou658bf2f2015-06-26 17:14:35 -070063
fredc0f420372012-04-12 00:02:00 -070064class BluetoothManagerService extends IBluetoothManager.Stub {
65 private static final String TAG = "BluetoothManagerService";
Pavlin Radoslavov41401112016-06-27 15:25:18 -070066 private static final boolean DBG = true;
fredc0f420372012-04-12 00:02:00 -070067
fredc0f420372012-04-12 00:02:00 -070068 private static final String BLUETOOTH_ADMIN_PERM = android.Manifest.permission.BLUETOOTH_ADMIN;
69 private static final String BLUETOOTH_PERM = android.Manifest.permission.BLUETOOTH;
fredc0f420372012-04-12 00:02:00 -070070 private static final String ACTION_SERVICE_STATE_CHANGED="com.android.bluetooth.btservice.action.STATE_CHANGED";
71 private static final String EXTRA_ACTION="action";
Zhihai Xud31c3222012-10-31 16:08:57 -070072 private static final String SECURE_SETTINGS_BLUETOOTH_ADDR_VALID="bluetooth_addr_valid";
fredc0f420372012-04-12 00:02:00 -070073 private static final String SECURE_SETTINGS_BLUETOOTH_ADDRESS="bluetooth_address";
74 private static final String SECURE_SETTINGS_BLUETOOTH_NAME="bluetooth_name";
fredc0f420372012-04-12 00:02:00 -070075 private static final int TIMEOUT_BIND_MS = 3000; //Maximum msec to wait for a bind
76 private static final int TIMEOUT_SAVE_MS = 500; //Maximum msec to wait for a save
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +053077 //Maximum msec to wait for service restart
78 private static final int SERVICE_RESTART_TIME_MS = 200;
Zhihai Xudd9d17d2013-01-08 17:05:58 -080079 //Maximum msec to wait for restart due to error
80 private static final int ERROR_RESTART_TIME_MS = 3000;
Zhihai Xu40874a02012-10-08 17:57:03 -070081 //Maximum msec to delay MESSAGE_USER_SWITCHED
82 private static final int USER_SWITCHED_TIME_MS = 200;
Benjamin Franze8b98922014-11-12 15:57:54 +000083 // Delay for the addProxy function in msec
84 private static final int ADD_PROXY_DELAY_MS = 100;
fredc0f420372012-04-12 00:02:00 -070085
86 private static final int MESSAGE_ENABLE = 1;
87 private static final int MESSAGE_DISABLE = 2;
fredc649fe492012-04-19 01:07:18 -070088 private static final int MESSAGE_REGISTER_ADAPTER = 20;
89 private static final int MESSAGE_UNREGISTER_ADAPTER = 21;
90 private static final int MESSAGE_REGISTER_STATE_CHANGE_CALLBACK = 30;
91 private static final int MESSAGE_UNREGISTER_STATE_CHANGE_CALLBACK = 31;
92 private static final int MESSAGE_BLUETOOTH_SERVICE_CONNECTED = 40;
93 private static final int MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED = 41;
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +053094 private static final int MESSAGE_RESTART_BLUETOOTH_SERVICE = 42;
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -070095 private static final int MESSAGE_BLUETOOTH_STATE_CHANGE = 60;
96 private static final int MESSAGE_TIMEOUT_BIND = 100;
97 private static final int MESSAGE_TIMEOUT_UNBIND = 101;
Ajay Panicker4bb48302016-03-31 14:14:27 -070098 private static final int MESSAGE_GET_NAME_AND_ADDRESS = 200;
Zhihai Xu40874a02012-10-08 17:57:03 -070099 private static final int MESSAGE_USER_SWITCHED = 300;
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -0700100 private static final int MESSAGE_USER_UNLOCKED = 301;
Benjamin Franze8b98922014-11-12 15:57:54 +0000101 private static final int MESSAGE_ADD_PROXY_DELAYED = 400;
102 private static final int MESSAGE_BIND_PROFILE_SERVICE = 401;
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -0700103 private static final int MAX_SAVE_RETRIES = 3;
104 private static final int MAX_ERROR_RESTART_RETRIES = 6;
Zhihai Xudd9d17d2013-01-08 17:05:58 -0800105
Zhihai Xu401202b2012-12-03 11:36:21 -0800106 // Bluetooth persisted setting is off
107 private static final int BLUETOOTH_OFF=0;
108 // Bluetooth persisted setting is on
109 // and Airplane mode won't affect Bluetooth state at start up
110 private static final int BLUETOOTH_ON_BLUETOOTH=1;
111 // Bluetooth persisted setting is on
112 // but Airplane mode will affect Bluetooth state at start up
113 // and Airplane mode will have higher priority.
114 private static final int BLUETOOTH_ON_AIRPLANE=2;
fredc0f420372012-04-12 00:02:00 -0700115
Matthew Xieddf7e472013-03-01 18:41:02 -0800116 private static final int SERVICE_IBLUETOOTH = 1;
117 private static final int SERVICE_IBLUETOOTHGATT = 2;
118
fredc0f420372012-04-12 00:02:00 -0700119 private final Context mContext;
Nitin Arorad055adb2015-03-02 15:03:51 -0800120 private static int mBleAppCount = 0;
Matthew Xiecdce0b92012-07-12 19:06:15 -0700121
122 // Locks are not provided for mName and mAddress.
123 // They are accessed in handler or broadcast receiver, same thread context.
fredc0f420372012-04-12 00:02:00 -0700124 private String mAddress;
125 private String mName;
Matthew Xie6fde3092012-07-11 17:10:07 -0700126 private final ContentResolver mContentResolver;
127 private final RemoteCallbackList<IBluetoothManagerCallback> mCallbacks;
128 private final RemoteCallbackList<IBluetoothStateChangeCallback> mStateChangeCallbacks;
Marie Janssen9db28eb2016-01-12 16:05:15 -0800129 private IBinder mBluetoothBinder;
fredc649fe492012-04-19 01:07:18 -0700130 private IBluetooth mBluetooth;
Matthew Xieddf7e472013-03-01 18:41:02 -0800131 private IBluetoothGatt mBluetoothGatt;
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700132 private final ReentrantReadWriteLock mBluetoothLock =
133 new ReentrantReadWriteLock();
fredc649fe492012-04-19 01:07:18 -0700134 private boolean mBinding;
135 private boolean mUnbinding;
Zhihai Xu401202b2012-12-03 11:36:21 -0800136 // used inside handler thread
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700137 private boolean mQuietEnable = false;
Zhihai Xu401202b2012-12-03 11:36:21 -0800138 // configuarion from external IBinder call which is used to
139 // synchronize with broadcast receiver.
140 private boolean mQuietEnableExternal;
141 // configuarion from external IBinder call which is used to
142 // synchronize with broadcast receiver.
143 private boolean mEnableExternal;
144 // used inside handler thread
Zhihai Xu40874a02012-10-08 17:57:03 -0700145 private boolean mEnable;
146 private int mState;
Zhihai Xu40874a02012-10-08 17:57:03 -0700147 private final BluetoothHandler mHandler;
Zhihai Xudd9d17d2013-01-08 17:05:58 -0800148 private int mErrorRecoveryRetryCounter;
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200149 private final int mSystemUiUid;
fredc0f420372012-04-12 00:02:00 -0700150
Benjamin Franze8b98922014-11-12 15:57:54 +0000151 // Save a ProfileServiceConnections object for each of the bound
152 // bluetooth profile services
153 private final Map <Integer, ProfileServiceConnections> mProfileServices =
154 new HashMap <Integer, ProfileServiceConnections>();
155
Svetoslav Ganovf9e2ad02016-06-29 17:31:44 -0700156 private final boolean mPermissionReviewRequired;
157
fredc649fe492012-04-19 01:07:18 -0700158 private void registerForAirplaneMode(IntentFilter filter) {
159 final ContentResolver resolver = mContext.getContentResolver();
Christopher Tatec09cdce2012-09-10 16:50:14 -0700160 final String airplaneModeRadios = Settings.Global.getString(resolver,
161 Settings.Global.AIRPLANE_MODE_RADIOS);
162 final String toggleableRadios = Settings.Global.getString(resolver,
163 Settings.Global.AIRPLANE_MODE_TOGGLEABLE_RADIOS);
fredc649fe492012-04-19 01:07:18 -0700164 boolean mIsAirplaneSensitive = airplaneModeRadios == null ? true :
Christopher Tatec09cdce2012-09-10 16:50:14 -0700165 airplaneModeRadios.contains(Settings.Global.RADIO_BLUETOOTH);
fredc649fe492012-04-19 01:07:18 -0700166 if (mIsAirplaneSensitive) {
167 filter.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED);
168 }
169 }
170
fredcbf072a72012-05-09 16:52:50 -0700171 private final IBluetoothCallback mBluetoothCallback = new IBluetoothCallback.Stub() {
172 @Override
173 public void onBluetoothStateChange(int prevState, int newState) throws RemoteException {
174 Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_STATE_CHANGE,prevState,newState);
175 mHandler.sendMessage(msg);
176 }
177 };
178
179 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
fredc0f420372012-04-12 00:02:00 -0700180 @Override
181 public void onReceive(Context context, Intent intent) {
182 String action = intent.getAction();
fredcbf072a72012-05-09 16:52:50 -0700183 if (BluetoothAdapter.ACTION_LOCAL_NAME_CHANGED.equals(action)) {
fredc0f420372012-04-12 00:02:00 -0700184 String newName = intent.getStringExtra(BluetoothAdapter.EXTRA_LOCAL_NAME);
Jeff Sharkey67609c72016-03-05 14:29:13 -0700185 if (DBG) Slog.d(TAG, "Bluetooth Adapter name changed to " + newName);
fredc0f420372012-04-12 00:02:00 -0700186 if (newName != null) {
187 storeNameAndAddress(newName, null);
188 }
fredc649fe492012-04-19 01:07:18 -0700189 } else if (Intent.ACTION_AIRPLANE_MODE_CHANGED.equals(action)) {
Zhihai Xu401202b2012-12-03 11:36:21 -0800190 synchronized(mReceiver) {
191 if (isBluetoothPersistedStateOn()) {
192 if (isAirplaneModeOn()) {
193 persistBluetoothSetting(BLUETOOTH_ON_AIRPLANE);
194 } else {
195 persistBluetoothSetting(BLUETOOTH_ON_BLUETOOTH);
196 }
197 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800198
199 int st = BluetoothAdapter.STATE_OFF;
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700200 try {
201 mBluetoothLock.readLock().lock();
202 if (mBluetooth != null) {
Nitin Arorad055adb2015-03-02 15:03:51 -0800203 st = mBluetooth.getState();
Nitin Arorad055adb2015-03-02 15:03:51 -0800204 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700205 } catch (RemoteException e) {
206 Slog.e(TAG, "Unable to call getState", e);
207 } finally {
208 mBluetoothLock.readLock().unlock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800209 }
Jeff Sharkey67609c72016-03-05 14:29:13 -0700210 Slog.d(TAG, "state" + st);
Nitin Arorad055adb2015-03-02 15:03:51 -0800211
Zhihai Xu401202b2012-12-03 11:36:21 -0800212 if (isAirplaneModeOn()) {
Nitin Arorad055adb2015-03-02 15:03:51 -0800213 // Clear registered LE apps to force shut-off
214 synchronized (this) {
215 mBleAppCount = 0;
Nitin Arora11f83882015-05-07 18:45:44 -0700216 mBleApps.clear();
Nitin Arorad055adb2015-03-02 15:03:51 -0800217 }
218 if (st == BluetoothAdapter.STATE_BLE_ON) {
219 //if state is BLE_ON make sure you trigger disableBLE part
220 try {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700221 mBluetoothLock.readLock().lock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800222 if (mBluetooth != null) {
223 mBluetooth.onBrEdrDown();
224 mEnableExternal = false;
225 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700226 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700227 Slog.e(TAG,"Unable to call onBrEdrDown", e);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700228 } finally {
Pavlin Radoslavov7ee53be2016-06-09 12:58:07 -0700229 mBluetoothLock.readLock().unlock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800230 }
231 } else if (st == BluetoothAdapter.STATE_ON){
232 // disable without persisting the setting
Jeff Sharkey67609c72016-03-05 14:29:13 -0700233 Slog.d(TAG, "Calling disable");
Nitin Arorad055adb2015-03-02 15:03:51 -0800234 sendDisableMsg();
235 }
Zhihai Xu401202b2012-12-03 11:36:21 -0800236 } else if (mEnableExternal) {
237 // enable without persisting the setting
Jeff Sharkey67609c72016-03-05 14:29:13 -0700238 Slog.d(TAG, "Calling enable");
Zhihai Xu401202b2012-12-03 11:36:21 -0800239 sendEnableMsg(mQuietEnableExternal);
240 }
fredc649fe492012-04-19 01:07:18 -0700241 }
fredc0f420372012-04-12 00:02:00 -0700242 }
243 }
244 };
245
246 BluetoothManagerService(Context context) {
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700247 mHandler = new BluetoothHandler(IoThread.get().getLooper());
Zhihai Xu40874a02012-10-08 17:57:03 -0700248
fredc0f420372012-04-12 00:02:00 -0700249 mContext = context;
Svetoslav Ganovf9e2ad02016-06-29 17:31:44 -0700250
251 mPermissionReviewRequired = Build.PERMISSIONS_REVIEW_REQUIRED
252 || context.getResources().getBoolean(
253 com.android.internal.R.bool.config_permissionReviewRequired);
254
fredc0f420372012-04-12 00:02:00 -0700255 mBluetooth = null;
Marie Janssen9db28eb2016-01-12 16:05:15 -0800256 mBluetoothBinder = null;
Nitin Arorad055adb2015-03-02 15:03:51 -0800257 mBluetoothGatt = null;
fredc0f420372012-04-12 00:02:00 -0700258 mBinding = false;
259 mUnbinding = false;
Zhihai Xu40874a02012-10-08 17:57:03 -0700260 mEnable = false;
261 mState = BluetoothAdapter.STATE_OFF;
Zhihai Xu401202b2012-12-03 11:36:21 -0800262 mQuietEnableExternal = false;
263 mEnableExternal = false;
fredc0f420372012-04-12 00:02:00 -0700264 mAddress = null;
265 mName = null;
Zhihai Xudd9d17d2013-01-08 17:05:58 -0800266 mErrorRecoveryRetryCounter = 0;
fredc0f420372012-04-12 00:02:00 -0700267 mContentResolver = context.getContentResolver();
Wei Wange4a744b2015-06-11 17:50:29 -0700268 // Observe BLE scan only mode settings change.
269 registerForBleScanModeChange();
fredcd6883532012-04-25 17:46:13 -0700270 mCallbacks = new RemoteCallbackList<IBluetoothManagerCallback>();
271 mStateChangeCallbacks = new RemoteCallbackList<IBluetoothStateChangeCallback>();
Miao Chou658bf2f2015-06-26 17:14:35 -0700272 IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_LOCAL_NAME_CHANGED);
Matthew Xie6fde3092012-07-11 17:10:07 -0700273 registerForAirplaneMode(filter);
Dianne Hackbornd83a0962014-05-02 16:28:33 -0700274 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
Matthew Xie6fde3092012-07-11 17:10:07 -0700275 mContext.registerReceiver(mReceiver, filter);
fredc0f420372012-04-12 00:02:00 -0700276 loadStoredNameAndAddress();
Zhihai Xu401202b2012-12-03 11:36:21 -0800277 if (isBluetoothPersistedStateOn()) {
278 mEnableExternal = true;
fredc0f420372012-04-12 00:02:00 -0700279 }
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200280
281 int sysUiUid = -1;
282 try {
Jeff Sharkeye06b4d12016-01-06 14:51:50 -0700283 sysUiUid = mContext.getPackageManager().getPackageUidAsUser("com.android.systemui",
Jeff Sharkeyc5967e92016-01-07 18:50:29 -0700284 PackageManager.MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM);
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200285 } catch (PackageManager.NameNotFoundException e) {
Joe LaPennaacddf2b2015-09-04 12:52:42 -0700286 // Some platforms, such as wearables do not have a system ui.
Jeff Sharkey67609c72016-03-05 14:29:13 -0700287 Slog.w(TAG, "Unable to resolve SystemUI's UID.", e);
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200288 }
289 mSystemUiUid = sysUiUid;
fredc0f420372012-04-12 00:02:00 -0700290 }
291
fredc649fe492012-04-19 01:07:18 -0700292 /**
293 * Returns true if airplane mode is currently on
294 */
295 private final boolean isAirplaneModeOn() {
Christopher Tatec09cdce2012-09-10 16:50:14 -0700296 return Settings.Global.getInt(mContext.getContentResolver(),
297 Settings.Global.AIRPLANE_MODE_ON, 0) == 1;
fredc649fe492012-04-19 01:07:18 -0700298 }
299
300 /**
301 * Returns true if the Bluetooth saved state is "on"
302 */
303 private final boolean isBluetoothPersistedStateOn() {
Jeff Brownbf6f6f92012-09-25 15:03:20 -0700304 return Settings.Global.getInt(mContentResolver,
Zhihai Xu401202b2012-12-03 11:36:21 -0800305 Settings.Global.BLUETOOTH_ON, 0) != BLUETOOTH_OFF;
306 }
307
308 /**
309 * Returns true if the Bluetooth saved state is BLUETOOTH_ON_BLUETOOTH
310 */
311 private final boolean isBluetoothPersistedStateOnBluetooth() {
312 return Settings.Global.getInt(mContentResolver,
313 Settings.Global.BLUETOOTH_ON, 0) == BLUETOOTH_ON_BLUETOOTH;
fredc649fe492012-04-19 01:07:18 -0700314 }
315
316 /**
317 * Save the Bluetooth on/off state
318 *
319 */
Zhihai Xu401202b2012-12-03 11:36:21 -0800320 private void persistBluetoothSetting(int value) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -0700321 Settings.Global.putInt(mContext.getContentResolver(),
322 Settings.Global.BLUETOOTH_ON,
Zhihai Xu401202b2012-12-03 11:36:21 -0800323 value);
fredc649fe492012-04-19 01:07:18 -0700324 }
325
326 /**
327 * Returns true if the Bluetooth Adapter's name and address is
328 * locally cached
329 * @return
330 */
fredc0f420372012-04-12 00:02:00 -0700331 private boolean isNameAndAddressSet() {
332 return mName !=null && mAddress!= null && mName.length()>0 && mAddress.length()>0;
333 }
334
fredc649fe492012-04-19 01:07:18 -0700335 /**
336 * Retrieve the Bluetooth Adapter's name and address and save it in
337 * in the local cache
338 */
fredc0f420372012-04-12 00:02:00 -0700339 private void loadStoredNameAndAddress() {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700340 if (DBG) Slog.d(TAG, "Loading stored name and address");
Zhihai Xud31c3222012-10-31 16:08:57 -0700341 if (mContext.getResources().getBoolean
342 (com.android.internal.R.bool.config_bluetooth_address_validation) &&
343 Settings.Secure.getInt(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDR_VALID, 0) == 0) {
344 // if the valid flag is not set, don't load the address and name
Jeff Sharkey67609c72016-03-05 14:29:13 -0700345 if (DBG) Slog.d(TAG, "invalid bluetooth name and address stored");
Zhihai Xud31c3222012-10-31 16:08:57 -0700346 return;
347 }
fredc0f420372012-04-12 00:02:00 -0700348 mName = Settings.Secure.getString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_NAME);
349 mAddress = Settings.Secure.getString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDRESS);
Jeff Sharkey67609c72016-03-05 14:29:13 -0700350 if (DBG) Slog.d(TAG, "Stored bluetooth Name=" + mName + ",Address=" + mAddress);
fredc0f420372012-04-12 00:02:00 -0700351 }
352
fredc649fe492012-04-19 01:07:18 -0700353 /**
354 * Save the Bluetooth name and address in the persistent store.
355 * Only non-null values will be saved.
356 * @param name
357 * @param address
358 */
fredc0f420372012-04-12 00:02:00 -0700359 private void storeNameAndAddress(String name, String address) {
360 if (name != null) {
361 Settings.Secure.putString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_NAME, name);
fredc0f420372012-04-12 00:02:00 -0700362 mName = name;
Jeff Sharkey67609c72016-03-05 14:29:13 -0700363 if (DBG) Slog.d(TAG,"Stored Bluetooth name: " +
fredc649fe492012-04-19 01:07:18 -0700364 Settings.Secure.getString(mContentResolver,SECURE_SETTINGS_BLUETOOTH_NAME));
fredc0f420372012-04-12 00:02:00 -0700365 }
366
367 if (address != null) {
368 Settings.Secure.putString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDRESS, address);
fredc0f420372012-04-12 00:02:00 -0700369 mAddress=address;
Jeff Sharkey67609c72016-03-05 14:29:13 -0700370 if (DBG) Slog.d(TAG,"Stored Bluetoothaddress: " +
fredc649fe492012-04-19 01:07:18 -0700371 Settings.Secure.getString(mContentResolver,SECURE_SETTINGS_BLUETOOTH_ADDRESS));
fredc0f420372012-04-12 00:02:00 -0700372 }
Zhihai Xud31c3222012-10-31 16:08:57 -0700373
374 if ((name != null) && (address != null)) {
375 Settings.Secure.putInt(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDR_VALID, 1);
376 }
fredc0f420372012-04-12 00:02:00 -0700377 }
378
379 public IBluetooth registerAdapter(IBluetoothManagerCallback callback){
Natalie Silvanovich55db6462014-05-01 16:12:23 -0700380 if (callback == null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700381 Slog.w(TAG, "Callback is null in registerAdapter");
Natalie Silvanovich55db6462014-05-01 16:12:23 -0700382 return null;
383 }
fredc0f420372012-04-12 00:02:00 -0700384 Message msg = mHandler.obtainMessage(MESSAGE_REGISTER_ADAPTER);
385 msg.obj = callback;
386 mHandler.sendMessage(msg);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700387
388 return mBluetooth;
fredc0f420372012-04-12 00:02:00 -0700389 }
390
391 public void unregisterAdapter(IBluetoothManagerCallback callback) {
Natalie Silvanovich55db6462014-05-01 16:12:23 -0700392 if (callback == null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700393 Slog.w(TAG, "Callback is null in unregisterAdapter");
Natalie Silvanovich55db6462014-05-01 16:12:23 -0700394 return;
395 }
fredc0f420372012-04-12 00:02:00 -0700396 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
397 "Need BLUETOOTH permission");
398 Message msg = mHandler.obtainMessage(MESSAGE_UNREGISTER_ADAPTER);
399 msg.obj = callback;
400 mHandler.sendMessage(msg);
401 }
402
403 public void registerStateChangeCallback(IBluetoothStateChangeCallback callback) {
404 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
405 "Need BLUETOOTH permission");
406 Message msg = mHandler.obtainMessage(MESSAGE_REGISTER_STATE_CHANGE_CALLBACK);
407 msg.obj = callback;
408 mHandler.sendMessage(msg);
409 }
410
411 public void unregisterStateChangeCallback(IBluetoothStateChangeCallback callback) {
412 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
413 "Need BLUETOOTH permission");
414 Message msg = mHandler.obtainMessage(MESSAGE_UNREGISTER_STATE_CHANGE_CALLBACK);
415 msg.obj = callback;
416 mHandler.sendMessage(msg);
417 }
418
419 public boolean isEnabled() {
Zhihai Xu6eb76522012-11-29 15:41:04 -0800420 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
421 (!checkIfCallerIsForegroundUser())) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700422 Slog.w(TAG,"isEnabled(): not allowed for non-active and non system user");
Zhihai Xu40874a02012-10-08 17:57:03 -0700423 return false;
424 }
425
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700426 try {
427 mBluetoothLock.readLock().lock();
428 if (mBluetooth != null) return mBluetooth.isEnabled();
429 } catch (RemoteException e) {
430 Slog.e(TAG, "isEnabled()", e);
431 } finally {
432 mBluetoothLock.readLock().unlock();
fredc0f420372012-04-12 00:02:00 -0700433 }
434 return false;
435 }
436
Nitin Arorad055adb2015-03-02 15:03:51 -0800437 class ClientDeathRecipient implements IBinder.DeathRecipient {
438 public void binderDied() {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700439 if (DBG) Slog.d(TAG, "Binder is dead - unregister Ble App");
Nitin Arorad055adb2015-03-02 15:03:51 -0800440 if (mBleAppCount > 0) --mBleAppCount;
441
442 if (mBleAppCount == 0) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700443 if (DBG) Slog.d(TAG, "Disabling LE only mode after application crash");
Nitin Arorad055adb2015-03-02 15:03:51 -0800444 try {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700445 mBluetoothLock.readLock().lock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800446 if (mBluetooth != null) {
447 mBluetooth.onBrEdrDown();
448 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700449 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700450 Slog.e(TAG,"Unable to call onBrEdrDown", e);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700451 } finally {
452 mBluetoothLock.readLock().unlock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800453 }
454 }
455 }
456 }
457
458 /** Internal death rec list */
459 Map<IBinder, ClientDeathRecipient> mBleApps = new HashMap<IBinder, ClientDeathRecipient>();
460
Wei Wang67d84162015-04-26 17:04:29 -0700461 @Override
462 public boolean isBleScanAlwaysAvailable() {
463 try {
464 return (Settings.Global.getInt(mContentResolver,
465 Settings.Global.BLE_SCAN_ALWAYS_AVAILABLE)) != 0;
466 } catch (SettingNotFoundException e) {
467 }
468 return false;
469 }
470
Wei Wange4a744b2015-06-11 17:50:29 -0700471 // Monitor change of BLE scan only mode settings.
472 private void registerForBleScanModeChange() {
473 ContentObserver contentObserver = new ContentObserver(null) {
474 @Override
475 public void onChange(boolean selfChange) {
476 if (!isBleScanAlwaysAvailable()) {
477 disableBleScanMode();
478 clearBleApps();
479 try {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700480 mBluetoothLock.readLock().lock();
Wei Wange4a744b2015-06-11 17:50:29 -0700481 if (mBluetooth != null) mBluetooth.onBrEdrDown();
482 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700483 Slog.e(TAG, "error when disabling bluetooth", e);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700484 } finally {
485 mBluetoothLock.readLock().unlock();
Wei Wange4a744b2015-06-11 17:50:29 -0700486 }
487 }
488 }
489 };
490
491 mContentResolver.registerContentObserver(
492 Settings.Global.getUriFor(Settings.Global.BLE_SCAN_ALWAYS_AVAILABLE),
493 false, contentObserver);
494 }
495
496 // Disable ble scan only mode.
497 private void disableBleScanMode() {
498 try {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700499 mBluetoothLock.writeLock().lock();
Wei Wange4a744b2015-06-11 17:50:29 -0700500 if (mBluetooth != null && (mBluetooth.getState() != BluetoothAdapter.STATE_ON)) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700501 if (DBG) Slog.d(TAG, "Reseting the mEnable flag for clean disable");
Wei Wange4a744b2015-06-11 17:50:29 -0700502 mEnable = false;
503 }
504 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700505 Slog.e(TAG, "getState()", e);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700506 } finally {
507 mBluetoothLock.writeLock().unlock();
Wei Wange4a744b2015-06-11 17:50:29 -0700508 }
509 }
510
Nitin Arorad055adb2015-03-02 15:03:51 -0800511 public int updateBleAppCount(IBinder token, boolean enable) {
512 if (enable) {
513 ClientDeathRecipient r = mBleApps.get(token);
514 if (r == null) {
515 ClientDeathRecipient deathRec = new ClientDeathRecipient();
516 try {
517 token.linkToDeath(deathRec, 0);
518 } catch (RemoteException ex) {
519 throw new IllegalArgumentException("Wake lock is already dead.");
520 }
521 mBleApps.put(token, deathRec);
522 synchronized (this) {
523 ++mBleAppCount;
524 }
Jeff Sharkey67609c72016-03-05 14:29:13 -0700525 if (DBG) Slog.d(TAG, "Registered for death Notification");
Nitin Arorad055adb2015-03-02 15:03:51 -0800526 }
527
528 } else {
529 ClientDeathRecipient r = mBleApps.get(token);
530 if (r != null) {
Wei Wange4a744b2015-06-11 17:50:29 -0700531 // Unregister death recipient as the app goes away.
532 token.unlinkToDeath(r, 0);
Nitin Arorad055adb2015-03-02 15:03:51 -0800533 mBleApps.remove(token);
534 synchronized (this) {
535 if (mBleAppCount > 0) --mBleAppCount;
536 }
Jeff Sharkey67609c72016-03-05 14:29:13 -0700537 if (DBG) Slog.d(TAG, "Unregistered for death Notification");
Nitin Arorad055adb2015-03-02 15:03:51 -0800538 }
539 }
Jeff Sharkey67609c72016-03-05 14:29:13 -0700540 if (DBG) Slog.d(TAG, "Updated BleAppCount" + mBleAppCount);
Nitin Arorad055adb2015-03-02 15:03:51 -0800541 if (mBleAppCount == 0 && mEnable) {
Wei Wange4a744b2015-06-11 17:50:29 -0700542 disableBleScanMode();
Nitin Arorad055adb2015-03-02 15:03:51 -0800543 }
544 return mBleAppCount;
545 }
546
Wei Wange4a744b2015-06-11 17:50:29 -0700547 // Clear all apps using BLE scan only mode.
548 private void clearBleApps() {
549 synchronized (this) {
550 mBleApps.clear();
551 mBleAppCount = 0;
552 }
553 }
554
Nitin Arorad055adb2015-03-02 15:03:51 -0800555 /** @hide*/
556 public boolean isBleAppPresent() {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700557 if (DBG) Slog.d(TAG, "isBleAppPresent() count: " + mBleAppCount);
Nitin Arorad055adb2015-03-02 15:03:51 -0800558 return (mBleAppCount > 0);
559 }
560
561 /**
562 * Action taken when GattService is turned off
563 */
564 private void onBluetoothGattServiceUp() {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700565 if (DBG) Slog.d(TAG,"BluetoothGatt Service is Up");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700566 try {
567 mBluetoothLock.readLock().lock();
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700568 if (isBleAppPresent() == false && mBluetooth != null
569 && mBluetooth.getState() == BluetoothAdapter.STATE_BLE_ON) {
Nitin Arorad055adb2015-03-02 15:03:51 -0800570 mBluetooth.onLeServiceUp();
571
572 // waive WRITE_SECURE_SETTINGS permission check
573 long callingIdentity = Binder.clearCallingIdentity();
574 persistBluetoothSetting(BLUETOOTH_ON_BLUETOOTH);
575 Binder.restoreCallingIdentity(callingIdentity);
576 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700577 } catch (RemoteException e) {
578 Slog.e(TAG,"Unable to call onServiceUp", e);
579 } finally {
580 mBluetoothLock.readLock().unlock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800581 }
582 }
583
584 /**
585 * Inform BluetoothAdapter instances that BREDR part is down
586 * and turn off all service and stack if no LE app needs it
587 */
588 private void sendBrEdrDownCallback() {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700589 if (DBG) Slog.d(TAG,"Calling sendBrEdrDownCallback callbacks");
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700590
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700591 if (mBluetooth == null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700592 Slog.w(TAG, "Bluetooth handle is null");
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700593 return;
594 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800595
596 if (isBleAppPresent() == false) {
597 try {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700598 mBluetoothLock.readLock().lock();
599 if (mBluetooth != null) mBluetooth.onBrEdrDown();
600 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700601 Slog.e(TAG, "Call to onBrEdrDown() failed.", e);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700602 } finally {
603 mBluetoothLock.readLock().unlock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800604 }
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700605 } else {
606 // Need to stay at BLE ON. Disconnect all Gatt connections
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700607 try {
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700608 mBluetoothGatt.unregAll();
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700609 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700610 Slog.e(TAG, "Unable to disconnect all apps.", e);
Nitin Arorad055adb2015-03-02 15:03:51 -0800611 }
612 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800613 }
614
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700615 public boolean enableNoAutoConnect()
616 {
617 mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
618 "Need BLUETOOTH ADMIN permission");
Zhihai Xu40874a02012-10-08 17:57:03 -0700619
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700620 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700621 Slog.d(TAG,"enableNoAutoConnect(): mBluetooth =" + mBluetooth +
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700622 " mBinding = " + mBinding);
623 }
Martijn Coenen8385c5a2012-11-29 10:14:16 -0800624 int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
625
626 if (callingAppId != Process.NFC_UID) {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700627 throw new SecurityException("no permission to enable Bluetooth quietly");
628 }
Martijn Coenen8385c5a2012-11-29 10:14:16 -0800629
Zhihai Xu401202b2012-12-03 11:36:21 -0800630 synchronized(mReceiver) {
631 mQuietEnableExternal = true;
632 mEnableExternal = true;
633 sendEnableMsg(true);
634 }
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700635 return true;
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700636 }
Ajay Panicker4bb48302016-03-31 14:14:27 -0700637
Svetoslav Ganovf9e2ad02016-06-29 17:31:44 -0700638 public boolean enable(String packageName) throws RemoteException {
639 final int callingUid = Binder.getCallingUid();
640 final boolean callerSystem = UserHandle.getAppId(callingUid) == Process.SYSTEM_UID;
641
642 if (!callerSystem) {
643 if (!checkIfCallerIsForegroundUser()) {
644 Slog.w(TAG, "enable(): not allowed for non-active and non system user");
645 return false;
646 }
647
648 mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
649 "Need BLUETOOTH ADMIN permission");
650
651 if (!isEnabled() && mPermissionReviewRequired
652 && startConsentUiIfNeeded(packageName, callingUid,
653 BluetoothAdapter.ACTION_REQUEST_ENABLE)) {
654 return false;
655 }
fredcf2458862012-04-16 15:18:27 -0700656 }
657
Zhihai Xu401202b2012-12-03 11:36:21 -0800658 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700659 Slog.d(TAG,"enable(): mBluetooth =" + mBluetooth +
Sanket Agarwal090bf552016-04-21 14:10:55 -0700660 " mBinding = " + mBinding + " mState = " + mState);
661 }
Zhihai Xu401202b2012-12-03 11:36:21 -0800662
663 synchronized(mReceiver) {
664 mQuietEnableExternal = false;
665 mEnableExternal = true;
666 // waive WRITE_SECURE_SETTINGS permission check
Zhihai Xu401202b2012-12-03 11:36:21 -0800667 sendEnableMsg(false);
668 }
Jeff Sharkey67609c72016-03-05 14:29:13 -0700669 if (DBG) Slog.d(TAG, "enable returning");
Zhihai Xu401202b2012-12-03 11:36:21 -0800670 return true;
fredc0f420372012-04-12 00:02:00 -0700671 }
672
Svetoslav Ganovf9e2ad02016-06-29 17:31:44 -0700673 public boolean disable(String packageName, boolean persist) throws RemoteException {
674 final int callingUid = Binder.getCallingUid();
675 final boolean callerSystem = UserHandle.getAppId(callingUid) == Process.SYSTEM_UID;
Zhihai Xu40874a02012-10-08 17:57:03 -0700676
Svetoslav Ganovf9e2ad02016-06-29 17:31:44 -0700677 if (!callerSystem) {
678 if (!checkIfCallerIsForegroundUser()) {
679 Slog.w(TAG, "disable(): not allowed for non-active and non system user");
680 return false;
681 }
682
683 mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
684 "Need BLUETOOTH ADMIN permission");
685
686 if (isEnabled() && mPermissionReviewRequired
687 && startConsentUiIfNeeded(packageName, callingUid,
688 BluetoothAdapter.ACTION_REQUEST_DISABLE)) {
689 return false;
690 }
Zhihai Xu40874a02012-10-08 17:57:03 -0700691 }
692
fredcf2458862012-04-16 15:18:27 -0700693 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700694 Slog.d(TAG,"disable(): mBluetooth = " + mBluetooth +
Matthew Xiecdce0b92012-07-12 19:06:15 -0700695 " mBinding = " + mBinding);
696 }
fredcf2458862012-04-16 15:18:27 -0700697
Zhihai Xu401202b2012-12-03 11:36:21 -0800698 synchronized(mReceiver) {
699 if (persist) {
700 // waive WRITE_SECURE_SETTINGS permission check
701 long callingIdentity = Binder.clearCallingIdentity();
702 persistBluetoothSetting(BLUETOOTH_OFF);
703 Binder.restoreCallingIdentity(callingIdentity);
704 }
705 mEnableExternal = false;
706 sendDisableMsg();
707 }
fredc0f420372012-04-12 00:02:00 -0700708 return true;
709 }
710
Svetoslav Ganovf9e2ad02016-06-29 17:31:44 -0700711 private boolean startConsentUiIfNeeded(String packageName,
712 int callingUid, String intentAction) throws RemoteException {
713 try {
714 // Validate the package only if we are going to use it
715 ApplicationInfo applicationInfo = mContext.getPackageManager()
716 .getApplicationInfoAsUser(packageName,
717 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
718 UserHandle.getUserId(callingUid));
719 if (applicationInfo.uid != callingUid) {
720 throw new SecurityException("Package " + callingUid
721 + " not in uid " + callingUid);
722 }
723
724 // Legacy apps in permission review mode trigger a user prompt
725 if (applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
726 Intent intent = new Intent(intentAction);
727 mContext.startActivity(intent);
728 return true;
729 }
730 } catch (PackageManager.NameNotFoundException e) {
731 throw new RemoteException(e.getMessage());
732 }
733 return false;
734 }
735
fredc649fe492012-04-19 01:07:18 -0700736 public void unbindAndFinish() {
fredcf2458862012-04-16 15:18:27 -0700737 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700738 Slog.d(TAG,"unbindAndFinish(): " + mBluetooth +
Matthew Xiecdce0b92012-07-12 19:06:15 -0700739 " mBinding = " + mBinding);
fredcf2458862012-04-16 15:18:27 -0700740 }
741
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700742 try {
743 mBluetoothLock.writeLock().lock();
fredc0f420372012-04-12 00:02:00 -0700744 if (mUnbinding) return;
745 mUnbinding = true;
Pavlin Radoslavove47ec142016-06-01 22:25:18 -0700746 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
Pavlin Radoslavov74f60c02016-09-21 17:28:11 -0700747 mHandler.removeMessages(MESSAGE_BIND_PROFILE_SERVICE);
Zhihai Xu40874a02012-10-08 17:57:03 -0700748 if (mBluetooth != null) {
Andre Eisenbach305fdab2015-11-11 21:43:26 -0800749 //Unregister callback object
750 try {
751 mBluetooth.unregisterCallback(mBluetoothCallback);
752 } catch (RemoteException re) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700753 Slog.e(TAG, "Unable to unregister BluetoothCallback",re);
fredcbf072a72012-05-09 16:52:50 -0700754 }
Andre Eisenbach305fdab2015-11-11 21:43:26 -0800755
Jeff Sharkey67609c72016-03-05 14:29:13 -0700756 if (DBG) Slog.d(TAG, "Sending unbind request.");
Marie Janssen9db28eb2016-01-12 16:05:15 -0800757 mBluetoothBinder = null;
fredcd6883532012-04-25 17:46:13 -0700758 mBluetooth = null;
759 //Unbind
fredc0f420372012-04-12 00:02:00 -0700760 mContext.unbindService(mConnection);
fredcd6883532012-04-25 17:46:13 -0700761 mUnbinding = false;
Zhihai Xu40874a02012-10-08 17:57:03 -0700762 mBinding = false;
fredcf2458862012-04-16 15:18:27 -0700763 } else {
764 mUnbinding=false;
fredc0f420372012-04-12 00:02:00 -0700765 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800766 mBluetoothGatt = null;
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700767 } finally {
768 mBluetoothLock.writeLock().unlock();
fredc0f420372012-04-12 00:02:00 -0700769 }
770 }
771
Matthew Xieddf7e472013-03-01 18:41:02 -0800772 public IBluetoothGatt getBluetoothGatt() {
773 // sync protection
774 return mBluetoothGatt;
775 }
776
Benjamin Franze8b98922014-11-12 15:57:54 +0000777 @Override
778 public boolean bindBluetoothProfileService(int bluetoothProfile,
779 IBluetoothProfileServiceConnection proxy) {
780 if (!mEnable) {
781 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700782 Slog.d(TAG, "Trying to bind to profile: " + bluetoothProfile +
Benjamin Franze8b98922014-11-12 15:57:54 +0000783 ", while Bluetooth was disabled");
784 }
785 return false;
786 }
787 synchronized (mProfileServices) {
788 ProfileServiceConnections psc = mProfileServices.get(new Integer(bluetoothProfile));
789 if (psc == null) {
790 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700791 Slog.d(TAG, "Creating new ProfileServiceConnections object for"
Benjamin Franze8b98922014-11-12 15:57:54 +0000792 + " profile: " + bluetoothProfile);
793 }
Benjamin Franz5b614592014-12-09 18:58:45 +0000794
795 if (bluetoothProfile != BluetoothProfile.HEADSET) return false;
796
797 Intent intent = new Intent(IBluetoothHeadset.class.getName());
Benjamin Franze8b98922014-11-12 15:57:54 +0000798 psc = new ProfileServiceConnections(intent);
Benjamin Franz5b614592014-12-09 18:58:45 +0000799 if (!psc.bindService()) return false;
800
Benjamin Franze8b98922014-11-12 15:57:54 +0000801 mProfileServices.put(new Integer(bluetoothProfile), psc);
Benjamin Franze8b98922014-11-12 15:57:54 +0000802 }
803 }
804
805 // Introducing a delay to give the client app time to prepare
806 Message addProxyMsg = mHandler.obtainMessage(MESSAGE_ADD_PROXY_DELAYED);
807 addProxyMsg.arg1 = bluetoothProfile;
808 addProxyMsg.obj = proxy;
809 mHandler.sendMessageDelayed(addProxyMsg, ADD_PROXY_DELAY_MS);
810 return true;
811 }
812
813 @Override
814 public void unbindBluetoothProfileService(int bluetoothProfile,
815 IBluetoothProfileServiceConnection proxy) {
816 synchronized (mProfileServices) {
817 ProfileServiceConnections psc = mProfileServices.get(new Integer(bluetoothProfile));
818 if (psc == null) {
819 return;
820 }
821 psc.removeProxy(proxy);
822 }
823 }
824
825 private void unbindAllBluetoothProfileServices() {
826 synchronized (mProfileServices) {
827 for (Integer i : mProfileServices.keySet()) {
828 ProfileServiceConnections psc = mProfileServices.get(i);
Benjamin Franz5b614592014-12-09 18:58:45 +0000829 try {
830 mContext.unbindService(psc);
831 } catch (IllegalArgumentException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700832 Slog.e(TAG, "Unable to unbind service with intent: " + psc.mIntent, e);
Benjamin Franz5b614592014-12-09 18:58:45 +0000833 }
Benjamin Franze8b98922014-11-12 15:57:54 +0000834 psc.removeAllProxies();
835 }
836 mProfileServices.clear();
837 }
838 }
839
840 /**
Miao Chou658bf2f2015-06-26 17:14:35 -0700841 * Send enable message and set adapter name and address. Called when the boot phase becomes
842 * PHASE_SYSTEM_SERVICES_READY.
843 */
844 public void handleOnBootPhase() {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700845 if (DBG) Slog.d(TAG, "Bluetooth boot completed");
Miao Chou658bf2f2015-06-26 17:14:35 -0700846 if (mEnableExternal && isBluetoothPersistedStateOnBluetooth()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700847 if (DBG) Slog.d(TAG, "Auto-enabling Bluetooth.");
Miao Chou658bf2f2015-06-26 17:14:35 -0700848 sendEnableMsg(mQuietEnableExternal);
Ajay Panickerbf796d82016-03-11 13:47:20 -0800849 } else if (!isNameAndAddressSet()) {
850 if (DBG) Slog.d(TAG, "Getting adapter name and address");
Ajay Panicker4bb48302016-03-31 14:14:27 -0700851 Message getMsg = mHandler.obtainMessage(MESSAGE_GET_NAME_AND_ADDRESS);
852 mHandler.sendMessage(getMsg);
Miao Chou658bf2f2015-06-26 17:14:35 -0700853 }
Miao Chou658bf2f2015-06-26 17:14:35 -0700854 }
855
856 /**
857 * Called when switching to a different foreground user.
858 */
859 public void handleOnSwitchUser(int userHandle) {
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -0700860 if (DBG) Slog.d(TAG, "User " + userHandle + " switched");
861 mHandler.obtainMessage(MESSAGE_USER_SWITCHED, userHandle, 0).sendToTarget();
862 }
863
864 /**
865 * Called when user is unlocked.
866 */
867 public void handleOnUnlockUser(int userHandle) {
868 if (DBG) Slog.d(TAG, "User " + userHandle + " unlocked");
869 mHandler.obtainMessage(MESSAGE_USER_UNLOCKED, userHandle, 0).sendToTarget();
Miao Chou658bf2f2015-06-26 17:14:35 -0700870 }
871
872 /**
Benjamin Franze8b98922014-11-12 15:57:54 +0000873 * This class manages the clients connected to a given ProfileService
874 * and maintains the connection with that service.
875 */
876 final private class ProfileServiceConnections implements ServiceConnection,
877 IBinder.DeathRecipient {
878 final RemoteCallbackList<IBluetoothProfileServiceConnection> mProxies =
879 new RemoteCallbackList <IBluetoothProfileServiceConnection>();
880 IBinder mService;
881 ComponentName mClassName;
882 Intent mIntent;
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700883 boolean mInvokingProxyCallbacks = false;
Benjamin Franze8b98922014-11-12 15:57:54 +0000884
885 ProfileServiceConnections(Intent intent) {
886 mService = null;
887 mClassName = null;
888 mIntent = intent;
889 }
890
Benjamin Franz5b614592014-12-09 18:58:45 +0000891 private boolean bindService() {
892 if (mIntent != null && mService == null &&
893 doBind(mIntent, this, 0, UserHandle.CURRENT_OR_SELF)) {
Benjamin Franze8b98922014-11-12 15:57:54 +0000894 Message msg = mHandler.obtainMessage(MESSAGE_BIND_PROFILE_SERVICE);
895 msg.obj = this;
896 mHandler.sendMessageDelayed(msg, TIMEOUT_BIND_MS);
Benjamin Franz5b614592014-12-09 18:58:45 +0000897 return true;
Benjamin Franze8b98922014-11-12 15:57:54 +0000898 }
Jeff Sharkey67609c72016-03-05 14:29:13 -0700899 Slog.w(TAG, "Unable to bind with intent: " + mIntent);
Benjamin Franz5b614592014-12-09 18:58:45 +0000900 return false;
Benjamin Franze8b98922014-11-12 15:57:54 +0000901 }
902
903 private void addProxy(IBluetoothProfileServiceConnection proxy) {
904 mProxies.register(proxy);
905 if (mService != null) {
906 try{
907 proxy.onServiceConnected(mClassName, mService);
908 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700909 Slog.e(TAG, "Unable to connect to proxy", e);
Benjamin Franze8b98922014-11-12 15:57:54 +0000910 }
911 } else {
912 if (!mHandler.hasMessages(MESSAGE_BIND_PROFILE_SERVICE, this)) {
913 Message msg = mHandler.obtainMessage(MESSAGE_BIND_PROFILE_SERVICE);
914 msg.obj = this;
915 mHandler.sendMessage(msg);
916 }
917 }
918 }
919
920 private void removeProxy(IBluetoothProfileServiceConnection proxy) {
921 if (proxy != null) {
922 if (mProxies.unregister(proxy)) {
923 try {
924 proxy.onServiceDisconnected(mClassName);
925 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700926 Slog.e(TAG, "Unable to disconnect proxy", e);
Benjamin Franze8b98922014-11-12 15:57:54 +0000927 }
928 }
929 } else {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700930 Slog.w(TAG, "Trying to remove a null proxy");
Benjamin Franze8b98922014-11-12 15:57:54 +0000931 }
932 }
933
934 private void removeAllProxies() {
935 onServiceDisconnected(mClassName);
936 mProxies.kill();
937 }
938
939 @Override
940 public void onServiceConnected(ComponentName className, IBinder service) {
941 // remove timeout message
942 mHandler.removeMessages(MESSAGE_BIND_PROFILE_SERVICE, this);
943 mService = service;
944 mClassName = className;
945 try {
946 mService.linkToDeath(this, 0);
947 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700948 Slog.e(TAG, "Unable to linkToDeath", e);
Benjamin Franze8b98922014-11-12 15:57:54 +0000949 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700950
951 if (mInvokingProxyCallbacks) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700952 Slog.e(TAG, "Proxy callbacks already in progress.");
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700953 return;
Benjamin Franze8b98922014-11-12 15:57:54 +0000954 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700955 mInvokingProxyCallbacks = true;
956
957 final int n = mProxies.beginBroadcast();
958 try {
959 for (int i = 0; i < n; i++) {
960 try {
961 mProxies.getBroadcastItem(i).onServiceConnected(className, service);
962 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700963 Slog.e(TAG, "Unable to connect to proxy", e);
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700964 }
965 }
966 } finally {
967 mProxies.finishBroadcast();
968 mInvokingProxyCallbacks = false;
969 }
Benjamin Franze8b98922014-11-12 15:57:54 +0000970 }
971
972 @Override
973 public void onServiceDisconnected(ComponentName className) {
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700974 if (mService == null) return;
Benjamin Franze8b98922014-11-12 15:57:54 +0000975 mService.unlinkToDeath(this, 0);
976 mService = null;
977 mClassName = null;
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700978
979 if (mInvokingProxyCallbacks) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700980 Slog.e(TAG, "Proxy callbacks already in progress.");
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700981 return;
Benjamin Franze8b98922014-11-12 15:57:54 +0000982 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700983 mInvokingProxyCallbacks = true;
984
985 final int n = mProxies.beginBroadcast();
986 try {
987 for (int i = 0; i < n; i++) {
988 try {
989 mProxies.getBroadcastItem(i).onServiceDisconnected(className);
990 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700991 Slog.e(TAG, "Unable to disconnect from proxy", e);
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700992 }
993 }
994 } finally {
995 mProxies.finishBroadcast();
996 mInvokingProxyCallbacks = false;
997 }
Benjamin Franze8b98922014-11-12 15:57:54 +0000998 }
999
1000 @Override
1001 public void binderDied() {
1002 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001003 Slog.w(TAG, "Profile service for profile: " + mClassName
Benjamin Franze8b98922014-11-12 15:57:54 +00001004 + " died.");
1005 }
1006 onServiceDisconnected(mClassName);
1007 // Trigger rebind
1008 Message msg = mHandler.obtainMessage(MESSAGE_BIND_PROFILE_SERVICE);
1009 msg.obj = this;
1010 mHandler.sendMessageDelayed(msg, TIMEOUT_BIND_MS);
1011 }
1012 }
1013
fredcbf072a72012-05-09 16:52:50 -07001014 private void sendBluetoothStateCallback(boolean isUp) {
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001015 try {
1016 int n = mStateChangeCallbacks.beginBroadcast();
Jeff Sharkey67609c72016-03-05 14:29:13 -07001017 if (DBG) Slog.d(TAG,"Broadcasting onBluetoothStateChange("+isUp+") to " + n + " receivers.");
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001018 for (int i=0; i <n;i++) {
1019 try {
1020 mStateChangeCallbacks.getBroadcastItem(i).onBluetoothStateChange(isUp);
1021 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001022 Slog.e(TAG, "Unable to call onBluetoothStateChange() on callback #" + i , e);
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001023 }
fredcbf072a72012-05-09 16:52:50 -07001024 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001025 } finally {
1026 mStateChangeCallbacks.finishBroadcast();
fredcbf072a72012-05-09 16:52:50 -07001027 }
fredcbf072a72012-05-09 16:52:50 -07001028 }
1029
1030 /**
Zhihai Xu40874a02012-10-08 17:57:03 -07001031 * Inform BluetoothAdapter instances that Adapter service is up
1032 */
1033 private void sendBluetoothServiceUpCallback() {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001034 if (DBG) Slog.d(TAG,"Calling onBluetoothServiceUp callbacks");
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001035 try {
1036 int n = mCallbacks.beginBroadcast();
Jeff Sharkey67609c72016-03-05 14:29:13 -07001037 Slog.d(TAG,"Broadcasting onBluetoothServiceUp() to " + n + " receivers.");
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001038 for (int i=0; i <n;i++) {
1039 try {
1040 mCallbacks.getBroadcastItem(i).onBluetoothServiceUp(mBluetooth);
1041 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001042 Slog.e(TAG, "Unable to call onBluetoothServiceUp() on callback #" + i, e);
Zhihai Xu40874a02012-10-08 17:57:03 -07001043 }
1044 }
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001045 } finally {
1046 mCallbacks.finishBroadcast();
Zhihai Xu40874a02012-10-08 17:57:03 -07001047 }
1048 }
1049 /**
fredcbf072a72012-05-09 16:52:50 -07001050 * Inform BluetoothAdapter instances that Adapter service is down
1051 */
1052 private void sendBluetoothServiceDownCallback() {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001053 if (DBG) Slog.d(TAG,"Calling onBluetoothServiceDown callbacks");
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001054 try {
1055 int n = mCallbacks.beginBroadcast();
Jeff Sharkey67609c72016-03-05 14:29:13 -07001056 Slog.d(TAG,"Broadcasting onBluetoothServiceDown() to " + n + " receivers.");
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001057 for (int i=0; i <n;i++) {
1058 try {
1059 mCallbacks.getBroadcastItem(i).onBluetoothServiceDown();
1060 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001061 Slog.e(TAG, "Unable to call onBluetoothServiceDown() on callback #" + i, e);
fredcd6883532012-04-25 17:46:13 -07001062 }
1063 }
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001064 } finally {
1065 mCallbacks.finishBroadcast();
fredcd6883532012-04-25 17:46:13 -07001066 }
1067 }
Svet Ganov408abf72015-05-12 19:13:36 -07001068
fredc0f420372012-04-12 00:02:00 -07001069 public String getAddress() {
Matthew Xieaf5ddbf2012-12-04 10:47:43 -08001070 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
Svet Ganov408abf72015-05-12 19:13:36 -07001071 "Need BLUETOOTH permission");
Zhihai Xu40874a02012-10-08 17:57:03 -07001072
Zhihai Xu6eb76522012-11-29 15:41:04 -08001073 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
Svet Ganov408abf72015-05-12 19:13:36 -07001074 (!checkIfCallerIsForegroundUser())) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001075 Slog.w(TAG,"getAddress(): not allowed for non-active and non system user");
Zhihai Xu6eb76522012-11-29 15:41:04 -08001076 return null;
Zhihai Xu40874a02012-10-08 17:57:03 -07001077 }
1078
Svet Ganov408abf72015-05-12 19:13:36 -07001079 if (mContext.checkCallingOrSelfPermission(Manifest.permission.LOCAL_MAC_ADDRESS)
1080 != PackageManager.PERMISSION_GRANTED) {
1081 return BluetoothAdapter.DEFAULT_MAC_ADDRESS;
1082 }
1083
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001084 try {
1085 mBluetoothLock.readLock().lock();
1086 if (mBluetooth != null) return mBluetooth.getAddress();
1087 } catch (RemoteException e) {
1088 Slog.e(TAG, "getAddress(): Unable to retrieve address remotely. Returning cached address", e);
1089 } finally {
1090 mBluetoothLock.readLock().unlock();
fredc116d1d462012-04-20 14:47:08 -07001091 }
Ajay Panickerbf796d82016-03-11 13:47:20 -08001092
Matthew Xiecdce0b92012-07-12 19:06:15 -07001093 // mAddress is accessed from outside.
1094 // It is alright without a lock. Here, bluetooth is off, no other thread is
1095 // changing mAddress
fredc0f420372012-04-12 00:02:00 -07001096 return mAddress;
1097 }
fredc649fe492012-04-19 01:07:18 -07001098
fredc0f420372012-04-12 00:02:00 -07001099 public String getName() {
Matthew Xieaf5ddbf2012-12-04 10:47:43 -08001100 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
1101 "Need BLUETOOTH permission");
Zhihai Xu40874a02012-10-08 17:57:03 -07001102
Zhihai Xu6eb76522012-11-29 15:41:04 -08001103 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
1104 (!checkIfCallerIsForegroundUser())) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001105 Slog.w(TAG,"getName(): not allowed for non-active and non system user");
Zhihai Xu6eb76522012-11-29 15:41:04 -08001106 return null;
Zhihai Xu40874a02012-10-08 17:57:03 -07001107 }
1108
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001109 try {
1110 mBluetoothLock.readLock().lock();
1111 if (mBluetooth != null) return mBluetooth.getName();
1112 } catch (RemoteException e) {
1113 Slog.e(TAG, "getName(): Unable to retrieve name remotely. Returning cached name", e);
1114 } finally {
1115 mBluetoothLock.readLock().unlock();
fredc116d1d462012-04-20 14:47:08 -07001116 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001117
Matthew Xiecdce0b92012-07-12 19:06:15 -07001118 // mName is accessed from outside.
1119 // It alright without a lock. Here, bluetooth is off, no other thread is
1120 // changing mName
fredc0f420372012-04-12 00:02:00 -07001121 return mName;
1122 }
1123
fredc0f420372012-04-12 00:02:00 -07001124 private class BluetoothServiceConnection implements ServiceConnection {
fredc0f420372012-04-12 00:02:00 -07001125 public void onServiceConnected(ComponentName className, IBinder service) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001126 if (DBG) Slog.d(TAG, "BluetoothServiceConnection: " + className.getClassName());
fredc0f420372012-04-12 00:02:00 -07001127 Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_SERVICE_CONNECTED);
Matthew Xieddf7e472013-03-01 18:41:02 -08001128 // TBD if (className.getClassName().equals(IBluetooth.class.getName())) {
1129 if (className.getClassName().equals("com.android.bluetooth.btservice.AdapterService")) {
1130 msg.arg1 = SERVICE_IBLUETOOTH;
1131 // } else if (className.getClassName().equals(IBluetoothGatt.class.getName())) {
1132 } else if (className.getClassName().equals("com.android.bluetooth.gatt.GattService")) {
1133 msg.arg1 = SERVICE_IBLUETOOTHGATT;
1134 } else {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001135 Slog.e(TAG, "Unknown service connected: " + className.getClassName());
Matthew Xieddf7e472013-03-01 18:41:02 -08001136 return;
1137 }
fredc0f420372012-04-12 00:02:00 -07001138 msg.obj = service;
1139 mHandler.sendMessage(msg);
1140 }
1141
1142 public void onServiceDisconnected(ComponentName className) {
fredc0f420372012-04-12 00:02:00 -07001143 // Called if we unexpected disconnected.
Jeff Sharkey67609c72016-03-05 14:29:13 -07001144 if (DBG) Slog.d(TAG, "BluetoothServiceConnection, disconnected: " +
Matthew Xieddf7e472013-03-01 18:41:02 -08001145 className.getClassName());
fredc0f420372012-04-12 00:02:00 -07001146 Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED);
Matthew Xieddf7e472013-03-01 18:41:02 -08001147 if (className.getClassName().equals("com.android.bluetooth.btservice.AdapterService")) {
1148 msg.arg1 = SERVICE_IBLUETOOTH;
1149 } else if (className.getClassName().equals("com.android.bluetooth.gatt.GattService")) {
1150 msg.arg1 = SERVICE_IBLUETOOTHGATT;
1151 } else {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001152 Slog.e(TAG, "Unknown service disconnected: " + className.getClassName());
Matthew Xieddf7e472013-03-01 18:41:02 -08001153 return;
1154 }
fredc0f420372012-04-12 00:02:00 -07001155 mHandler.sendMessage(msg);
1156 }
1157 }
1158
1159 private BluetoothServiceConnection mConnection = new BluetoothServiceConnection();
1160
Zhihai Xu40874a02012-10-08 17:57:03 -07001161 private class BluetoothHandler extends Handler {
Ajay Panicker4bb48302016-03-31 14:14:27 -07001162 boolean mGetNameAddressOnly = false;
1163
Zhihai Xu40874a02012-10-08 17:57:03 -07001164 public BluetoothHandler(Looper looper) {
1165 super(looper);
1166 }
1167
fredc0f420372012-04-12 00:02:00 -07001168 @Override
1169 public void handleMessage(Message msg) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001170 if (DBG) Slog.d (TAG, "Message: " + msg.what);
fredc0f420372012-04-12 00:02:00 -07001171 switch (msg.what) {
Ajay Panicker4bb48302016-03-31 14:14:27 -07001172 case MESSAGE_GET_NAME_AND_ADDRESS:
1173 if (DBG) Slog.d(TAG, "MESSAGE_GET_NAME_AND_ADDRESS");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001174 try {
1175 mBluetoothLock.writeLock().lock();
Ajay Panicker4bb48302016-03-31 14:14:27 -07001176 if ((mBluetooth == null) && (!mBinding)) {
1177 if (DBG) Slog.d(TAG, "Binding to service to get name and address");
1178 mGetNameAddressOnly = true;
1179 Message timeoutMsg = mHandler.obtainMessage(MESSAGE_TIMEOUT_BIND);
1180 mHandler.sendMessageDelayed(timeoutMsg, TIMEOUT_BIND_MS);
1181 Intent i = new Intent(IBluetooth.class.getName());
1182 if (!doBind(i, mConnection,
1183 Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT,
1184 UserHandle.CURRENT)) {
1185 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
1186 } else {
1187 mBinding = true;
1188 }
1189 } else if (mBluetooth != null) {
1190 try {
1191 storeNameAndAddress(mBluetooth.getName(),
1192 mBluetooth.getAddress());
1193 } catch (RemoteException re) {
1194 Slog.e(TAG, "Unable to grab names", re);
1195 }
1196 if (mGetNameAddressOnly && !mEnable) {
1197 unbindAndFinish();
1198 }
1199 mGetNameAddressOnly = false;
1200 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001201 } finally {
1202 mBluetoothLock.writeLock().unlock();
Ajay Panicker4bb48302016-03-31 14:14:27 -07001203 }
1204 break;
1205
Matthew Xiecdce0b92012-07-12 19:06:15 -07001206 case MESSAGE_ENABLE:
fredcf2458862012-04-16 15:18:27 -07001207 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001208 Slog.d(TAG, "MESSAGE_ENABLE: mBluetooth = " + mBluetooth);
fredc649fe492012-04-19 01:07:18 -07001209 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001210 mHandler.removeMessages(MESSAGE_RESTART_BLUETOOTH_SERVICE);
1211 mEnable = true;
Calvin Ona0b91d72016-06-15 17:58:23 -07001212
1213 // Use service interface to get the exact state
1214 try {
1215 mBluetoothLock.readLock().lock();
1216 if (mBluetooth != null) {
1217 int state = mBluetooth.getState();
1218 if (state == BluetoothAdapter.STATE_BLE_ON) {
1219 Slog.w(TAG, "BT is in BLE_ON State");
1220 mBluetooth.onLeServiceUp();
1221 break;
1222 }
1223 }
1224 } catch (RemoteException e) {
1225 Slog.e(TAG, "", e);
1226 } finally {
1227 mBluetoothLock.readLock().unlock();
1228 }
1229
1230 mQuietEnable = (msg.arg1 == 1);
Pavlin Radoslavove47ec142016-06-01 22:25:18 -07001231 if (mBluetooth == null) {
Calvin Ona0b91d72016-06-15 17:58:23 -07001232 handleEnable(mQuietEnable);
Pavlin Radoslavove47ec142016-06-01 22:25:18 -07001233 } else {
1234 //
1235 // We need to wait until transitioned to STATE_OFF and
1236 // the previous Bluetooth process has exited. The
1237 // waiting period has three components:
1238 // (a) Wait until the local state is STATE_OFF. This
1239 // is accomplished by "waitForOnOff(false, true)".
1240 // (b) Wait until the STATE_OFF state is updated to
1241 // all components.
1242 // (c) Wait until the Bluetooth process exits, and
1243 // ActivityManager detects it.
1244 // The waiting for (b) and (c) is accomplished by
1245 // delaying the MESSAGE_RESTART_BLUETOOTH_SERVICE
1246 // message. On slower devices, that delay needs to be
1247 // on the order of (2 * SERVICE_RESTART_TIME_MS).
1248 //
1249 waitForOnOff(false, true);
Pavlin Radoslavove47ec142016-06-01 22:25:18 -07001250 Message restartMsg = mHandler.obtainMessage(
1251 MESSAGE_RESTART_BLUETOOTH_SERVICE);
1252 mHandler.sendMessageDelayed(restartMsg,
1253 2 * SERVICE_RESTART_TIME_MS);
1254 }
fredc649fe492012-04-19 01:07:18 -07001255 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001256
fredc0f420372012-04-12 00:02:00 -07001257 case MESSAGE_DISABLE:
Zhihai Xu40874a02012-10-08 17:57:03 -07001258 mHandler.removeMessages(MESSAGE_RESTART_BLUETOOTH_SERVICE);
1259 if (mEnable && mBluetooth != null) {
1260 waitForOnOff(true, false);
1261 mEnable = false;
Zhihai Xu401202b2012-12-03 11:36:21 -08001262 handleDisable();
Zhihai Xu40874a02012-10-08 17:57:03 -07001263 waitForOnOff(false, false);
1264 } else {
1265 mEnable = false;
Zhihai Xu401202b2012-12-03 11:36:21 -08001266 handleDisable();
Zhihai Xu40874a02012-10-08 17:57:03 -07001267 }
fredc0f420372012-04-12 00:02:00 -07001268 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001269
fredc0f420372012-04-12 00:02:00 -07001270 case MESSAGE_REGISTER_ADAPTER:
1271 {
1272 IBluetoothManagerCallback callback = (IBluetoothManagerCallback) msg.obj;
fredcd6883532012-04-25 17:46:13 -07001273 boolean added = mCallbacks.register(callback);
Jeff Sharkey67609c72016-03-05 14:29:13 -07001274 Slog.d(TAG,"Added callback: " + (callback == null? "null": callback) +":" +added );
fredc0f420372012-04-12 00:02:00 -07001275 }
1276 break;
1277 case MESSAGE_UNREGISTER_ADAPTER:
1278 {
1279 IBluetoothManagerCallback callback = (IBluetoothManagerCallback) msg.obj;
fredcd6883532012-04-25 17:46:13 -07001280 boolean removed = mCallbacks.unregister(callback);
Jeff Sharkey67609c72016-03-05 14:29:13 -07001281 Slog.d(TAG,"Removed callback: " + (callback == null? "null": callback) +":" + removed);
fredc0f420372012-04-12 00:02:00 -07001282 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001283 }
fredc0f420372012-04-12 00:02:00 -07001284 case MESSAGE_REGISTER_STATE_CHANGE_CALLBACK:
1285 {
1286 IBluetoothStateChangeCallback callback = (IBluetoothStateChangeCallback) msg.obj;
Matthew Xie9b693992013-10-10 11:21:40 -07001287 if (callback != null) {
1288 mStateChangeCallbacks.register(callback);
1289 }
fredc0f420372012-04-12 00:02:00 -07001290 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001291 }
fredc0f420372012-04-12 00:02:00 -07001292 case MESSAGE_UNREGISTER_STATE_CHANGE_CALLBACK:
1293 {
1294 IBluetoothStateChangeCallback callback = (IBluetoothStateChangeCallback) msg.obj;
Matthew Xie9b693992013-10-10 11:21:40 -07001295 if (callback != null) {
1296 mStateChangeCallbacks.unregister(callback);
1297 }
fredc0f420372012-04-12 00:02:00 -07001298 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001299 }
Benjamin Franze8b98922014-11-12 15:57:54 +00001300 case MESSAGE_ADD_PROXY_DELAYED:
1301 {
1302 ProfileServiceConnections psc = mProfileServices.get(
1303 new Integer(msg.arg1));
1304 if (psc == null) {
1305 break;
1306 }
1307 IBluetoothProfileServiceConnection proxy =
1308 (IBluetoothProfileServiceConnection) msg.obj;
1309 psc.addProxy(proxy);
1310 break;
1311 }
1312 case MESSAGE_BIND_PROFILE_SERVICE:
1313 {
1314 ProfileServiceConnections psc = (ProfileServiceConnections) msg.obj;
1315 removeMessages(MESSAGE_BIND_PROFILE_SERVICE, msg.obj);
1316 if (psc == null) {
1317 break;
1318 }
1319 psc.bindService();
1320 break;
1321 }
fredc0f420372012-04-12 00:02:00 -07001322 case MESSAGE_BLUETOOTH_SERVICE_CONNECTED:
1323 {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001324 if (DBG) Slog.d(TAG,"MESSAGE_BLUETOOTH_SERVICE_CONNECTED: " + msg.arg1);
fredc0f420372012-04-12 00:02:00 -07001325
1326 IBinder service = (IBinder) msg.obj;
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001327 try {
1328 mBluetoothLock.writeLock().lock();
Matthew Xieddf7e472013-03-01 18:41:02 -08001329 if (msg.arg1 == SERVICE_IBLUETOOTHGATT) {
1330 mBluetoothGatt = IBluetoothGatt.Stub.asInterface(service);
Nitin Arorad055adb2015-03-02 15:03:51 -08001331 onBluetoothGattServiceUp();
Matthew Xieddf7e472013-03-01 18:41:02 -08001332 break;
1333 } // else must be SERVICE_IBLUETOOTH
1334
1335 //Remove timeout
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001336 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
Matthew Xieddf7e472013-03-01 18:41:02 -08001337
fredc0f420372012-04-12 00:02:00 -07001338 mBinding = false;
Marie Janssen9db28eb2016-01-12 16:05:15 -08001339 mBluetoothBinder = service;
fredc0f420372012-04-12 00:02:00 -07001340 mBluetooth = IBluetooth.Stub.asInterface(service);
fredc0f420372012-04-12 00:02:00 -07001341
Ajay Panicker4bb48302016-03-31 14:14:27 -07001342 if (!isNameAndAddressSet()) {
1343 Message getMsg = mHandler.obtainMessage(MESSAGE_GET_NAME_AND_ADDRESS);
1344 mHandler.sendMessage(getMsg);
1345 if (mGetNameAddressOnly) return;
1346 }
1347
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001348 try {
1349 boolean enableHciSnoopLog = (Settings.Secure.getInt(mContentResolver,
1350 Settings.Secure.BLUETOOTH_HCI_LOG, 0) == 1);
1351 if (!mBluetooth.configHciSnoopLog(enableHciSnoopLog)) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001352 Slog.e(TAG,"IBluetooth.configHciSnoopLog return false");
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001353 }
1354 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001355 Slog.e(TAG,"Unable to call configHciSnoopLog", e);
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001356 }
1357
Matthew Xiecdce0b92012-07-12 19:06:15 -07001358 //Register callback object
fredcbf072a72012-05-09 16:52:50 -07001359 try {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001360 mBluetooth.registerCallback(mBluetoothCallback);
1361 } catch (RemoteException re) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001362 Slog.e(TAG, "Unable to register BluetoothCallback",re);
fredcbf072a72012-05-09 16:52:50 -07001363 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001364 //Inform BluetoothAdapter instances that service is up
Zhihai Xu40874a02012-10-08 17:57:03 -07001365 sendBluetoothServiceUpCallback();
1366
Matthew Xiecdce0b92012-07-12 19:06:15 -07001367 //Do enable request
1368 try {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001369 if (mQuietEnable == false) {
1370 if(!mBluetooth.enable()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001371 Slog.e(TAG,"IBluetooth.enable() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001372 }
1373 }
1374 else
1375 {
1376 if(!mBluetooth.enableNoAutoConnect()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001377 Slog.e(TAG,"IBluetooth.enableNoAutoConnect() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001378 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001379 }
1380 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001381 Slog.e(TAG,"Unable to call enable()",e);
Matthew Xiecdce0b92012-07-12 19:06:15 -07001382 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001383 } finally {
1384 mBluetoothLock.writeLock().unlock();
Freda8c6df02012-07-11 10:25:23 -07001385 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001386
1387 if (!mEnable) {
1388 waitForOnOff(true, false);
Zhihai Xu401202b2012-12-03 11:36:21 -08001389 handleDisable();
Zhihai Xu40874a02012-10-08 17:57:03 -07001390 waitForOnOff(false, false);
1391 }
fredc649fe492012-04-19 01:07:18 -07001392 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001393 }
fredc649fe492012-04-19 01:07:18 -07001394 case MESSAGE_TIMEOUT_BIND: {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001395 Slog.e(TAG, "MESSAGE_TIMEOUT_BIND");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001396 mBluetoothLock.writeLock().lock();
1397 mBinding = false;
1398 mBluetoothLock.writeLock().unlock();
1399
fredc649fe492012-04-19 01:07:18 -07001400 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001401 }
fredcbf072a72012-05-09 16:52:50 -07001402 case MESSAGE_BLUETOOTH_STATE_CHANGE:
fredc0f420372012-04-12 00:02:00 -07001403 {
fredcbf072a72012-05-09 16:52:50 -07001404 int prevState = msg.arg1;
1405 int newState = msg.arg2;
Jeff Sharkey67609c72016-03-05 14:29:13 -07001406 if (DBG) Slog.d(TAG, "MESSAGE_BLUETOOTH_STATE_CHANGE: prevState = " + prevState + ", newState=" + newState);
Zhihai Xu40874a02012-10-08 17:57:03 -07001407 mState = newState;
1408 bluetoothStateChangeHandler(prevState, newState);
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001409 // handle error state transition case from TURNING_ON to OFF
1410 // unbind and rebind bluetooth service and enable bluetooth
Nitin Arorad055adb2015-03-02 15:03:51 -08001411 if ((prevState == BluetoothAdapter.STATE_BLE_TURNING_ON) &&
Calvin Ona0b91d72016-06-15 17:58:23 -07001412 (newState == BluetoothAdapter.STATE_OFF) &&
1413 (mBluetooth != null) && mEnable) {
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001414 recoverBluetoothServiceFromError();
1415 }
Nitin Arorad055adb2015-03-02 15:03:51 -08001416 if ((prevState == BluetoothAdapter.STATE_TURNING_ON) &&
Calvin Ona0b91d72016-06-15 17:58:23 -07001417 (newState == BluetoothAdapter.STATE_BLE_ON) &&
1418 (mBluetooth != null) && mEnable) {
Nitin Arorad055adb2015-03-02 15:03:51 -08001419 recoverBluetoothServiceFromError();
1420 }
Calvin Ona0b91d72016-06-15 17:58:23 -07001421 // If we tried to enable BT while BT was in the process of shutting down,
1422 // wait for the BT process to fully tear down and then force a restart
1423 // here. This is a bit of a hack (b/29363429).
1424 if ((prevState == BluetoothAdapter.STATE_BLE_TURNING_OFF) &&
1425 (newState == BluetoothAdapter.STATE_OFF)) {
1426 if (mEnable) {
1427 Slog.d(TAG, "Entering STATE_OFF but mEnabled is true; restarting.");
1428 waitForOnOff(false, true);
1429 Message restartMsg = mHandler.obtainMessage(
1430 MESSAGE_RESTART_BLUETOOTH_SERVICE);
1431 mHandler.sendMessageDelayed(restartMsg, 2 * SERVICE_RESTART_TIME_MS);
1432 }
1433 }
Nitin Arorad055adb2015-03-02 15:03:51 -08001434 if (newState == BluetoothAdapter.STATE_ON ||
Calvin Ona0b91d72016-06-15 17:58:23 -07001435 newState == BluetoothAdapter.STATE_BLE_ON) {
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001436 // bluetooth is working, reset the counter
1437 if (mErrorRecoveryRetryCounter != 0) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001438 Slog.w(TAG, "bluetooth is recovered from error");
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001439 mErrorRecoveryRetryCounter = 0;
1440 }
1441 }
fredc649fe492012-04-19 01:07:18 -07001442 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001443 }
fredc0f420372012-04-12 00:02:00 -07001444 case MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED:
1445 {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001446 Slog.e(TAG, "MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED: " + msg.arg1);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001447 try {
1448 mBluetoothLock.writeLock().lock();
Matthew Xieddf7e472013-03-01 18:41:02 -08001449 if (msg.arg1 == SERVICE_IBLUETOOTH) {
1450 // if service is unbinded already, do nothing and return
1451 if (mBluetooth == null) break;
1452 mBluetooth = null;
1453 } else if (msg.arg1 == SERVICE_IBLUETOOTHGATT) {
1454 mBluetoothGatt = null;
1455 break;
1456 } else {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001457 Slog.e(TAG, "Bad msg.arg1: " + msg.arg1);
Matthew Xieddf7e472013-03-01 18:41:02 -08001458 break;
1459 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001460 } finally {
1461 mBluetoothLock.writeLock().unlock();
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301462 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001463
1464 if (mEnable) {
1465 mEnable = false;
1466 // Send a Bluetooth Restart message
1467 Message restartMsg = mHandler.obtainMessage(
1468 MESSAGE_RESTART_BLUETOOTH_SERVICE);
1469 mHandler.sendMessageDelayed(restartMsg,
1470 SERVICE_RESTART_TIME_MS);
1471 }
1472
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001473 sendBluetoothServiceDownCallback();
Zhihai Xu40874a02012-10-08 17:57:03 -07001474
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001475 // Send BT state broadcast to update
1476 // the BT icon correctly
1477 if ((mState == BluetoothAdapter.STATE_TURNING_ON) ||
Calvin Ona0b91d72016-06-15 17:58:23 -07001478 (mState == BluetoothAdapter.STATE_ON)) {
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001479 bluetoothStateChangeHandler(BluetoothAdapter.STATE_ON,
1480 BluetoothAdapter.STATE_TURNING_OFF);
1481 mState = BluetoothAdapter.STATE_TURNING_OFF;
Zhihai Xu40874a02012-10-08 17:57:03 -07001482 }
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001483 if (mState == BluetoothAdapter.STATE_TURNING_OFF) {
1484 bluetoothStateChangeHandler(BluetoothAdapter.STATE_TURNING_OFF,
1485 BluetoothAdapter.STATE_OFF);
1486 }
1487
1488 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
1489 mState = BluetoothAdapter.STATE_OFF;
fredc649fe492012-04-19 01:07:18 -07001490 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001491 }
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301492 case MESSAGE_RESTART_BLUETOOTH_SERVICE:
1493 {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001494 Slog.d(TAG, "MESSAGE_RESTART_BLUETOOTH_SERVICE:"
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301495 +" Restart IBluetooth service");
1496 /* Enable without persisting the setting as
1497 it doesnt change when IBluetooth
1498 service restarts */
Zhihai Xu40874a02012-10-08 17:57:03 -07001499 mEnable = true;
Zhihai Xu401202b2012-12-03 11:36:21 -08001500 handleEnable(mQuietEnable);
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301501 break;
1502 }
1503
fredc0f420372012-04-12 00:02:00 -07001504 case MESSAGE_TIMEOUT_UNBIND:
1505 {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001506 Slog.e(TAG, "MESSAGE_TIMEOUT_UNBIND");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001507 mBluetoothLock.writeLock().lock();
1508 mUnbinding = false;
1509 mBluetoothLock.writeLock().unlock();
fredc649fe492012-04-19 01:07:18 -07001510 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001511 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001512
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001513 case MESSAGE_USER_SWITCHED: {
1514 if (DBG) Slog.d(TAG, "MESSAGE_USER_SWITCHED");
Zhihai Xu40874a02012-10-08 17:57:03 -07001515 mHandler.removeMessages(MESSAGE_USER_SWITCHED);
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001516
Zhihai Xu40874a02012-10-08 17:57:03 -07001517 /* disable and enable BT when detect a user switch */
1518 if (mEnable && mBluetooth != null) {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001519 try {
1520 mBluetoothLock.readLock().lock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001521 if (mBluetooth != null) {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001522 mBluetooth.unregisterCallback(mBluetoothCallback);
Zhihai Xu40874a02012-10-08 17:57:03 -07001523 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001524 } catch (RemoteException re) {
1525 Slog.e(TAG, "Unable to unregister", re);
1526 } finally {
1527 mBluetoothLock.readLock().unlock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001528 }
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001529
1530 if (mState == BluetoothAdapter.STATE_TURNING_OFF) {
1531 // MESSAGE_USER_SWITCHED happened right after MESSAGE_ENABLE
1532 bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_OFF);
1533 mState = BluetoothAdapter.STATE_OFF;
1534 }
1535 if (mState == BluetoothAdapter.STATE_OFF) {
1536 bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_TURNING_ON);
1537 mState = BluetoothAdapter.STATE_TURNING_ON;
1538 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001539
1540 waitForOnOff(true, false);
1541
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001542 if (mState == BluetoothAdapter.STATE_TURNING_ON) {
1543 bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_ON);
1544 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001545
Benjamin Franze8b98922014-11-12 15:57:54 +00001546 unbindAllBluetoothProfileServices();
Zhihai Xu40874a02012-10-08 17:57:03 -07001547 // disable
Zhihai Xu401202b2012-12-03 11:36:21 -08001548 handleDisable();
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001549 // Pbap service need receive STATE_TURNING_OFF intent to close
1550 bluetoothStateChangeHandler(BluetoothAdapter.STATE_ON,
1551 BluetoothAdapter.STATE_TURNING_OFF);
Zhihai Xu40874a02012-10-08 17:57:03 -07001552
Pavlin Radoslavov41401112016-06-27 15:25:18 -07001553 boolean didDisableTimeout = !waitForOnOff(false, true);
Zhihai Xu40874a02012-10-08 17:57:03 -07001554
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001555 bluetoothStateChangeHandler(BluetoothAdapter.STATE_TURNING_OFF,
Zhihai Xu40874a02012-10-08 17:57:03 -07001556 BluetoothAdapter.STATE_OFF);
Zhihai Xu40874a02012-10-08 17:57:03 -07001557 sendBluetoothServiceDownCallback();
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001558
Pavlin Radoslavove957a8a2016-05-24 15:28:41 -07001559 try {
1560 mBluetoothLock.writeLock().lock();
1561 if (mBluetooth != null) {
1562 mBluetooth = null;
1563 // Unbind
1564 mContext.unbindService(mConnection);
1565 }
1566 mBluetoothGatt = null;
1567 } finally {
1568 mBluetoothLock.writeLock().unlock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001569 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001570
Pavlin Radoslavov41401112016-06-27 15:25:18 -07001571 //
1572 // If disabling Bluetooth times out, wait for an
1573 // additional amount of time to ensure the process is
1574 // shut down completely before attempting to restart.
1575 //
1576 if (didDisableTimeout) {
1577 SystemClock.sleep(3000);
1578 } else {
1579 SystemClock.sleep(100);
1580 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001581
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001582 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
1583 mState = BluetoothAdapter.STATE_OFF;
Zhihai Xu40874a02012-10-08 17:57:03 -07001584 // enable
Zhihai Xu401202b2012-12-03 11:36:21 -08001585 handleEnable(mQuietEnable);
John Spurlock8a985d22014-02-25 09:40:05 -05001586 } else if (mBinding || mBluetooth != null) {
Zhihai Xu40874a02012-10-08 17:57:03 -07001587 Message userMsg = mHandler.obtainMessage(MESSAGE_USER_SWITCHED);
1588 userMsg.arg2 = 1 + msg.arg2;
1589 // if user is switched when service is being binding
1590 // delay sending MESSAGE_USER_SWITCHED
1591 mHandler.sendMessageDelayed(userMsg, USER_SWITCHED_TIME_MS);
1592 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001593 Slog.d(TAG, "delay MESSAGE_USER_SWITCHED " + userMsg.arg2);
Zhihai Xu40874a02012-10-08 17:57:03 -07001594 }
John Spurlock8a985d22014-02-25 09:40:05 -05001595 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001596 break;
1597 }
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001598 case MESSAGE_USER_UNLOCKED: {
1599 if (DBG) Slog.d(TAG, "MESSAGE_USER_UNLOCKED");
1600 mHandler.removeMessages(MESSAGE_USER_SWITCHED);
1601
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001602 if (mEnable && !mBinding && (mBluetooth == null)) {
1603 // We should be connected, but we gave up for some
1604 // reason; maybe the Bluetooth service wasn't encryption
1605 // aware, so try binding again.
1606 if (DBG) Slog.d(TAG, "Enabled but not bound; retrying after unlock");
1607 handleEnable(mQuietEnable);
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001608 }
1609 }
fredc0f420372012-04-12 00:02:00 -07001610 }
1611 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001612 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001613
Zhihai Xu401202b2012-12-03 11:36:21 -08001614 private void handleEnable(boolean quietMode) {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001615 mQuietEnable = quietMode;
1616
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001617 try {
1618 mBluetoothLock.writeLock().lock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001619 if ((mBluetooth == null) && (!mBinding)) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001620 //Start bind timeout and bind
1621 Message timeoutMsg=mHandler.obtainMessage(MESSAGE_TIMEOUT_BIND);
1622 mHandler.sendMessageDelayed(timeoutMsg,TIMEOUT_BIND_MS);
Matthew Xiecdce0b92012-07-12 19:06:15 -07001623 Intent i = new Intent(IBluetooth.class.getName());
Dianne Hackbornce09f5a2014-10-10 15:03:13 -07001624 if (!doBind(i, mConnection,Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT,
1625 UserHandle.CURRENT)) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001626 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
Zhihai Xu40874a02012-10-08 17:57:03 -07001627 } else {
1628 mBinding = true;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001629 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001630 } else if (mBluetooth != null) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001631 //Enable bluetooth
1632 try {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001633 if (!mQuietEnable) {
1634 if(!mBluetooth.enable()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001635 Slog.e(TAG,"IBluetooth.enable() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001636 }
1637 }
1638 else {
1639 if(!mBluetooth.enableNoAutoConnect()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001640 Slog.e(TAG,"IBluetooth.enableNoAutoConnect() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001641 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001642 }
1643 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001644 Slog.e(TAG,"Unable to call enable()",e);
Matthew Xiecdce0b92012-07-12 19:06:15 -07001645 }
1646 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001647 } finally {
1648 mBluetoothLock.writeLock().unlock();
Matthew Xiecdce0b92012-07-12 19:06:15 -07001649 }
1650 }
1651
Dianne Hackborn221ea892013-08-04 16:50:16 -07001652 boolean doBind(Intent intent, ServiceConnection conn, int flags, UserHandle user) {
1653 ComponentName comp = intent.resolveSystemService(mContext.getPackageManager(), 0);
1654 intent.setComponent(comp);
1655 if (comp == null || !mContext.bindServiceAsUser(intent, conn, flags, user)) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001656 Slog.e(TAG, "Fail to bind to: " + intent);
Dianne Hackborn221ea892013-08-04 16:50:16 -07001657 return false;
1658 }
1659 return true;
1660 }
1661
Zhihai Xu401202b2012-12-03 11:36:21 -08001662 private void handleDisable() {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001663 try {
1664 mBluetoothLock.readLock().lock();
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001665 if (mBluetooth != null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001666 if (DBG) Slog.d(TAG,"Sending off request.");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001667 if (!mBluetooth.disable()) {
1668 Slog.e(TAG,"IBluetooth.disable() returned false");
Matthew Xiecdce0b92012-07-12 19:06:15 -07001669 }
1670 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001671 } catch (RemoteException e) {
1672 Slog.e(TAG,"Unable to call disable()",e);
1673 } finally {
1674 mBluetoothLock.readLock().unlock();
Matthew Xiecdce0b92012-07-12 19:06:15 -07001675 }
1676 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001677
1678 private boolean checkIfCallerIsForegroundUser() {
1679 int foregroundUser;
1680 int callingUser = UserHandle.getCallingUserId();
Martijn Coenen8385c5a2012-11-29 10:14:16 -08001681 int callingUid = Binder.getCallingUid();
Zhihai Xu40874a02012-10-08 17:57:03 -07001682 long callingIdentity = Binder.clearCallingIdentity();
Benjamin Franze8b98922014-11-12 15:57:54 +00001683 UserManager um = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
1684 UserInfo ui = um.getProfileParent(callingUser);
1685 int parentUser = (ui != null) ? ui.id : UserHandle.USER_NULL;
Martijn Coenen8385c5a2012-11-29 10:14:16 -08001686 int callingAppId = UserHandle.getAppId(callingUid);
Zhihai Xu40874a02012-10-08 17:57:03 -07001687 boolean valid = false;
1688 try {
1689 foregroundUser = ActivityManager.getCurrentUser();
Martijn Coenen8385c5a2012-11-29 10:14:16 -08001690 valid = (callingUser == foregroundUser) ||
Benjamin Franze8b98922014-11-12 15:57:54 +00001691 parentUser == foregroundUser ||
Adrian Roosbd9a9a52014-08-18 15:31:57 +02001692 callingAppId == Process.NFC_UID ||
1693 callingAppId == mSystemUiUid;
Zhihai Xu40874a02012-10-08 17:57:03 -07001694 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001695 Slog.d(TAG, "checkIfCallerIsForegroundUser: valid=" + valid
Zhihai Xu40874a02012-10-08 17:57:03 -07001696 + " callingUser=" + callingUser
Benjamin Franze8b98922014-11-12 15:57:54 +00001697 + " parentUser=" + parentUser
Zhihai Xu40874a02012-10-08 17:57:03 -07001698 + " foregroundUser=" + foregroundUser);
1699 }
1700 } finally {
1701 Binder.restoreCallingIdentity(callingIdentity);
1702 }
1703 return valid;
1704 }
1705
Nitin Arorad055adb2015-03-02 15:03:51 -08001706 private void sendBleStateChanged(int prevState, int newState) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001707 if (DBG) Slog.d(TAG,"BLE State Change Intent: " + prevState + " -> " + newState);
Nitin Arorad055adb2015-03-02 15:03:51 -08001708 // Send broadcast message to everyone else
1709 Intent intent = new Intent(BluetoothAdapter.ACTION_BLE_STATE_CHANGED);
1710 intent.putExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE, prevState);
1711 intent.putExtra(BluetoothAdapter.EXTRA_STATE, newState);
1712 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1713 mContext.sendBroadcastAsUser(intent, UserHandle.ALL, BLUETOOTH_PERM);
1714 }
1715
Zhihai Xu40874a02012-10-08 17:57:03 -07001716 private void bluetoothStateChangeHandler(int prevState, int newState) {
Nitin Arorad055adb2015-03-02 15:03:51 -08001717 boolean isStandardBroadcast = true;
Zhihai Xu40874a02012-10-08 17:57:03 -07001718 if (prevState != newState) {
1719 //Notify all proxy objects first of adapter state change
Calvin Ona0b91d72016-06-15 17:58:23 -07001720 if (newState == BluetoothAdapter.STATE_BLE_ON ||
1721 newState == BluetoothAdapter.STATE_OFF) {
Nitin Arorad055adb2015-03-02 15:03:51 -08001722 boolean intermediate_off = (prevState == BluetoothAdapter.STATE_TURNING_OFF
1723 && newState == BluetoothAdapter.STATE_BLE_ON);
Zhihai Xu40874a02012-10-08 17:57:03 -07001724
Nitin Arorad055adb2015-03-02 15:03:51 -08001725 if (newState == BluetoothAdapter.STATE_OFF) {
1726 // If Bluetooth is off, send service down event to proxy objects, and unbind
Jeff Sharkey67609c72016-03-05 14:29:13 -07001727 if (DBG) Slog.d(TAG, "Bluetooth is complete turn off");
Pavlin Radoslavove47ec142016-06-01 22:25:18 -07001728 sendBluetoothServiceDownCallback();
1729 unbindAndFinish();
1730 sendBleStateChanged(prevState, newState);
1731 // Don't broadcast as it has already been broadcast before
1732 isStandardBroadcast = false;
Nitin Arorad055adb2015-03-02 15:03:51 -08001733
1734 } else if (!intermediate_off) {
1735 // connect to GattService
Jeff Sharkey67609c72016-03-05 14:29:13 -07001736 if (DBG) Slog.d(TAG, "Bluetooth is in LE only mode");
Nitin Arorad055adb2015-03-02 15:03:51 -08001737 if (mBluetoothGatt != null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001738 if (DBG) Slog.d(TAG, "Calling BluetoothGattServiceUp");
Nitin Arorad055adb2015-03-02 15:03:51 -08001739 onBluetoothGattServiceUp();
1740 } else {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001741 if (DBG) Slog.d(TAG, "Binding Bluetooth GATT service");
Nitin Arorad055adb2015-03-02 15:03:51 -08001742 if (mContext.getPackageManager().hasSystemFeature(
1743 PackageManager.FEATURE_BLUETOOTH_LE)) {
1744 Intent i = new Intent(IBluetoothGatt.class.getName());
1745 doBind(i, mConnection, Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT, UserHandle.CURRENT);
1746 }
1747 }
1748 sendBleStateChanged(prevState, newState);
1749 //Don't broadcase this as std intent
1750 isStandardBroadcast = false;
1751
1752 } else if (intermediate_off){
Jeff Sharkey67609c72016-03-05 14:29:13 -07001753 if (DBG) Slog.d(TAG, "Intermediate off, back to LE only mode");
Nitin Arorad055adb2015-03-02 15:03:51 -08001754 // For LE only mode, broadcast as is
1755 sendBleStateChanged(prevState, newState);
1756 sendBluetoothStateCallback(false); // BT is OFF for general users
1757 // Broadcast as STATE_OFF
1758 newState = BluetoothAdapter.STATE_OFF;
1759 sendBrEdrDownCallback();
Zhihai Xu40874a02012-10-08 17:57:03 -07001760 }
Nitin Arorad055adb2015-03-02 15:03:51 -08001761 } else if (newState == BluetoothAdapter.STATE_ON) {
1762 boolean isUp = (newState==BluetoothAdapter.STATE_ON);
1763 sendBluetoothStateCallback(isUp);
1764 sendBleStateChanged(prevState, newState);
1765
Calvin Ona0b91d72016-06-15 17:58:23 -07001766 } else if (newState == BluetoothAdapter.STATE_BLE_TURNING_ON ||
1767 newState == BluetoothAdapter.STATE_BLE_TURNING_OFF ) {
Nitin Arorad055adb2015-03-02 15:03:51 -08001768 sendBleStateChanged(prevState, newState);
1769 isStandardBroadcast = false;
1770
Calvin Ona0b91d72016-06-15 17:58:23 -07001771 } else if (newState == BluetoothAdapter.STATE_TURNING_ON ||
1772 newState == BluetoothAdapter.STATE_TURNING_OFF) {
Nitin Arorad055adb2015-03-02 15:03:51 -08001773 sendBleStateChanged(prevState, newState);
Zhihai Xu40874a02012-10-08 17:57:03 -07001774 }
1775
Nitin Arorad055adb2015-03-02 15:03:51 -08001776 if (isStandardBroadcast) {
1777 if (prevState == BluetoothAdapter.STATE_BLE_ON) {
1778 // Show prevState of BLE_ON as OFF to standard users
1779 prevState = BluetoothAdapter.STATE_OFF;
1780 }
1781 Intent intent = new Intent(BluetoothAdapter.ACTION_STATE_CHANGED);
1782 intent.putExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE, prevState);
1783 intent.putExtra(BluetoothAdapter.EXTRA_STATE, newState);
1784 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1785 mContext.sendBroadcastAsUser(intent, UserHandle.ALL, BLUETOOTH_PERM);
1786 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001787 }
1788 }
1789
1790 /**
1791 * if on is true, wait for state become ON
1792 * if off is true, wait for state become OFF
1793 * if both on and off are false, wait for state not ON
1794 */
1795 private boolean waitForOnOff(boolean on, boolean off) {
1796 int i = 0;
1797 while (i < 10) {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001798 try {
1799 mBluetoothLock.readLock().lock();
1800 if (mBluetooth == null) break;
1801 if (on) {
1802 if (mBluetooth.getState() == BluetoothAdapter.STATE_ON) return true;
1803 } else if (off) {
1804 if (mBluetooth.getState() == BluetoothAdapter.STATE_OFF) return true;
1805 } else {
1806 if (mBluetooth.getState() != BluetoothAdapter.STATE_ON) return true;
Zhihai Xu40874a02012-10-08 17:57:03 -07001807 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001808 } catch (RemoteException e) {
1809 Slog.e(TAG, "getState()", e);
1810 break;
1811 } finally {
1812 mBluetoothLock.readLock().unlock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001813 }
1814 if (on || off) {
1815 SystemClock.sleep(300);
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07001816 } else {
Zhihai Xu40874a02012-10-08 17:57:03 -07001817 SystemClock.sleep(50);
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07001818 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001819 i++;
1820 }
Jeff Sharkey67609c72016-03-05 14:29:13 -07001821 Slog.e(TAG,"waitForOnOff time out");
Zhihai Xu40874a02012-10-08 17:57:03 -07001822 return false;
1823 }
Zhihai Xu681ae7f2012-11-12 15:14:18 -08001824
Zhihai Xu401202b2012-12-03 11:36:21 -08001825 private void sendDisableMsg() {
1826 mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_DISABLE));
1827 }
1828
1829 private void sendEnableMsg(boolean quietMode) {
1830 mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_ENABLE,
1831 quietMode ? 1 : 0, 0));
1832 }
1833
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001834 private void recoverBluetoothServiceFromError() {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001835 Slog.e(TAG,"recoverBluetoothServiceFromError");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001836 try {
1837 mBluetoothLock.readLock().lock();
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001838 if (mBluetooth != null) {
1839 //Unregister callback object
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001840 mBluetooth.unregisterCallback(mBluetoothCallback);
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001841 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001842 } catch (RemoteException re) {
1843 Slog.e(TAG, "Unable to unregister", re);
1844 } finally {
1845 mBluetoothLock.readLock().unlock();
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001846 }
1847
1848 SystemClock.sleep(500);
1849
1850 // disable
1851 handleDisable();
1852
1853 waitForOnOff(false, true);
1854
1855 sendBluetoothServiceDownCallback();
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001856
Pavlin Radoslavove957a8a2016-05-24 15:28:41 -07001857 try {
1858 mBluetoothLock.writeLock().lock();
1859 if (mBluetooth != null) {
1860 mBluetooth = null;
1861 // Unbind
1862 mContext.unbindService(mConnection);
1863 }
1864 mBluetoothGatt = null;
1865 } finally {
1866 mBluetoothLock.writeLock().unlock();
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001867 }
1868
1869 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
1870 mState = BluetoothAdapter.STATE_OFF;
1871
1872 mEnable = false;
1873
1874 if (mErrorRecoveryRetryCounter++ < MAX_ERROR_RESTART_RETRIES) {
1875 // Send a Bluetooth Restart message to reenable bluetooth
1876 Message restartMsg = mHandler.obtainMessage(
1877 MESSAGE_RESTART_BLUETOOTH_SERVICE);
1878 mHandler.sendMessageDelayed(restartMsg, ERROR_RESTART_TIME_MS);
1879 } else {
1880 // todo: notify user to power down and power up phone to make bluetooth work.
1881 }
1882 }
Mike Lockwood726d4de2014-10-28 14:06:28 -07001883
1884 @Override
Pavlin Radoslavov6e8faff2016-02-23 11:54:37 -08001885 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1886 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DUMP, TAG);
1887 String errorMsg = null;
1888 if (mBluetoothBinder == null) {
1889 errorMsg = "Bluetooth Service not connected";
1890 } else {
1891 try {
1892 mBluetoothBinder.dump(fd, args);
1893 } catch (RemoteException re) {
1894 errorMsg = "RemoteException while calling Bluetooth Service";
1895 }
Mike Lockwood726d4de2014-10-28 14:06:28 -07001896 }
Pavlin Radoslavov6e8faff2016-02-23 11:54:37 -08001897 if (errorMsg != null) {
1898 // Silently return if we are extracting metrics in Protobuf format
1899 if ((args.length > 0) && args[0].startsWith("--proto"))
1900 return;
1901 writer.println(errorMsg);
1902 }
Mike Lockwood726d4de2014-10-28 14:06:28 -07001903 }
fredc0f420372012-04-12 00:02:00 -07001904}