blob: a3af5c6430128b99ea2deb05966739a2a9b03cea [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 Ganovb1e2da72016-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 Ganovb1e2da72016-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 Ganovb1e2da72016-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 }
Marie Janssen9fa24912016-10-18 10:04:24 -0700210 Slog.d(TAG, "Airplane Mode change - current 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();
Marie Janssena80d7452016-10-25 10:47:51 -0700224 mEnable = false;
Nitin Arorad055adb2015-03-02 15:03:51 -0800225 mEnableExternal = false;
226 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700227 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700228 Slog.e(TAG,"Unable to call onBrEdrDown", e);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700229 } finally {
Pavlin Radoslavov7ee53be2016-06-09 12:58:07 -0700230 mBluetoothLock.readLock().unlock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800231 }
232 } else if (st == BluetoothAdapter.STATE_ON){
233 // disable without persisting the setting
Jeff Sharkey67609c72016-03-05 14:29:13 -0700234 Slog.d(TAG, "Calling disable");
Nitin Arorad055adb2015-03-02 15:03:51 -0800235 sendDisableMsg();
236 }
Zhihai Xu401202b2012-12-03 11:36:21 -0800237 } else if (mEnableExternal) {
238 // enable without persisting the setting
Jeff Sharkey67609c72016-03-05 14:29:13 -0700239 Slog.d(TAG, "Calling enable");
Zhihai Xu401202b2012-12-03 11:36:21 -0800240 sendEnableMsg(mQuietEnableExternal);
241 }
fredc649fe492012-04-19 01:07:18 -0700242 }
fredc0f420372012-04-12 00:02:00 -0700243 }
244 }
245 };
246
247 BluetoothManagerService(Context context) {
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700248 mHandler = new BluetoothHandler(IoThread.get().getLooper());
Zhihai Xu40874a02012-10-08 17:57:03 -0700249
fredc0f420372012-04-12 00:02:00 -0700250 mContext = context;
Svetoslav Ganovb1e2da72016-06-29 17:31:44 -0700251
252 mPermissionReviewRequired = Build.PERMISSIONS_REVIEW_REQUIRED
253 || context.getResources().getBoolean(
254 com.android.internal.R.bool.config_permissionReviewRequired);
255
fredc0f420372012-04-12 00:02:00 -0700256 mBluetooth = null;
Marie Janssen9db28eb2016-01-12 16:05:15 -0800257 mBluetoothBinder = null;
Nitin Arorad055adb2015-03-02 15:03:51 -0800258 mBluetoothGatt = null;
fredc0f420372012-04-12 00:02:00 -0700259 mBinding = false;
260 mUnbinding = false;
Zhihai Xu40874a02012-10-08 17:57:03 -0700261 mEnable = false;
262 mState = BluetoothAdapter.STATE_OFF;
Zhihai Xu401202b2012-12-03 11:36:21 -0800263 mQuietEnableExternal = false;
264 mEnableExternal = false;
fredc0f420372012-04-12 00:02:00 -0700265 mAddress = null;
266 mName = null;
Zhihai Xudd9d17d2013-01-08 17:05:58 -0800267 mErrorRecoveryRetryCounter = 0;
fredc0f420372012-04-12 00:02:00 -0700268 mContentResolver = context.getContentResolver();
Wei Wange4a744b2015-06-11 17:50:29 -0700269 // Observe BLE scan only mode settings change.
270 registerForBleScanModeChange();
fredcd6883532012-04-25 17:46:13 -0700271 mCallbacks = new RemoteCallbackList<IBluetoothManagerCallback>();
272 mStateChangeCallbacks = new RemoteCallbackList<IBluetoothStateChangeCallback>();
Miao Chou658bf2f2015-06-26 17:14:35 -0700273 IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_LOCAL_NAME_CHANGED);
Matthew Xie6fde3092012-07-11 17:10:07 -0700274 registerForAirplaneMode(filter);
Dianne Hackbornd83a0962014-05-02 16:28:33 -0700275 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
Matthew Xie6fde3092012-07-11 17:10:07 -0700276 mContext.registerReceiver(mReceiver, filter);
fredc0f420372012-04-12 00:02:00 -0700277 loadStoredNameAndAddress();
Zhihai Xu401202b2012-12-03 11:36:21 -0800278 if (isBluetoothPersistedStateOn()) {
Marie Janssen9fa24912016-10-18 10:04:24 -0700279 if (DBG) Slog.d(TAG, "Startup: Bluetooth persisted state is ON.");
Zhihai Xu401202b2012-12-03 11:36:21 -0800280 mEnableExternal = true;
fredc0f420372012-04-12 00:02:00 -0700281 }
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200282
283 int sysUiUid = -1;
284 try {
Jeff Sharkeye06b4d12016-01-06 14:51:50 -0700285 sysUiUid = mContext.getPackageManager().getPackageUidAsUser("com.android.systemui",
Jeff Sharkeyc5967e92016-01-07 18:50:29 -0700286 PackageManager.MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM);
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200287 } catch (PackageManager.NameNotFoundException e) {
Joe LaPennaacddf2b2015-09-04 12:52:42 -0700288 // Some platforms, such as wearables do not have a system ui.
Jeff Sharkey67609c72016-03-05 14:29:13 -0700289 Slog.w(TAG, "Unable to resolve SystemUI's UID.", e);
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200290 }
291 mSystemUiUid = sysUiUid;
fredc0f420372012-04-12 00:02:00 -0700292 }
293
fredc649fe492012-04-19 01:07:18 -0700294 /**
295 * Returns true if airplane mode is currently on
296 */
297 private final boolean isAirplaneModeOn() {
Christopher Tatec09cdce2012-09-10 16:50:14 -0700298 return Settings.Global.getInt(mContext.getContentResolver(),
299 Settings.Global.AIRPLANE_MODE_ON, 0) == 1;
fredc649fe492012-04-19 01:07:18 -0700300 }
301
302 /**
303 * Returns true if the Bluetooth saved state is "on"
304 */
305 private final boolean isBluetoothPersistedStateOn() {
Marie Janssen9fa24912016-10-18 10:04:24 -0700306 int state = Settings.Global.getInt(mContentResolver,
307 Settings.Global.BLUETOOTH_ON, -1);
308 if (DBG) Slog.d(TAG, "Bluetooth persisted state: " + state);
309 return state != BLUETOOTH_OFF;
Zhihai Xu401202b2012-12-03 11:36:21 -0800310 }
311
312 /**
313 * Returns true if the Bluetooth saved state is BLUETOOTH_ON_BLUETOOTH
314 */
315 private final boolean isBluetoothPersistedStateOnBluetooth() {
316 return Settings.Global.getInt(mContentResolver,
Andre Eisenbach8c184312016-09-06 18:03:10 -0700317 Settings.Global.BLUETOOTH_ON, BLUETOOTH_ON_BLUETOOTH) == BLUETOOTH_ON_BLUETOOTH;
fredc649fe492012-04-19 01:07:18 -0700318 }
319
320 /**
321 * Save the Bluetooth on/off state
322 *
323 */
Zhihai Xu401202b2012-12-03 11:36:21 -0800324 private void persistBluetoothSetting(int value) {
Marie Janssen9fa24912016-10-18 10:04:24 -0700325 if (DBG) Slog.d(TAG, "Persisting Bluetooth Setting: " + value);
Jeff Brownbf6f6f92012-09-25 15:03:20 -0700326 Settings.Global.putInt(mContext.getContentResolver(),
327 Settings.Global.BLUETOOTH_ON,
Zhihai Xu401202b2012-12-03 11:36:21 -0800328 value);
fredc649fe492012-04-19 01:07:18 -0700329 }
330
331 /**
332 * Returns true if the Bluetooth Adapter's name and address is
333 * locally cached
334 * @return
335 */
fredc0f420372012-04-12 00:02:00 -0700336 private boolean isNameAndAddressSet() {
337 return mName !=null && mAddress!= null && mName.length()>0 && mAddress.length()>0;
338 }
339
fredc649fe492012-04-19 01:07:18 -0700340 /**
341 * Retrieve the Bluetooth Adapter's name and address and save it in
342 * in the local cache
343 */
fredc0f420372012-04-12 00:02:00 -0700344 private void loadStoredNameAndAddress() {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700345 if (DBG) Slog.d(TAG, "Loading stored name and address");
Zhihai Xud31c3222012-10-31 16:08:57 -0700346 if (mContext.getResources().getBoolean
347 (com.android.internal.R.bool.config_bluetooth_address_validation) &&
348 Settings.Secure.getInt(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDR_VALID, 0) == 0) {
349 // if the valid flag is not set, don't load the address and name
Jeff Sharkey67609c72016-03-05 14:29:13 -0700350 if (DBG) Slog.d(TAG, "invalid bluetooth name and address stored");
Zhihai Xud31c3222012-10-31 16:08:57 -0700351 return;
352 }
fredc0f420372012-04-12 00:02:00 -0700353 mName = Settings.Secure.getString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_NAME);
354 mAddress = Settings.Secure.getString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDRESS);
Jeff Sharkey67609c72016-03-05 14:29:13 -0700355 if (DBG) Slog.d(TAG, "Stored bluetooth Name=" + mName + ",Address=" + mAddress);
fredc0f420372012-04-12 00:02:00 -0700356 }
357
fredc649fe492012-04-19 01:07:18 -0700358 /**
359 * Save the Bluetooth name and address in the persistent store.
360 * Only non-null values will be saved.
361 * @param name
362 * @param address
363 */
fredc0f420372012-04-12 00:02:00 -0700364 private void storeNameAndAddress(String name, String address) {
365 if (name != null) {
366 Settings.Secure.putString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_NAME, name);
fredc0f420372012-04-12 00:02:00 -0700367 mName = name;
Jeff Sharkey67609c72016-03-05 14:29:13 -0700368 if (DBG) Slog.d(TAG,"Stored Bluetooth name: " +
fredc649fe492012-04-19 01:07:18 -0700369 Settings.Secure.getString(mContentResolver,SECURE_SETTINGS_BLUETOOTH_NAME));
fredc0f420372012-04-12 00:02:00 -0700370 }
371
372 if (address != null) {
373 Settings.Secure.putString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDRESS, address);
fredc0f420372012-04-12 00:02:00 -0700374 mAddress=address;
Jeff Sharkey67609c72016-03-05 14:29:13 -0700375 if (DBG) Slog.d(TAG,"Stored Bluetoothaddress: " +
fredc649fe492012-04-19 01:07:18 -0700376 Settings.Secure.getString(mContentResolver,SECURE_SETTINGS_BLUETOOTH_ADDRESS));
fredc0f420372012-04-12 00:02:00 -0700377 }
Zhihai Xud31c3222012-10-31 16:08:57 -0700378
379 if ((name != null) && (address != null)) {
380 Settings.Secure.putInt(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDR_VALID, 1);
381 }
fredc0f420372012-04-12 00:02:00 -0700382 }
383
384 public IBluetooth registerAdapter(IBluetoothManagerCallback callback){
Natalie Silvanovich55db6462014-05-01 16:12:23 -0700385 if (callback == null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700386 Slog.w(TAG, "Callback is null in registerAdapter");
Natalie Silvanovich55db6462014-05-01 16:12:23 -0700387 return null;
388 }
fredc0f420372012-04-12 00:02:00 -0700389 Message msg = mHandler.obtainMessage(MESSAGE_REGISTER_ADAPTER);
390 msg.obj = callback;
391 mHandler.sendMessage(msg);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700392
393 return mBluetooth;
fredc0f420372012-04-12 00:02:00 -0700394 }
395
396 public void unregisterAdapter(IBluetoothManagerCallback callback) {
Natalie Silvanovich55db6462014-05-01 16:12:23 -0700397 if (callback == null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700398 Slog.w(TAG, "Callback is null in unregisterAdapter");
Natalie Silvanovich55db6462014-05-01 16:12:23 -0700399 return;
400 }
fredc0f420372012-04-12 00:02:00 -0700401 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
402 "Need BLUETOOTH permission");
403 Message msg = mHandler.obtainMessage(MESSAGE_UNREGISTER_ADAPTER);
404 msg.obj = callback;
405 mHandler.sendMessage(msg);
406 }
407
408 public void registerStateChangeCallback(IBluetoothStateChangeCallback callback) {
409 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
410 "Need BLUETOOTH permission");
411 Message msg = mHandler.obtainMessage(MESSAGE_REGISTER_STATE_CHANGE_CALLBACK);
412 msg.obj = callback;
413 mHandler.sendMessage(msg);
414 }
415
416 public void unregisterStateChangeCallback(IBluetoothStateChangeCallback callback) {
417 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
418 "Need BLUETOOTH permission");
419 Message msg = mHandler.obtainMessage(MESSAGE_UNREGISTER_STATE_CHANGE_CALLBACK);
420 msg.obj = callback;
421 mHandler.sendMessage(msg);
422 }
423
424 public boolean isEnabled() {
Zhihai Xu6eb76522012-11-29 15:41:04 -0800425 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
426 (!checkIfCallerIsForegroundUser())) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700427 Slog.w(TAG,"isEnabled(): not allowed for non-active and non system user");
Zhihai Xu40874a02012-10-08 17:57:03 -0700428 return false;
429 }
430
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700431 try {
432 mBluetoothLock.readLock().lock();
433 if (mBluetooth != null) return mBluetooth.isEnabled();
434 } catch (RemoteException e) {
435 Slog.e(TAG, "isEnabled()", e);
436 } finally {
437 mBluetoothLock.readLock().unlock();
fredc0f420372012-04-12 00:02:00 -0700438 }
439 return false;
440 }
441
Christine Hallstrom995c90a2016-05-25 15:49:08 -0700442 public int getState() {
443 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
444 (!checkIfCallerIsForegroundUser())) {
445 Slog.w(TAG, "getState(): not allowed for non-active and non system user");
446 return BluetoothAdapter.STATE_OFF;
447 }
448
449 try {
450 mBluetoothLock.readLock().lock();
451 if (mBluetooth != null) return mBluetooth.getState();
452 } catch (RemoteException e) {
453 Slog.e(TAG, "getState()", e);
454 } finally {
455 mBluetoothLock.readLock().unlock();
456 }
457 return BluetoothAdapter.STATE_OFF;
458 }
459
Nitin Arorad055adb2015-03-02 15:03:51 -0800460 class ClientDeathRecipient implements IBinder.DeathRecipient {
461 public void binderDied() {
Marie Janssena80d7452016-10-25 10:47:51 -0700462 if (DBG) Slog.d(TAG, "Binder is dead - unregister Ble App");
Nitin Arorad055adb2015-03-02 15:03:51 -0800463 if (mBleAppCount > 0) --mBleAppCount;
464
465 if (mBleAppCount == 0) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700466 if (DBG) Slog.d(TAG, "Disabling LE only mode after application crash");
Nitin Arorad055adb2015-03-02 15:03:51 -0800467 try {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700468 mBluetoothLock.readLock().lock();
Marie Janssena80d7452016-10-25 10:47:51 -0700469 if (mBluetooth != null &&
470 mBluetooth.getState() == BluetoothAdapter.STATE_BLE_ON) {
471 mEnable = false;
Nitin Arorad055adb2015-03-02 15:03:51 -0800472 mBluetooth.onBrEdrDown();
473 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700474 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700475 Slog.e(TAG,"Unable to call onBrEdrDown", e);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700476 } finally {
477 mBluetoothLock.readLock().unlock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800478 }
479 }
480 }
481 }
482
483 /** Internal death rec list */
484 Map<IBinder, ClientDeathRecipient> mBleApps = new HashMap<IBinder, ClientDeathRecipient>();
485
Wei Wang67d84162015-04-26 17:04:29 -0700486 @Override
487 public boolean isBleScanAlwaysAvailable() {
Marie Janssena80d7452016-10-25 10:47:51 -0700488 if (isAirplaneModeOn() && !mEnable) {
489 return false;
490 }
Wei Wang67d84162015-04-26 17:04:29 -0700491 try {
492 return (Settings.Global.getInt(mContentResolver,
493 Settings.Global.BLE_SCAN_ALWAYS_AVAILABLE)) != 0;
494 } catch (SettingNotFoundException e) {
495 }
496 return false;
497 }
498
Wei Wange4a744b2015-06-11 17:50:29 -0700499 // Monitor change of BLE scan only mode settings.
500 private void registerForBleScanModeChange() {
501 ContentObserver contentObserver = new ContentObserver(null) {
502 @Override
503 public void onChange(boolean selfChange) {
504 if (!isBleScanAlwaysAvailable()) {
505 disableBleScanMode();
506 clearBleApps();
507 try {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700508 mBluetoothLock.readLock().lock();
Wei Wange4a744b2015-06-11 17:50:29 -0700509 if (mBluetooth != null) mBluetooth.onBrEdrDown();
510 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700511 Slog.e(TAG, "error when disabling bluetooth", e);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700512 } finally {
513 mBluetoothLock.readLock().unlock();
Wei Wange4a744b2015-06-11 17:50:29 -0700514 }
515 }
516 }
517 };
518
519 mContentResolver.registerContentObserver(
520 Settings.Global.getUriFor(Settings.Global.BLE_SCAN_ALWAYS_AVAILABLE),
521 false, contentObserver);
522 }
523
524 // Disable ble scan only mode.
525 private void disableBleScanMode() {
526 try {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700527 mBluetoothLock.writeLock().lock();
Wei Wange4a744b2015-06-11 17:50:29 -0700528 if (mBluetooth != null && (mBluetooth.getState() != BluetoothAdapter.STATE_ON)) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700529 if (DBG) Slog.d(TAG, "Reseting the mEnable flag for clean disable");
Wei Wange4a744b2015-06-11 17:50:29 -0700530 mEnable = false;
531 }
532 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700533 Slog.e(TAG, "getState()", e);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700534 } finally {
535 mBluetoothLock.writeLock().unlock();
Wei Wange4a744b2015-06-11 17:50:29 -0700536 }
537 }
538
Nitin Arorad055adb2015-03-02 15:03:51 -0800539 public int updateBleAppCount(IBinder token, boolean enable) {
540 if (enable) {
541 ClientDeathRecipient r = mBleApps.get(token);
542 if (r == null) {
543 ClientDeathRecipient deathRec = new ClientDeathRecipient();
544 try {
545 token.linkToDeath(deathRec, 0);
546 } catch (RemoteException ex) {
547 throw new IllegalArgumentException("Wake lock is already dead.");
548 }
549 mBleApps.put(token, deathRec);
550 synchronized (this) {
551 ++mBleAppCount;
552 }
Jeff Sharkey67609c72016-03-05 14:29:13 -0700553 if (DBG) Slog.d(TAG, "Registered for death Notification");
Nitin Arorad055adb2015-03-02 15:03:51 -0800554 }
555
556 } else {
557 ClientDeathRecipient r = mBleApps.get(token);
558 if (r != null) {
Wei Wange4a744b2015-06-11 17:50:29 -0700559 // Unregister death recipient as the app goes away.
560 token.unlinkToDeath(r, 0);
Nitin Arorad055adb2015-03-02 15:03:51 -0800561 mBleApps.remove(token);
562 synchronized (this) {
563 if (mBleAppCount > 0) --mBleAppCount;
564 }
Jeff Sharkey67609c72016-03-05 14:29:13 -0700565 if (DBG) Slog.d(TAG, "Unregistered for death Notification");
Nitin Arorad055adb2015-03-02 15:03:51 -0800566 }
567 }
Jeff Sharkey67609c72016-03-05 14:29:13 -0700568 if (DBG) Slog.d(TAG, "Updated BleAppCount" + mBleAppCount);
Nitin Arorad055adb2015-03-02 15:03:51 -0800569 if (mBleAppCount == 0 && mEnable) {
Wei Wange4a744b2015-06-11 17:50:29 -0700570 disableBleScanMode();
Nitin Arorad055adb2015-03-02 15:03:51 -0800571 }
572 return mBleAppCount;
573 }
574
Wei Wange4a744b2015-06-11 17:50:29 -0700575 // Clear all apps using BLE scan only mode.
576 private void clearBleApps() {
577 synchronized (this) {
578 mBleApps.clear();
579 mBleAppCount = 0;
580 }
581 }
582
Nitin Arorad055adb2015-03-02 15:03:51 -0800583 /** @hide*/
584 public boolean isBleAppPresent() {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700585 if (DBG) Slog.d(TAG, "isBleAppPresent() count: " + mBleAppCount);
Nitin Arorad055adb2015-03-02 15:03:51 -0800586 return (mBleAppCount > 0);
587 }
588
589 /**
590 * Action taken when GattService is turned off
591 */
592 private void onBluetoothGattServiceUp() {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700593 if (DBG) Slog.d(TAG,"BluetoothGatt Service is Up");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700594 try {
595 mBluetoothLock.readLock().lock();
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700596 if (isBleAppPresent() == false && mBluetooth != null
597 && mBluetooth.getState() == BluetoothAdapter.STATE_BLE_ON) {
Nitin Arorad055adb2015-03-02 15:03:51 -0800598 mBluetooth.onLeServiceUp();
599
600 // waive WRITE_SECURE_SETTINGS permission check
601 long callingIdentity = Binder.clearCallingIdentity();
602 persistBluetoothSetting(BLUETOOTH_ON_BLUETOOTH);
603 Binder.restoreCallingIdentity(callingIdentity);
604 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700605 } catch (RemoteException e) {
606 Slog.e(TAG,"Unable to call onServiceUp", e);
607 } finally {
608 mBluetoothLock.readLock().unlock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800609 }
610 }
611
612 /**
613 * Inform BluetoothAdapter instances that BREDR part is down
614 * and turn off all service and stack if no LE app needs it
615 */
616 private void sendBrEdrDownCallback() {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700617 if (DBG) Slog.d(TAG,"Calling sendBrEdrDownCallback callbacks");
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700618
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700619 if (mBluetooth == null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700620 Slog.w(TAG, "Bluetooth handle is null");
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700621 return;
622 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800623
624 if (isBleAppPresent() == false) {
625 try {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700626 mBluetoothLock.readLock().lock();
627 if (mBluetooth != null) mBluetooth.onBrEdrDown();
628 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700629 Slog.e(TAG, "Call to onBrEdrDown() failed.", e);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700630 } finally {
631 mBluetoothLock.readLock().unlock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800632 }
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700633 } else {
634 // Need to stay at BLE ON. Disconnect all Gatt connections
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700635 try {
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700636 mBluetoothGatt.unregAll();
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700637 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700638 Slog.e(TAG, "Unable to disconnect all apps.", e);
Nitin Arorad055adb2015-03-02 15:03:51 -0800639 }
640 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800641 }
642
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700643 public boolean enableNoAutoConnect()
644 {
645 mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
646 "Need BLUETOOTH ADMIN permission");
Zhihai Xu40874a02012-10-08 17:57:03 -0700647
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700648 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700649 Slog.d(TAG,"enableNoAutoConnect(): mBluetooth =" + mBluetooth +
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700650 " mBinding = " + mBinding);
651 }
Martijn Coenen8385c5a2012-11-29 10:14:16 -0800652 int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
653
654 if (callingAppId != Process.NFC_UID) {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700655 throw new SecurityException("no permission to enable Bluetooth quietly");
656 }
Martijn Coenen8385c5a2012-11-29 10:14:16 -0800657
Zhihai Xu401202b2012-12-03 11:36:21 -0800658 synchronized(mReceiver) {
659 mQuietEnableExternal = true;
660 mEnableExternal = true;
661 sendEnableMsg(true);
662 }
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700663 return true;
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700664 }
Ajay Panicker4bb48302016-03-31 14:14:27 -0700665
Svetoslav Ganovb1e2da72016-06-29 17:31:44 -0700666 public boolean enable(String packageName) throws RemoteException {
667 final int callingUid = Binder.getCallingUid();
668 final boolean callerSystem = UserHandle.getAppId(callingUid) == Process.SYSTEM_UID;
669
670 if (!callerSystem) {
671 if (!checkIfCallerIsForegroundUser()) {
672 Slog.w(TAG, "enable(): not allowed for non-active and non system user");
673 return false;
674 }
675
676 mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
677 "Need BLUETOOTH ADMIN permission");
678
679 if (!isEnabled() && mPermissionReviewRequired
680 && startConsentUiIfNeeded(packageName, callingUid,
681 BluetoothAdapter.ACTION_REQUEST_ENABLE)) {
682 return false;
683 }
fredcf2458862012-04-16 15:18:27 -0700684 }
685
Zhihai Xu401202b2012-12-03 11:36:21 -0800686 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700687 Slog.d(TAG,"enable(): mBluetooth =" + mBluetooth +
Sanket Agarwal090bf552016-04-21 14:10:55 -0700688 " mBinding = " + mBinding + " mState = " + mState);
689 }
Zhihai Xu401202b2012-12-03 11:36:21 -0800690
691 synchronized(mReceiver) {
692 mQuietEnableExternal = false;
693 mEnableExternal = true;
694 // waive WRITE_SECURE_SETTINGS permission check
Zhihai Xu401202b2012-12-03 11:36:21 -0800695 sendEnableMsg(false);
696 }
Jeff Sharkey67609c72016-03-05 14:29:13 -0700697 if (DBG) Slog.d(TAG, "enable returning");
Zhihai Xu401202b2012-12-03 11:36:21 -0800698 return true;
fredc0f420372012-04-12 00:02:00 -0700699 }
700
Svetoslav Ganovb1e2da72016-06-29 17:31:44 -0700701 public boolean disable(String packageName, boolean persist) throws RemoteException {
702 final int callingUid = Binder.getCallingUid();
703 final boolean callerSystem = UserHandle.getAppId(callingUid) == Process.SYSTEM_UID;
Zhihai Xu40874a02012-10-08 17:57:03 -0700704
Svetoslav Ganovb1e2da72016-06-29 17:31:44 -0700705 if (!callerSystem) {
706 if (!checkIfCallerIsForegroundUser()) {
707 Slog.w(TAG, "disable(): not allowed for non-active and non system user");
708 return false;
709 }
710
711 mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
712 "Need BLUETOOTH ADMIN permission");
713
714 if (isEnabled() && mPermissionReviewRequired
715 && startConsentUiIfNeeded(packageName, callingUid,
716 BluetoothAdapter.ACTION_REQUEST_DISABLE)) {
717 return false;
718 }
Zhihai Xu40874a02012-10-08 17:57:03 -0700719 }
720
fredcf2458862012-04-16 15:18:27 -0700721 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700722 Slog.d(TAG,"disable(): mBluetooth = " + mBluetooth +
Matthew Xiecdce0b92012-07-12 19:06:15 -0700723 " mBinding = " + mBinding);
724 }
fredcf2458862012-04-16 15:18:27 -0700725
Zhihai Xu401202b2012-12-03 11:36:21 -0800726 synchronized(mReceiver) {
727 if (persist) {
728 // waive WRITE_SECURE_SETTINGS permission check
729 long callingIdentity = Binder.clearCallingIdentity();
730 persistBluetoothSetting(BLUETOOTH_OFF);
731 Binder.restoreCallingIdentity(callingIdentity);
732 }
733 mEnableExternal = false;
734 sendDisableMsg();
735 }
fredc0f420372012-04-12 00:02:00 -0700736 return true;
737 }
738
Svetoslav Ganovb1e2da72016-06-29 17:31:44 -0700739 private boolean startConsentUiIfNeeded(String packageName,
740 int callingUid, String intentAction) throws RemoteException {
741 try {
742 // Validate the package only if we are going to use it
743 ApplicationInfo applicationInfo = mContext.getPackageManager()
744 .getApplicationInfoAsUser(packageName,
745 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
746 UserHandle.getUserId(callingUid));
747 if (applicationInfo.uid != callingUid) {
748 throw new SecurityException("Package " + callingUid
749 + " not in uid " + callingUid);
750 }
751
752 // Legacy apps in permission review mode trigger a user prompt
753 if (applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
754 Intent intent = new Intent(intentAction);
755 mContext.startActivity(intent);
756 return true;
757 }
758 } catch (PackageManager.NameNotFoundException e) {
759 throw new RemoteException(e.getMessage());
760 }
761 return false;
762 }
763
fredc649fe492012-04-19 01:07:18 -0700764 public void unbindAndFinish() {
fredcf2458862012-04-16 15:18:27 -0700765 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700766 Slog.d(TAG,"unbindAndFinish(): " + mBluetooth +
Matthew Xiecdce0b92012-07-12 19:06:15 -0700767 " mBinding = " + mBinding);
fredcf2458862012-04-16 15:18:27 -0700768 }
769
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700770 try {
771 mBluetoothLock.writeLock().lock();
fredc0f420372012-04-12 00:02:00 -0700772 if (mUnbinding) return;
773 mUnbinding = true;
Pavlin Radoslavove47ec142016-06-01 22:25:18 -0700774 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
Pavlin Radoslavovc7dda102016-09-21 17:28:11 -0700775 mHandler.removeMessages(MESSAGE_BIND_PROFILE_SERVICE);
Zhihai Xu40874a02012-10-08 17:57:03 -0700776 if (mBluetooth != null) {
Andre Eisenbach305fdab2015-11-11 21:43:26 -0800777 //Unregister callback object
778 try {
779 mBluetooth.unregisterCallback(mBluetoothCallback);
780 } catch (RemoteException re) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700781 Slog.e(TAG, "Unable to unregister BluetoothCallback",re);
fredcbf072a72012-05-09 16:52:50 -0700782 }
Andre Eisenbach305fdab2015-11-11 21:43:26 -0800783
Jeff Sharkey67609c72016-03-05 14:29:13 -0700784 if (DBG) Slog.d(TAG, "Sending unbind request.");
Marie Janssen9db28eb2016-01-12 16:05:15 -0800785 mBluetoothBinder = null;
fredcd6883532012-04-25 17:46:13 -0700786 mBluetooth = null;
787 //Unbind
fredc0f420372012-04-12 00:02:00 -0700788 mContext.unbindService(mConnection);
fredcd6883532012-04-25 17:46:13 -0700789 mUnbinding = false;
Zhihai Xu40874a02012-10-08 17:57:03 -0700790 mBinding = false;
fredcf2458862012-04-16 15:18:27 -0700791 } else {
792 mUnbinding=false;
fredc0f420372012-04-12 00:02:00 -0700793 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800794 mBluetoothGatt = null;
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700795 } finally {
796 mBluetoothLock.writeLock().unlock();
fredc0f420372012-04-12 00:02:00 -0700797 }
798 }
799
Matthew Xieddf7e472013-03-01 18:41:02 -0800800 public IBluetoothGatt getBluetoothGatt() {
801 // sync protection
802 return mBluetoothGatt;
803 }
804
Benjamin Franze8b98922014-11-12 15:57:54 +0000805 @Override
806 public boolean bindBluetoothProfileService(int bluetoothProfile,
807 IBluetoothProfileServiceConnection proxy) {
808 if (!mEnable) {
809 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700810 Slog.d(TAG, "Trying to bind to profile: " + bluetoothProfile +
Benjamin Franze8b98922014-11-12 15:57:54 +0000811 ", while Bluetooth was disabled");
812 }
813 return false;
814 }
815 synchronized (mProfileServices) {
816 ProfileServiceConnections psc = mProfileServices.get(new Integer(bluetoothProfile));
817 if (psc == null) {
818 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700819 Slog.d(TAG, "Creating new ProfileServiceConnections object for"
Benjamin Franze8b98922014-11-12 15:57:54 +0000820 + " profile: " + bluetoothProfile);
821 }
Benjamin Franz5b614592014-12-09 18:58:45 +0000822
823 if (bluetoothProfile != BluetoothProfile.HEADSET) return false;
824
825 Intent intent = new Intent(IBluetoothHeadset.class.getName());
Benjamin Franze8b98922014-11-12 15:57:54 +0000826 psc = new ProfileServiceConnections(intent);
Benjamin Franz5b614592014-12-09 18:58:45 +0000827 if (!psc.bindService()) return false;
828
Benjamin Franze8b98922014-11-12 15:57:54 +0000829 mProfileServices.put(new Integer(bluetoothProfile), psc);
Benjamin Franze8b98922014-11-12 15:57:54 +0000830 }
831 }
832
833 // Introducing a delay to give the client app time to prepare
834 Message addProxyMsg = mHandler.obtainMessage(MESSAGE_ADD_PROXY_DELAYED);
835 addProxyMsg.arg1 = bluetoothProfile;
836 addProxyMsg.obj = proxy;
837 mHandler.sendMessageDelayed(addProxyMsg, ADD_PROXY_DELAY_MS);
838 return true;
839 }
840
841 @Override
842 public void unbindBluetoothProfileService(int bluetoothProfile,
843 IBluetoothProfileServiceConnection proxy) {
844 synchronized (mProfileServices) {
845 ProfileServiceConnections psc = mProfileServices.get(new Integer(bluetoothProfile));
846 if (psc == null) {
847 return;
848 }
849 psc.removeProxy(proxy);
850 }
851 }
852
853 private void unbindAllBluetoothProfileServices() {
854 synchronized (mProfileServices) {
855 for (Integer i : mProfileServices.keySet()) {
856 ProfileServiceConnections psc = mProfileServices.get(i);
Benjamin Franz5b614592014-12-09 18:58:45 +0000857 try {
858 mContext.unbindService(psc);
859 } catch (IllegalArgumentException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700860 Slog.e(TAG, "Unable to unbind service with intent: " + psc.mIntent, e);
Benjamin Franz5b614592014-12-09 18:58:45 +0000861 }
Benjamin Franze8b98922014-11-12 15:57:54 +0000862 psc.removeAllProxies();
863 }
864 mProfileServices.clear();
865 }
866 }
867
868 /**
Miao Chou658bf2f2015-06-26 17:14:35 -0700869 * Send enable message and set adapter name and address. Called when the boot phase becomes
870 * PHASE_SYSTEM_SERVICES_READY.
871 */
872 public void handleOnBootPhase() {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700873 if (DBG) Slog.d(TAG, "Bluetooth boot completed");
Miao Chou658bf2f2015-06-26 17:14:35 -0700874 if (mEnableExternal && isBluetoothPersistedStateOnBluetooth()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700875 if (DBG) Slog.d(TAG, "Auto-enabling Bluetooth.");
Miao Chou658bf2f2015-06-26 17:14:35 -0700876 sendEnableMsg(mQuietEnableExternal);
Ajay Panickerbf796d82016-03-11 13:47:20 -0800877 } else if (!isNameAndAddressSet()) {
878 if (DBG) Slog.d(TAG, "Getting adapter name and address");
Ajay Panicker4bb48302016-03-31 14:14:27 -0700879 Message getMsg = mHandler.obtainMessage(MESSAGE_GET_NAME_AND_ADDRESS);
880 mHandler.sendMessage(getMsg);
Miao Chou658bf2f2015-06-26 17:14:35 -0700881 }
Miao Chou658bf2f2015-06-26 17:14:35 -0700882 }
883
884 /**
885 * Called when switching to a different foreground user.
886 */
887 public void handleOnSwitchUser(int userHandle) {
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -0700888 if (DBG) Slog.d(TAG, "User " + userHandle + " switched");
889 mHandler.obtainMessage(MESSAGE_USER_SWITCHED, userHandle, 0).sendToTarget();
890 }
891
892 /**
893 * Called when user is unlocked.
894 */
895 public void handleOnUnlockUser(int userHandle) {
896 if (DBG) Slog.d(TAG, "User " + userHandle + " unlocked");
897 mHandler.obtainMessage(MESSAGE_USER_UNLOCKED, userHandle, 0).sendToTarget();
Miao Chou658bf2f2015-06-26 17:14:35 -0700898 }
899
900 /**
Benjamin Franze8b98922014-11-12 15:57:54 +0000901 * This class manages the clients connected to a given ProfileService
902 * and maintains the connection with that service.
903 */
904 final private class ProfileServiceConnections implements ServiceConnection,
905 IBinder.DeathRecipient {
906 final RemoteCallbackList<IBluetoothProfileServiceConnection> mProxies =
907 new RemoteCallbackList <IBluetoothProfileServiceConnection>();
908 IBinder mService;
909 ComponentName mClassName;
910 Intent mIntent;
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700911 boolean mInvokingProxyCallbacks = false;
Benjamin Franze8b98922014-11-12 15:57:54 +0000912
913 ProfileServiceConnections(Intent intent) {
914 mService = null;
915 mClassName = null;
916 mIntent = intent;
917 }
918
Benjamin Franz5b614592014-12-09 18:58:45 +0000919 private boolean bindService() {
920 if (mIntent != null && mService == null &&
921 doBind(mIntent, this, 0, UserHandle.CURRENT_OR_SELF)) {
Benjamin Franze8b98922014-11-12 15:57:54 +0000922 Message msg = mHandler.obtainMessage(MESSAGE_BIND_PROFILE_SERVICE);
923 msg.obj = this;
924 mHandler.sendMessageDelayed(msg, TIMEOUT_BIND_MS);
Benjamin Franz5b614592014-12-09 18:58:45 +0000925 return true;
Benjamin Franze8b98922014-11-12 15:57:54 +0000926 }
Jeff Sharkey67609c72016-03-05 14:29:13 -0700927 Slog.w(TAG, "Unable to bind with intent: " + mIntent);
Benjamin Franz5b614592014-12-09 18:58:45 +0000928 return false;
Benjamin Franze8b98922014-11-12 15:57:54 +0000929 }
930
931 private void addProxy(IBluetoothProfileServiceConnection proxy) {
932 mProxies.register(proxy);
933 if (mService != null) {
934 try{
935 proxy.onServiceConnected(mClassName, mService);
936 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700937 Slog.e(TAG, "Unable to connect to proxy", e);
Benjamin Franze8b98922014-11-12 15:57:54 +0000938 }
939 } else {
940 if (!mHandler.hasMessages(MESSAGE_BIND_PROFILE_SERVICE, this)) {
941 Message msg = mHandler.obtainMessage(MESSAGE_BIND_PROFILE_SERVICE);
942 msg.obj = this;
943 mHandler.sendMessage(msg);
944 }
945 }
946 }
947
948 private void removeProxy(IBluetoothProfileServiceConnection proxy) {
949 if (proxy != null) {
950 if (mProxies.unregister(proxy)) {
951 try {
952 proxy.onServiceDisconnected(mClassName);
953 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700954 Slog.e(TAG, "Unable to disconnect proxy", e);
Benjamin Franze8b98922014-11-12 15:57:54 +0000955 }
956 }
957 } else {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700958 Slog.w(TAG, "Trying to remove a null proxy");
Benjamin Franze8b98922014-11-12 15:57:54 +0000959 }
960 }
961
962 private void removeAllProxies() {
963 onServiceDisconnected(mClassName);
964 mProxies.kill();
965 }
966
967 @Override
968 public void onServiceConnected(ComponentName className, IBinder service) {
969 // remove timeout message
970 mHandler.removeMessages(MESSAGE_BIND_PROFILE_SERVICE, this);
971 mService = service;
972 mClassName = className;
973 try {
974 mService.linkToDeath(this, 0);
975 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700976 Slog.e(TAG, "Unable to linkToDeath", e);
Benjamin Franze8b98922014-11-12 15:57:54 +0000977 }
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).onServiceConnected(className, service);
990 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700991 Slog.e(TAG, "Unable to connect to 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 onServiceDisconnected(ComponentName className) {
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001002 if (mService == null) return;
Benjamin Franze8b98922014-11-12 15:57:54 +00001003 mService.unlinkToDeath(this, 0);
1004 mService = null;
1005 mClassName = null;
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001006
1007 if (mInvokingProxyCallbacks) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001008 Slog.e(TAG, "Proxy callbacks already in progress.");
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001009 return;
Benjamin Franze8b98922014-11-12 15:57:54 +00001010 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001011 mInvokingProxyCallbacks = true;
1012
1013 final int n = mProxies.beginBroadcast();
1014 try {
1015 for (int i = 0; i < n; i++) {
1016 try {
1017 mProxies.getBroadcastItem(i).onServiceDisconnected(className);
1018 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001019 Slog.e(TAG, "Unable to disconnect from proxy", e);
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001020 }
1021 }
1022 } finally {
1023 mProxies.finishBroadcast();
1024 mInvokingProxyCallbacks = false;
1025 }
Benjamin Franze8b98922014-11-12 15:57:54 +00001026 }
1027
1028 @Override
1029 public void binderDied() {
1030 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001031 Slog.w(TAG, "Profile service for profile: " + mClassName
Benjamin Franze8b98922014-11-12 15:57:54 +00001032 + " died.");
1033 }
1034 onServiceDisconnected(mClassName);
1035 // Trigger rebind
1036 Message msg = mHandler.obtainMessage(MESSAGE_BIND_PROFILE_SERVICE);
1037 msg.obj = this;
1038 mHandler.sendMessageDelayed(msg, TIMEOUT_BIND_MS);
1039 }
1040 }
1041
fredcbf072a72012-05-09 16:52:50 -07001042 private void sendBluetoothStateCallback(boolean isUp) {
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001043 try {
1044 int n = mStateChangeCallbacks.beginBroadcast();
Jeff Sharkey67609c72016-03-05 14:29:13 -07001045 if (DBG) Slog.d(TAG,"Broadcasting onBluetoothStateChange("+isUp+") to " + n + " receivers.");
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001046 for (int i=0; i <n;i++) {
1047 try {
1048 mStateChangeCallbacks.getBroadcastItem(i).onBluetoothStateChange(isUp);
1049 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001050 Slog.e(TAG, "Unable to call onBluetoothStateChange() on callback #" + i , e);
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001051 }
fredcbf072a72012-05-09 16:52:50 -07001052 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001053 } finally {
1054 mStateChangeCallbacks.finishBroadcast();
fredcbf072a72012-05-09 16:52:50 -07001055 }
fredcbf072a72012-05-09 16:52:50 -07001056 }
1057
1058 /**
Zhihai Xu40874a02012-10-08 17:57:03 -07001059 * Inform BluetoothAdapter instances that Adapter service is up
1060 */
1061 private void sendBluetoothServiceUpCallback() {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001062 if (DBG) Slog.d(TAG,"Calling onBluetoothServiceUp callbacks");
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001063 try {
1064 int n = mCallbacks.beginBroadcast();
Jeff Sharkey67609c72016-03-05 14:29:13 -07001065 Slog.d(TAG,"Broadcasting onBluetoothServiceUp() to " + n + " receivers.");
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001066 for (int i=0; i <n;i++) {
1067 try {
1068 mCallbacks.getBroadcastItem(i).onBluetoothServiceUp(mBluetooth);
1069 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001070 Slog.e(TAG, "Unable to call onBluetoothServiceUp() on callback #" + i, e);
Zhihai Xu40874a02012-10-08 17:57:03 -07001071 }
1072 }
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001073 } finally {
1074 mCallbacks.finishBroadcast();
Zhihai Xu40874a02012-10-08 17:57:03 -07001075 }
1076 }
1077 /**
fredcbf072a72012-05-09 16:52:50 -07001078 * Inform BluetoothAdapter instances that Adapter service is down
1079 */
1080 private void sendBluetoothServiceDownCallback() {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001081 if (DBG) Slog.d(TAG,"Calling onBluetoothServiceDown callbacks");
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001082 try {
1083 int n = mCallbacks.beginBroadcast();
Jeff Sharkey67609c72016-03-05 14:29:13 -07001084 Slog.d(TAG,"Broadcasting onBluetoothServiceDown() to " + n + " receivers.");
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001085 for (int i=0; i <n;i++) {
1086 try {
1087 mCallbacks.getBroadcastItem(i).onBluetoothServiceDown();
1088 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001089 Slog.e(TAG, "Unable to call onBluetoothServiceDown() on callback #" + i, e);
fredcd6883532012-04-25 17:46:13 -07001090 }
1091 }
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001092 } finally {
1093 mCallbacks.finishBroadcast();
fredcd6883532012-04-25 17:46:13 -07001094 }
1095 }
Svet Ganov408abf72015-05-12 19:13:36 -07001096
fredc0f420372012-04-12 00:02:00 -07001097 public String getAddress() {
Matthew Xieaf5ddbf2012-12-04 10:47:43 -08001098 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
Svet Ganov408abf72015-05-12 19:13:36 -07001099 "Need BLUETOOTH permission");
Zhihai Xu40874a02012-10-08 17:57:03 -07001100
Zhihai Xu6eb76522012-11-29 15:41:04 -08001101 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
Svet Ganov408abf72015-05-12 19:13:36 -07001102 (!checkIfCallerIsForegroundUser())) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001103 Slog.w(TAG,"getAddress(): not allowed for non-active and non system user");
Zhihai Xu6eb76522012-11-29 15:41:04 -08001104 return null;
Zhihai Xu40874a02012-10-08 17:57:03 -07001105 }
1106
Svet Ganov408abf72015-05-12 19:13:36 -07001107 if (mContext.checkCallingOrSelfPermission(Manifest.permission.LOCAL_MAC_ADDRESS)
1108 != PackageManager.PERMISSION_GRANTED) {
1109 return BluetoothAdapter.DEFAULT_MAC_ADDRESS;
1110 }
1111
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001112 try {
1113 mBluetoothLock.readLock().lock();
1114 if (mBluetooth != null) return mBluetooth.getAddress();
1115 } catch (RemoteException e) {
1116 Slog.e(TAG, "getAddress(): Unable to retrieve address remotely. Returning cached address", e);
1117 } finally {
1118 mBluetoothLock.readLock().unlock();
fredc116d1d462012-04-20 14:47:08 -07001119 }
Ajay Panickerbf796d82016-03-11 13:47:20 -08001120
Matthew Xiecdce0b92012-07-12 19:06:15 -07001121 // mAddress is accessed from outside.
1122 // It is alright without a lock. Here, bluetooth is off, no other thread is
1123 // changing mAddress
fredc0f420372012-04-12 00:02:00 -07001124 return mAddress;
1125 }
fredc649fe492012-04-19 01:07:18 -07001126
fredc0f420372012-04-12 00:02:00 -07001127 public String getName() {
Matthew Xieaf5ddbf2012-12-04 10:47:43 -08001128 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
1129 "Need BLUETOOTH permission");
Zhihai Xu40874a02012-10-08 17:57:03 -07001130
Zhihai Xu6eb76522012-11-29 15:41:04 -08001131 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
1132 (!checkIfCallerIsForegroundUser())) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001133 Slog.w(TAG,"getName(): not allowed for non-active and non system user");
Zhihai Xu6eb76522012-11-29 15:41:04 -08001134 return null;
Zhihai Xu40874a02012-10-08 17:57:03 -07001135 }
1136
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001137 try {
1138 mBluetoothLock.readLock().lock();
1139 if (mBluetooth != null) return mBluetooth.getName();
1140 } catch (RemoteException e) {
1141 Slog.e(TAG, "getName(): Unable to retrieve name remotely. Returning cached name", e);
1142 } finally {
1143 mBluetoothLock.readLock().unlock();
fredc116d1d462012-04-20 14:47:08 -07001144 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001145
Matthew Xiecdce0b92012-07-12 19:06:15 -07001146 // mName is accessed from outside.
1147 // It alright without a lock. Here, bluetooth is off, no other thread is
1148 // changing mName
fredc0f420372012-04-12 00:02:00 -07001149 return mName;
1150 }
1151
fredc0f420372012-04-12 00:02:00 -07001152 private class BluetoothServiceConnection implements ServiceConnection {
fredc0f420372012-04-12 00:02:00 -07001153 public void onServiceConnected(ComponentName className, IBinder service) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001154 if (DBG) Slog.d(TAG, "BluetoothServiceConnection: " + className.getClassName());
fredc0f420372012-04-12 00:02:00 -07001155 Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_SERVICE_CONNECTED);
Matthew Xieddf7e472013-03-01 18:41:02 -08001156 // TBD if (className.getClassName().equals(IBluetooth.class.getName())) {
1157 if (className.getClassName().equals("com.android.bluetooth.btservice.AdapterService")) {
1158 msg.arg1 = SERVICE_IBLUETOOTH;
1159 // } else if (className.getClassName().equals(IBluetoothGatt.class.getName())) {
1160 } else if (className.getClassName().equals("com.android.bluetooth.gatt.GattService")) {
1161 msg.arg1 = SERVICE_IBLUETOOTHGATT;
1162 } else {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001163 Slog.e(TAG, "Unknown service connected: " + className.getClassName());
Matthew Xieddf7e472013-03-01 18:41:02 -08001164 return;
1165 }
fredc0f420372012-04-12 00:02:00 -07001166 msg.obj = service;
1167 mHandler.sendMessage(msg);
1168 }
1169
1170 public void onServiceDisconnected(ComponentName className) {
fredc0f420372012-04-12 00:02:00 -07001171 // Called if we unexpected disconnected.
Jeff Sharkey67609c72016-03-05 14:29:13 -07001172 if (DBG) Slog.d(TAG, "BluetoothServiceConnection, disconnected: " +
Matthew Xieddf7e472013-03-01 18:41:02 -08001173 className.getClassName());
fredc0f420372012-04-12 00:02:00 -07001174 Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED);
Matthew Xieddf7e472013-03-01 18:41:02 -08001175 if (className.getClassName().equals("com.android.bluetooth.btservice.AdapterService")) {
1176 msg.arg1 = SERVICE_IBLUETOOTH;
1177 } else if (className.getClassName().equals("com.android.bluetooth.gatt.GattService")) {
1178 msg.arg1 = SERVICE_IBLUETOOTHGATT;
1179 } else {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001180 Slog.e(TAG, "Unknown service disconnected: " + className.getClassName());
Matthew Xieddf7e472013-03-01 18:41:02 -08001181 return;
1182 }
fredc0f420372012-04-12 00:02:00 -07001183 mHandler.sendMessage(msg);
1184 }
1185 }
1186
1187 private BluetoothServiceConnection mConnection = new BluetoothServiceConnection();
1188
Zhihai Xu40874a02012-10-08 17:57:03 -07001189 private class BluetoothHandler extends Handler {
Ajay Panicker4bb48302016-03-31 14:14:27 -07001190 boolean mGetNameAddressOnly = false;
1191
Zhihai Xu40874a02012-10-08 17:57:03 -07001192 public BluetoothHandler(Looper looper) {
1193 super(looper);
1194 }
1195
fredc0f420372012-04-12 00:02:00 -07001196 @Override
1197 public void handleMessage(Message msg) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001198 if (DBG) Slog.d (TAG, "Message: " + msg.what);
fredc0f420372012-04-12 00:02:00 -07001199 switch (msg.what) {
Ajay Panicker4bb48302016-03-31 14:14:27 -07001200 case MESSAGE_GET_NAME_AND_ADDRESS:
1201 if (DBG) Slog.d(TAG, "MESSAGE_GET_NAME_AND_ADDRESS");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001202 try {
1203 mBluetoothLock.writeLock().lock();
Ajay Panicker4bb48302016-03-31 14:14:27 -07001204 if ((mBluetooth == null) && (!mBinding)) {
1205 if (DBG) Slog.d(TAG, "Binding to service to get name and address");
1206 mGetNameAddressOnly = true;
1207 Message timeoutMsg = mHandler.obtainMessage(MESSAGE_TIMEOUT_BIND);
1208 mHandler.sendMessageDelayed(timeoutMsg, TIMEOUT_BIND_MS);
1209 Intent i = new Intent(IBluetooth.class.getName());
1210 if (!doBind(i, mConnection,
1211 Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT,
1212 UserHandle.CURRENT)) {
1213 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
1214 } else {
1215 mBinding = true;
1216 }
1217 } else if (mBluetooth != null) {
1218 try {
1219 storeNameAndAddress(mBluetooth.getName(),
1220 mBluetooth.getAddress());
1221 } catch (RemoteException re) {
1222 Slog.e(TAG, "Unable to grab names", re);
1223 }
1224 if (mGetNameAddressOnly && !mEnable) {
1225 unbindAndFinish();
1226 }
1227 mGetNameAddressOnly = false;
1228 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001229 } finally {
1230 mBluetoothLock.writeLock().unlock();
Ajay Panicker4bb48302016-03-31 14:14:27 -07001231 }
1232 break;
1233
Matthew Xiecdce0b92012-07-12 19:06:15 -07001234 case MESSAGE_ENABLE:
fredcf2458862012-04-16 15:18:27 -07001235 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001236 Slog.d(TAG, "MESSAGE_ENABLE: mBluetooth = " + mBluetooth);
fredc649fe492012-04-19 01:07:18 -07001237 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001238 mHandler.removeMessages(MESSAGE_RESTART_BLUETOOTH_SERVICE);
1239 mEnable = true;
Calvin Ona0b91d72016-06-15 17:58:23 -07001240
1241 // Use service interface to get the exact state
1242 try {
1243 mBluetoothLock.readLock().lock();
1244 if (mBluetooth != null) {
1245 int state = mBluetooth.getState();
1246 if (state == BluetoothAdapter.STATE_BLE_ON) {
1247 Slog.w(TAG, "BT is in BLE_ON State");
1248 mBluetooth.onLeServiceUp();
1249 break;
1250 }
1251 }
1252 } catch (RemoteException e) {
1253 Slog.e(TAG, "", e);
1254 } finally {
1255 mBluetoothLock.readLock().unlock();
1256 }
1257
1258 mQuietEnable = (msg.arg1 == 1);
Pavlin Radoslavove47ec142016-06-01 22:25:18 -07001259 if (mBluetooth == null) {
Calvin Ona0b91d72016-06-15 17:58:23 -07001260 handleEnable(mQuietEnable);
Pavlin Radoslavove47ec142016-06-01 22:25:18 -07001261 } else {
1262 //
1263 // We need to wait until transitioned to STATE_OFF and
1264 // the previous Bluetooth process has exited. The
1265 // waiting period has three components:
1266 // (a) Wait until the local state is STATE_OFF. This
1267 // is accomplished by "waitForOnOff(false, true)".
1268 // (b) Wait until the STATE_OFF state is updated to
1269 // all components.
1270 // (c) Wait until the Bluetooth process exits, and
1271 // ActivityManager detects it.
1272 // The waiting for (b) and (c) is accomplished by
1273 // delaying the MESSAGE_RESTART_BLUETOOTH_SERVICE
1274 // message. On slower devices, that delay needs to be
1275 // on the order of (2 * SERVICE_RESTART_TIME_MS).
1276 //
1277 waitForOnOff(false, true);
Pavlin Radoslavove47ec142016-06-01 22:25:18 -07001278 Message restartMsg = mHandler.obtainMessage(
1279 MESSAGE_RESTART_BLUETOOTH_SERVICE);
1280 mHandler.sendMessageDelayed(restartMsg,
1281 2 * SERVICE_RESTART_TIME_MS);
1282 }
fredc649fe492012-04-19 01:07:18 -07001283 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001284
fredc0f420372012-04-12 00:02:00 -07001285 case MESSAGE_DISABLE:
Zhihai Xu40874a02012-10-08 17:57:03 -07001286 mHandler.removeMessages(MESSAGE_RESTART_BLUETOOTH_SERVICE);
1287 if (mEnable && mBluetooth != null) {
1288 waitForOnOff(true, false);
1289 mEnable = false;
Zhihai Xu401202b2012-12-03 11:36:21 -08001290 handleDisable();
Zhihai Xu40874a02012-10-08 17:57:03 -07001291 waitForOnOff(false, false);
1292 } else {
1293 mEnable = false;
Zhihai Xu401202b2012-12-03 11:36:21 -08001294 handleDisable();
Zhihai Xu40874a02012-10-08 17:57:03 -07001295 }
fredc0f420372012-04-12 00:02:00 -07001296 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001297
fredc0f420372012-04-12 00:02:00 -07001298 case MESSAGE_REGISTER_ADAPTER:
1299 {
1300 IBluetoothManagerCallback callback = (IBluetoothManagerCallback) msg.obj;
fredcd6883532012-04-25 17:46:13 -07001301 boolean added = mCallbacks.register(callback);
Jeff Sharkey67609c72016-03-05 14:29:13 -07001302 Slog.d(TAG,"Added callback: " + (callback == null? "null": callback) +":" +added );
fredc0f420372012-04-12 00:02:00 -07001303 }
1304 break;
1305 case MESSAGE_UNREGISTER_ADAPTER:
1306 {
1307 IBluetoothManagerCallback callback = (IBluetoothManagerCallback) msg.obj;
fredcd6883532012-04-25 17:46:13 -07001308 boolean removed = mCallbacks.unregister(callback);
Jeff Sharkey67609c72016-03-05 14:29:13 -07001309 Slog.d(TAG,"Removed callback: " + (callback == null? "null": callback) +":" + removed);
fredc0f420372012-04-12 00:02:00 -07001310 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001311 }
fredc0f420372012-04-12 00:02:00 -07001312 case MESSAGE_REGISTER_STATE_CHANGE_CALLBACK:
1313 {
1314 IBluetoothStateChangeCallback callback = (IBluetoothStateChangeCallback) msg.obj;
Matthew Xie9b693992013-10-10 11:21:40 -07001315 if (callback != null) {
1316 mStateChangeCallbacks.register(callback);
1317 }
fredc0f420372012-04-12 00:02:00 -07001318 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001319 }
fredc0f420372012-04-12 00:02:00 -07001320 case MESSAGE_UNREGISTER_STATE_CHANGE_CALLBACK:
1321 {
1322 IBluetoothStateChangeCallback callback = (IBluetoothStateChangeCallback) msg.obj;
Matthew Xie9b693992013-10-10 11:21:40 -07001323 if (callback != null) {
1324 mStateChangeCallbacks.unregister(callback);
1325 }
fredc0f420372012-04-12 00:02:00 -07001326 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001327 }
Benjamin Franze8b98922014-11-12 15:57:54 +00001328 case MESSAGE_ADD_PROXY_DELAYED:
1329 {
1330 ProfileServiceConnections psc = mProfileServices.get(
1331 new Integer(msg.arg1));
1332 if (psc == null) {
1333 break;
1334 }
1335 IBluetoothProfileServiceConnection proxy =
1336 (IBluetoothProfileServiceConnection) msg.obj;
1337 psc.addProxy(proxy);
1338 break;
1339 }
1340 case MESSAGE_BIND_PROFILE_SERVICE:
1341 {
1342 ProfileServiceConnections psc = (ProfileServiceConnections) msg.obj;
1343 removeMessages(MESSAGE_BIND_PROFILE_SERVICE, msg.obj);
1344 if (psc == null) {
1345 break;
1346 }
1347 psc.bindService();
1348 break;
1349 }
fredc0f420372012-04-12 00:02:00 -07001350 case MESSAGE_BLUETOOTH_SERVICE_CONNECTED:
1351 {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001352 if (DBG) Slog.d(TAG,"MESSAGE_BLUETOOTH_SERVICE_CONNECTED: " + msg.arg1);
fredc0f420372012-04-12 00:02:00 -07001353
1354 IBinder service = (IBinder) msg.obj;
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001355 try {
1356 mBluetoothLock.writeLock().lock();
Matthew Xieddf7e472013-03-01 18:41:02 -08001357 if (msg.arg1 == SERVICE_IBLUETOOTHGATT) {
1358 mBluetoothGatt = IBluetoothGatt.Stub.asInterface(service);
Nitin Arorad055adb2015-03-02 15:03:51 -08001359 onBluetoothGattServiceUp();
Matthew Xieddf7e472013-03-01 18:41:02 -08001360 break;
1361 } // else must be SERVICE_IBLUETOOTH
1362
1363 //Remove timeout
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001364 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
Matthew Xieddf7e472013-03-01 18:41:02 -08001365
fredc0f420372012-04-12 00:02:00 -07001366 mBinding = false;
Marie Janssen9db28eb2016-01-12 16:05:15 -08001367 mBluetoothBinder = service;
fredc0f420372012-04-12 00:02:00 -07001368 mBluetooth = IBluetooth.Stub.asInterface(service);
fredc0f420372012-04-12 00:02:00 -07001369
Ajay Panicker4bb48302016-03-31 14:14:27 -07001370 if (!isNameAndAddressSet()) {
1371 Message getMsg = mHandler.obtainMessage(MESSAGE_GET_NAME_AND_ADDRESS);
1372 mHandler.sendMessage(getMsg);
1373 if (mGetNameAddressOnly) return;
1374 }
1375
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001376 try {
1377 boolean enableHciSnoopLog = (Settings.Secure.getInt(mContentResolver,
1378 Settings.Secure.BLUETOOTH_HCI_LOG, 0) == 1);
1379 if (!mBluetooth.configHciSnoopLog(enableHciSnoopLog)) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001380 Slog.e(TAG,"IBluetooth.configHciSnoopLog return false");
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001381 }
1382 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001383 Slog.e(TAG,"Unable to call configHciSnoopLog", e);
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001384 }
1385
Matthew Xiecdce0b92012-07-12 19:06:15 -07001386 //Register callback object
fredcbf072a72012-05-09 16:52:50 -07001387 try {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001388 mBluetooth.registerCallback(mBluetoothCallback);
1389 } catch (RemoteException re) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001390 Slog.e(TAG, "Unable to register BluetoothCallback",re);
fredcbf072a72012-05-09 16:52:50 -07001391 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001392 //Inform BluetoothAdapter instances that service is up
Zhihai Xu40874a02012-10-08 17:57:03 -07001393 sendBluetoothServiceUpCallback();
1394
Matthew Xiecdce0b92012-07-12 19:06:15 -07001395 //Do enable request
1396 try {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001397 if (mQuietEnable == false) {
1398 if(!mBluetooth.enable()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001399 Slog.e(TAG,"IBluetooth.enable() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001400 }
1401 }
1402 else
1403 {
1404 if(!mBluetooth.enableNoAutoConnect()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001405 Slog.e(TAG,"IBluetooth.enableNoAutoConnect() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001406 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001407 }
1408 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001409 Slog.e(TAG,"Unable to call enable()",e);
Matthew Xiecdce0b92012-07-12 19:06:15 -07001410 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001411 } finally {
1412 mBluetoothLock.writeLock().unlock();
Freda8c6df02012-07-11 10:25:23 -07001413 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001414
1415 if (!mEnable) {
1416 waitForOnOff(true, false);
Zhihai Xu401202b2012-12-03 11:36:21 -08001417 handleDisable();
Zhihai Xu40874a02012-10-08 17:57:03 -07001418 waitForOnOff(false, false);
1419 }
fredc649fe492012-04-19 01:07:18 -07001420 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001421 }
fredc649fe492012-04-19 01:07:18 -07001422 case MESSAGE_TIMEOUT_BIND: {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001423 Slog.e(TAG, "MESSAGE_TIMEOUT_BIND");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001424 mBluetoothLock.writeLock().lock();
1425 mBinding = false;
1426 mBluetoothLock.writeLock().unlock();
1427
fredc649fe492012-04-19 01:07:18 -07001428 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001429 }
fredcbf072a72012-05-09 16:52:50 -07001430 case MESSAGE_BLUETOOTH_STATE_CHANGE:
fredc0f420372012-04-12 00:02:00 -07001431 {
fredcbf072a72012-05-09 16:52:50 -07001432 int prevState = msg.arg1;
1433 int newState = msg.arg2;
Marie Janssen9fa24912016-10-18 10:04:24 -07001434 if (DBG) Slog.d(TAG, "MESSAGE_BLUETOOTH_STATE_CHANGE: prevState = " + prevState + ", newState =" + newState);
Zhihai Xu40874a02012-10-08 17:57:03 -07001435 mState = newState;
1436 bluetoothStateChangeHandler(prevState, newState);
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001437 // handle error state transition case from TURNING_ON to OFF
1438 // unbind and rebind bluetooth service and enable bluetooth
Nitin Arorad055adb2015-03-02 15:03:51 -08001439 if ((prevState == BluetoothAdapter.STATE_BLE_TURNING_ON) &&
Calvin Ona0b91d72016-06-15 17:58:23 -07001440 (newState == BluetoothAdapter.STATE_OFF) &&
1441 (mBluetooth != null) && mEnable) {
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001442 recoverBluetoothServiceFromError();
1443 }
Nitin Arorad055adb2015-03-02 15:03:51 -08001444 if ((prevState == BluetoothAdapter.STATE_TURNING_ON) &&
Calvin Ona0b91d72016-06-15 17:58:23 -07001445 (newState == BluetoothAdapter.STATE_BLE_ON) &&
1446 (mBluetooth != null) && mEnable) {
Nitin Arorad055adb2015-03-02 15:03:51 -08001447 recoverBluetoothServiceFromError();
1448 }
Calvin Ona0b91d72016-06-15 17:58:23 -07001449 // If we tried to enable BT while BT was in the process of shutting down,
1450 // wait for the BT process to fully tear down and then force a restart
1451 // here. This is a bit of a hack (b/29363429).
1452 if ((prevState == BluetoothAdapter.STATE_BLE_TURNING_OFF) &&
1453 (newState == BluetoothAdapter.STATE_OFF)) {
1454 if (mEnable) {
1455 Slog.d(TAG, "Entering STATE_OFF but mEnabled is true; restarting.");
1456 waitForOnOff(false, true);
1457 Message restartMsg = mHandler.obtainMessage(
1458 MESSAGE_RESTART_BLUETOOTH_SERVICE);
1459 mHandler.sendMessageDelayed(restartMsg, 2 * SERVICE_RESTART_TIME_MS);
1460 }
1461 }
Nitin Arorad055adb2015-03-02 15:03:51 -08001462 if (newState == BluetoothAdapter.STATE_ON ||
Calvin Ona0b91d72016-06-15 17:58:23 -07001463 newState == BluetoothAdapter.STATE_BLE_ON) {
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001464 // bluetooth is working, reset the counter
1465 if (mErrorRecoveryRetryCounter != 0) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001466 Slog.w(TAG, "bluetooth is recovered from error");
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001467 mErrorRecoveryRetryCounter = 0;
1468 }
1469 }
fredc649fe492012-04-19 01:07:18 -07001470 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001471 }
fredc0f420372012-04-12 00:02:00 -07001472 case MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED:
1473 {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001474 Slog.e(TAG, "MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED: " + msg.arg1);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001475 try {
1476 mBluetoothLock.writeLock().lock();
Matthew Xieddf7e472013-03-01 18:41:02 -08001477 if (msg.arg1 == SERVICE_IBLUETOOTH) {
1478 // if service is unbinded already, do nothing and return
1479 if (mBluetooth == null) break;
1480 mBluetooth = null;
1481 } else if (msg.arg1 == SERVICE_IBLUETOOTHGATT) {
1482 mBluetoothGatt = null;
1483 break;
1484 } else {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001485 Slog.e(TAG, "Bad msg.arg1: " + msg.arg1);
Matthew Xieddf7e472013-03-01 18:41:02 -08001486 break;
1487 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001488 } finally {
1489 mBluetoothLock.writeLock().unlock();
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301490 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001491
1492 if (mEnable) {
1493 mEnable = false;
1494 // Send a Bluetooth Restart message
1495 Message restartMsg = mHandler.obtainMessage(
1496 MESSAGE_RESTART_BLUETOOTH_SERVICE);
1497 mHandler.sendMessageDelayed(restartMsg,
1498 SERVICE_RESTART_TIME_MS);
1499 }
1500
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001501 sendBluetoothServiceDownCallback();
Zhihai Xu40874a02012-10-08 17:57:03 -07001502
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001503 // Send BT state broadcast to update
1504 // the BT icon correctly
1505 if ((mState == BluetoothAdapter.STATE_TURNING_ON) ||
Calvin Ona0b91d72016-06-15 17:58:23 -07001506 (mState == BluetoothAdapter.STATE_ON)) {
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001507 bluetoothStateChangeHandler(BluetoothAdapter.STATE_ON,
1508 BluetoothAdapter.STATE_TURNING_OFF);
1509 mState = BluetoothAdapter.STATE_TURNING_OFF;
Zhihai Xu40874a02012-10-08 17:57:03 -07001510 }
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001511 if (mState == BluetoothAdapter.STATE_TURNING_OFF) {
1512 bluetoothStateChangeHandler(BluetoothAdapter.STATE_TURNING_OFF,
1513 BluetoothAdapter.STATE_OFF);
1514 }
1515
1516 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
1517 mState = BluetoothAdapter.STATE_OFF;
fredc649fe492012-04-19 01:07:18 -07001518 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001519 }
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301520 case MESSAGE_RESTART_BLUETOOTH_SERVICE:
1521 {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001522 Slog.d(TAG, "MESSAGE_RESTART_BLUETOOTH_SERVICE:"
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301523 +" Restart IBluetooth service");
1524 /* Enable without persisting the setting as
1525 it doesnt change when IBluetooth
1526 service restarts */
Zhihai Xu40874a02012-10-08 17:57:03 -07001527 mEnable = true;
Zhihai Xu401202b2012-12-03 11:36:21 -08001528 handleEnable(mQuietEnable);
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301529 break;
1530 }
1531
fredc0f420372012-04-12 00:02:00 -07001532 case MESSAGE_TIMEOUT_UNBIND:
1533 {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001534 Slog.e(TAG, "MESSAGE_TIMEOUT_UNBIND");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001535 mBluetoothLock.writeLock().lock();
1536 mUnbinding = false;
1537 mBluetoothLock.writeLock().unlock();
fredc649fe492012-04-19 01:07:18 -07001538 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001539 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001540
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001541 case MESSAGE_USER_SWITCHED: {
1542 if (DBG) Slog.d(TAG, "MESSAGE_USER_SWITCHED");
Zhihai Xu40874a02012-10-08 17:57:03 -07001543 mHandler.removeMessages(MESSAGE_USER_SWITCHED);
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001544
Zhihai Xu40874a02012-10-08 17:57:03 -07001545 /* disable and enable BT when detect a user switch */
1546 if (mEnable && mBluetooth != null) {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001547 try {
1548 mBluetoothLock.readLock().lock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001549 if (mBluetooth != null) {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001550 mBluetooth.unregisterCallback(mBluetoothCallback);
Zhihai Xu40874a02012-10-08 17:57:03 -07001551 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001552 } catch (RemoteException re) {
1553 Slog.e(TAG, "Unable to unregister", re);
1554 } finally {
1555 mBluetoothLock.readLock().unlock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001556 }
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001557
1558 if (mState == BluetoothAdapter.STATE_TURNING_OFF) {
1559 // MESSAGE_USER_SWITCHED happened right after MESSAGE_ENABLE
1560 bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_OFF);
1561 mState = BluetoothAdapter.STATE_OFF;
1562 }
1563 if (mState == BluetoothAdapter.STATE_OFF) {
1564 bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_TURNING_ON);
1565 mState = BluetoothAdapter.STATE_TURNING_ON;
1566 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001567
1568 waitForOnOff(true, false);
1569
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001570 if (mState == BluetoothAdapter.STATE_TURNING_ON) {
1571 bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_ON);
1572 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001573
Benjamin Franze8b98922014-11-12 15:57:54 +00001574 unbindAllBluetoothProfileServices();
Zhihai Xu40874a02012-10-08 17:57:03 -07001575 // disable
Zhihai Xu401202b2012-12-03 11:36:21 -08001576 handleDisable();
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001577 // Pbap service need receive STATE_TURNING_OFF intent to close
1578 bluetoothStateChangeHandler(BluetoothAdapter.STATE_ON,
1579 BluetoothAdapter.STATE_TURNING_OFF);
Zhihai Xu40874a02012-10-08 17:57:03 -07001580
Pavlin Radoslavov41401112016-06-27 15:25:18 -07001581 boolean didDisableTimeout = !waitForOnOff(false, true);
Zhihai Xu40874a02012-10-08 17:57:03 -07001582
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001583 bluetoothStateChangeHandler(BluetoothAdapter.STATE_TURNING_OFF,
Zhihai Xu40874a02012-10-08 17:57:03 -07001584 BluetoothAdapter.STATE_OFF);
Zhihai Xu40874a02012-10-08 17:57:03 -07001585 sendBluetoothServiceDownCallback();
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001586
Pavlin Radoslavove957a8a2016-05-24 15:28:41 -07001587 try {
1588 mBluetoothLock.writeLock().lock();
1589 if (mBluetooth != null) {
1590 mBluetooth = null;
1591 // Unbind
1592 mContext.unbindService(mConnection);
1593 }
1594 mBluetoothGatt = null;
1595 } finally {
1596 mBluetoothLock.writeLock().unlock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001597 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001598
Pavlin Radoslavov41401112016-06-27 15:25:18 -07001599 //
1600 // If disabling Bluetooth times out, wait for an
1601 // additional amount of time to ensure the process is
1602 // shut down completely before attempting to restart.
1603 //
1604 if (didDisableTimeout) {
1605 SystemClock.sleep(3000);
1606 } else {
1607 SystemClock.sleep(100);
1608 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001609
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001610 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
1611 mState = BluetoothAdapter.STATE_OFF;
Zhihai Xu40874a02012-10-08 17:57:03 -07001612 // enable
Zhihai Xu401202b2012-12-03 11:36:21 -08001613 handleEnable(mQuietEnable);
John Spurlock8a985d22014-02-25 09:40:05 -05001614 } else if (mBinding || mBluetooth != null) {
Zhihai Xu40874a02012-10-08 17:57:03 -07001615 Message userMsg = mHandler.obtainMessage(MESSAGE_USER_SWITCHED);
1616 userMsg.arg2 = 1 + msg.arg2;
1617 // if user is switched when service is being binding
1618 // delay sending MESSAGE_USER_SWITCHED
1619 mHandler.sendMessageDelayed(userMsg, USER_SWITCHED_TIME_MS);
1620 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001621 Slog.d(TAG, "delay MESSAGE_USER_SWITCHED " + userMsg.arg2);
Zhihai Xu40874a02012-10-08 17:57:03 -07001622 }
John Spurlock8a985d22014-02-25 09:40:05 -05001623 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001624 break;
1625 }
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001626 case MESSAGE_USER_UNLOCKED: {
1627 if (DBG) Slog.d(TAG, "MESSAGE_USER_UNLOCKED");
1628 mHandler.removeMessages(MESSAGE_USER_SWITCHED);
1629
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001630 if (mEnable && !mBinding && (mBluetooth == null)) {
1631 // We should be connected, but we gave up for some
1632 // reason; maybe the Bluetooth service wasn't encryption
1633 // aware, so try binding again.
1634 if (DBG) Slog.d(TAG, "Enabled but not bound; retrying after unlock");
1635 handleEnable(mQuietEnable);
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001636 }
1637 }
fredc0f420372012-04-12 00:02:00 -07001638 }
1639 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001640 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001641
Zhihai Xu401202b2012-12-03 11:36:21 -08001642 private void handleEnable(boolean quietMode) {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001643 mQuietEnable = quietMode;
1644
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001645 try {
1646 mBluetoothLock.writeLock().lock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001647 if ((mBluetooth == null) && (!mBinding)) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001648 //Start bind timeout and bind
1649 Message timeoutMsg=mHandler.obtainMessage(MESSAGE_TIMEOUT_BIND);
1650 mHandler.sendMessageDelayed(timeoutMsg,TIMEOUT_BIND_MS);
Matthew Xiecdce0b92012-07-12 19:06:15 -07001651 Intent i = new Intent(IBluetooth.class.getName());
Dianne Hackbornce09f5a2014-10-10 15:03:13 -07001652 if (!doBind(i, mConnection,Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT,
1653 UserHandle.CURRENT)) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001654 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
Zhihai Xu40874a02012-10-08 17:57:03 -07001655 } else {
1656 mBinding = true;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001657 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001658 } else if (mBluetooth != null) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001659 //Enable bluetooth
1660 try {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001661 if (!mQuietEnable) {
1662 if(!mBluetooth.enable()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001663 Slog.e(TAG,"IBluetooth.enable() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001664 }
1665 }
1666 else {
1667 if(!mBluetooth.enableNoAutoConnect()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001668 Slog.e(TAG,"IBluetooth.enableNoAutoConnect() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001669 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001670 }
1671 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001672 Slog.e(TAG,"Unable to call enable()",e);
Matthew Xiecdce0b92012-07-12 19:06:15 -07001673 }
1674 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001675 } finally {
1676 mBluetoothLock.writeLock().unlock();
Matthew Xiecdce0b92012-07-12 19:06:15 -07001677 }
1678 }
1679
Dianne Hackborn221ea892013-08-04 16:50:16 -07001680 boolean doBind(Intent intent, ServiceConnection conn, int flags, UserHandle user) {
1681 ComponentName comp = intent.resolveSystemService(mContext.getPackageManager(), 0);
1682 intent.setComponent(comp);
1683 if (comp == null || !mContext.bindServiceAsUser(intent, conn, flags, user)) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001684 Slog.e(TAG, "Fail to bind to: " + intent);
Dianne Hackborn221ea892013-08-04 16:50:16 -07001685 return false;
1686 }
1687 return true;
1688 }
1689
Zhihai Xu401202b2012-12-03 11:36:21 -08001690 private void handleDisable() {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001691 try {
1692 mBluetoothLock.readLock().lock();
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001693 if (mBluetooth != null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001694 if (DBG) Slog.d(TAG,"Sending off request.");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001695 if (!mBluetooth.disable()) {
1696 Slog.e(TAG,"IBluetooth.disable() returned false");
Matthew Xiecdce0b92012-07-12 19:06:15 -07001697 }
1698 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001699 } catch (RemoteException e) {
1700 Slog.e(TAG,"Unable to call disable()",e);
1701 } finally {
1702 mBluetoothLock.readLock().unlock();
Matthew Xiecdce0b92012-07-12 19:06:15 -07001703 }
1704 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001705
1706 private boolean checkIfCallerIsForegroundUser() {
1707 int foregroundUser;
1708 int callingUser = UserHandle.getCallingUserId();
Martijn Coenen8385c5a2012-11-29 10:14:16 -08001709 int callingUid = Binder.getCallingUid();
Zhihai Xu40874a02012-10-08 17:57:03 -07001710 long callingIdentity = Binder.clearCallingIdentity();
Benjamin Franze8b98922014-11-12 15:57:54 +00001711 UserManager um = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
1712 UserInfo ui = um.getProfileParent(callingUser);
1713 int parentUser = (ui != null) ? ui.id : UserHandle.USER_NULL;
Martijn Coenen8385c5a2012-11-29 10:14:16 -08001714 int callingAppId = UserHandle.getAppId(callingUid);
Zhihai Xu40874a02012-10-08 17:57:03 -07001715 boolean valid = false;
1716 try {
1717 foregroundUser = ActivityManager.getCurrentUser();
Martijn Coenen8385c5a2012-11-29 10:14:16 -08001718 valid = (callingUser == foregroundUser) ||
Benjamin Franze8b98922014-11-12 15:57:54 +00001719 parentUser == foregroundUser ||
Adrian Roosbd9a9a52014-08-18 15:31:57 +02001720 callingAppId == Process.NFC_UID ||
1721 callingAppId == mSystemUiUid;
Zhihai Xu40874a02012-10-08 17:57:03 -07001722 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001723 Slog.d(TAG, "checkIfCallerIsForegroundUser: valid=" + valid
Zhihai Xu40874a02012-10-08 17:57:03 -07001724 + " callingUser=" + callingUser
Benjamin Franze8b98922014-11-12 15:57:54 +00001725 + " parentUser=" + parentUser
Zhihai Xu40874a02012-10-08 17:57:03 -07001726 + " foregroundUser=" + foregroundUser);
1727 }
1728 } finally {
1729 Binder.restoreCallingIdentity(callingIdentity);
1730 }
1731 return valid;
1732 }
1733
Nitin Arorad055adb2015-03-02 15:03:51 -08001734 private void sendBleStateChanged(int prevState, int newState) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001735 if (DBG) Slog.d(TAG,"BLE State Change Intent: " + prevState + " -> " + newState);
Nitin Arorad055adb2015-03-02 15:03:51 -08001736 // Send broadcast message to everyone else
1737 Intent intent = new Intent(BluetoothAdapter.ACTION_BLE_STATE_CHANGED);
1738 intent.putExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE, prevState);
1739 intent.putExtra(BluetoothAdapter.EXTRA_STATE, newState);
1740 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1741 mContext.sendBroadcastAsUser(intent, UserHandle.ALL, BLUETOOTH_PERM);
1742 }
1743
Zhihai Xu40874a02012-10-08 17:57:03 -07001744 private void bluetoothStateChangeHandler(int prevState, int newState) {
Nitin Arorad055adb2015-03-02 15:03:51 -08001745 boolean isStandardBroadcast = true;
Marie Janssen9fa24912016-10-18 10:04:24 -07001746 if (DBG) Slog.d(TAG, "bluetoothStateChangeHandler: " + prevState + " -> " + newState);
Zhihai Xu40874a02012-10-08 17:57:03 -07001747 if (prevState != newState) {
1748 //Notify all proxy objects first of adapter state change
Calvin Ona0b91d72016-06-15 17:58:23 -07001749 if (newState == BluetoothAdapter.STATE_BLE_ON ||
1750 newState == BluetoothAdapter.STATE_OFF) {
Nitin Arorad055adb2015-03-02 15:03:51 -08001751 boolean intermediate_off = (prevState == BluetoothAdapter.STATE_TURNING_OFF
1752 && newState == BluetoothAdapter.STATE_BLE_ON);
Zhihai Xu40874a02012-10-08 17:57:03 -07001753
Nitin Arorad055adb2015-03-02 15:03:51 -08001754 if (newState == BluetoothAdapter.STATE_OFF) {
1755 // If Bluetooth is off, send service down event to proxy objects, and unbind
Jeff Sharkey67609c72016-03-05 14:29:13 -07001756 if (DBG) Slog.d(TAG, "Bluetooth is complete turn off");
Pavlin Radoslavove47ec142016-06-01 22:25:18 -07001757 sendBluetoothServiceDownCallback();
1758 unbindAndFinish();
1759 sendBleStateChanged(prevState, newState);
1760 // Don't broadcast as it has already been broadcast before
1761 isStandardBroadcast = false;
Nitin Arorad055adb2015-03-02 15:03:51 -08001762
1763 } else if (!intermediate_off) {
1764 // connect to GattService
Jeff Sharkey67609c72016-03-05 14:29:13 -07001765 if (DBG) Slog.d(TAG, "Bluetooth is in LE only mode");
Nitin Arorad055adb2015-03-02 15:03:51 -08001766 if (mBluetoothGatt != null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001767 if (DBG) Slog.d(TAG, "Calling BluetoothGattServiceUp");
Nitin Arorad055adb2015-03-02 15:03:51 -08001768 onBluetoothGattServiceUp();
1769 } else {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001770 if (DBG) Slog.d(TAG, "Binding Bluetooth GATT service");
Nitin Arorad055adb2015-03-02 15:03:51 -08001771 if (mContext.getPackageManager().hasSystemFeature(
1772 PackageManager.FEATURE_BLUETOOTH_LE)) {
1773 Intent i = new Intent(IBluetoothGatt.class.getName());
1774 doBind(i, mConnection, Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT, UserHandle.CURRENT);
1775 }
1776 }
1777 sendBleStateChanged(prevState, newState);
1778 //Don't broadcase this as std intent
1779 isStandardBroadcast = false;
1780
1781 } else if (intermediate_off){
Jeff Sharkey67609c72016-03-05 14:29:13 -07001782 if (DBG) Slog.d(TAG, "Intermediate off, back to LE only mode");
Nitin Arorad055adb2015-03-02 15:03:51 -08001783 // For LE only mode, broadcast as is
1784 sendBleStateChanged(prevState, newState);
1785 sendBluetoothStateCallback(false); // BT is OFF for general users
1786 // Broadcast as STATE_OFF
1787 newState = BluetoothAdapter.STATE_OFF;
1788 sendBrEdrDownCallback();
Zhihai Xu40874a02012-10-08 17:57:03 -07001789 }
Nitin Arorad055adb2015-03-02 15:03:51 -08001790 } else if (newState == BluetoothAdapter.STATE_ON) {
1791 boolean isUp = (newState==BluetoothAdapter.STATE_ON);
1792 sendBluetoothStateCallback(isUp);
1793 sendBleStateChanged(prevState, newState);
1794
Calvin Ona0b91d72016-06-15 17:58:23 -07001795 } else if (newState == BluetoothAdapter.STATE_BLE_TURNING_ON ||
1796 newState == BluetoothAdapter.STATE_BLE_TURNING_OFF ) {
Nitin Arorad055adb2015-03-02 15:03:51 -08001797 sendBleStateChanged(prevState, newState);
1798 isStandardBroadcast = false;
1799
Calvin Ona0b91d72016-06-15 17:58:23 -07001800 } else if (newState == BluetoothAdapter.STATE_TURNING_ON ||
1801 newState == BluetoothAdapter.STATE_TURNING_OFF) {
Nitin Arorad055adb2015-03-02 15:03:51 -08001802 sendBleStateChanged(prevState, newState);
Zhihai Xu40874a02012-10-08 17:57:03 -07001803 }
1804
Nitin Arorad055adb2015-03-02 15:03:51 -08001805 if (isStandardBroadcast) {
1806 if (prevState == BluetoothAdapter.STATE_BLE_ON) {
1807 // Show prevState of BLE_ON as OFF to standard users
1808 prevState = BluetoothAdapter.STATE_OFF;
1809 }
1810 Intent intent = new Intent(BluetoothAdapter.ACTION_STATE_CHANGED);
1811 intent.putExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE, prevState);
1812 intent.putExtra(BluetoothAdapter.EXTRA_STATE, newState);
1813 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1814 mContext.sendBroadcastAsUser(intent, UserHandle.ALL, BLUETOOTH_PERM);
1815 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001816 }
1817 }
1818
1819 /**
1820 * if on is true, wait for state become ON
1821 * if off is true, wait for state become OFF
1822 * if both on and off are false, wait for state not ON
1823 */
1824 private boolean waitForOnOff(boolean on, boolean off) {
1825 int i = 0;
1826 while (i < 10) {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001827 try {
1828 mBluetoothLock.readLock().lock();
1829 if (mBluetooth == null) break;
1830 if (on) {
1831 if (mBluetooth.getState() == BluetoothAdapter.STATE_ON) return true;
1832 } else if (off) {
1833 if (mBluetooth.getState() == BluetoothAdapter.STATE_OFF) return true;
1834 } else {
1835 if (mBluetooth.getState() != BluetoothAdapter.STATE_ON) return true;
Zhihai Xu40874a02012-10-08 17:57:03 -07001836 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001837 } catch (RemoteException e) {
1838 Slog.e(TAG, "getState()", e);
1839 break;
1840 } finally {
1841 mBluetoothLock.readLock().unlock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001842 }
1843 if (on || off) {
1844 SystemClock.sleep(300);
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07001845 } else {
Zhihai Xu40874a02012-10-08 17:57:03 -07001846 SystemClock.sleep(50);
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07001847 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001848 i++;
1849 }
Jeff Sharkey67609c72016-03-05 14:29:13 -07001850 Slog.e(TAG,"waitForOnOff time out");
Zhihai Xu40874a02012-10-08 17:57:03 -07001851 return false;
1852 }
Zhihai Xu681ae7f2012-11-12 15:14:18 -08001853
Zhihai Xu401202b2012-12-03 11:36:21 -08001854 private void sendDisableMsg() {
1855 mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_DISABLE));
1856 }
1857
1858 private void sendEnableMsg(boolean quietMode) {
1859 mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_ENABLE,
1860 quietMode ? 1 : 0, 0));
1861 }
1862
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001863 private void recoverBluetoothServiceFromError() {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001864 Slog.e(TAG,"recoverBluetoothServiceFromError");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001865 try {
1866 mBluetoothLock.readLock().lock();
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001867 if (mBluetooth != null) {
1868 //Unregister callback object
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001869 mBluetooth.unregisterCallback(mBluetoothCallback);
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001870 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001871 } catch (RemoteException re) {
1872 Slog.e(TAG, "Unable to unregister", re);
1873 } finally {
1874 mBluetoothLock.readLock().unlock();
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001875 }
1876
1877 SystemClock.sleep(500);
1878
1879 // disable
1880 handleDisable();
1881
1882 waitForOnOff(false, true);
1883
1884 sendBluetoothServiceDownCallback();
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001885
Pavlin Radoslavove957a8a2016-05-24 15:28:41 -07001886 try {
1887 mBluetoothLock.writeLock().lock();
1888 if (mBluetooth != null) {
1889 mBluetooth = null;
1890 // Unbind
1891 mContext.unbindService(mConnection);
1892 }
1893 mBluetoothGatt = null;
1894 } finally {
1895 mBluetoothLock.writeLock().unlock();
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001896 }
1897
1898 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
1899 mState = BluetoothAdapter.STATE_OFF;
1900
1901 mEnable = false;
1902
1903 if (mErrorRecoveryRetryCounter++ < MAX_ERROR_RESTART_RETRIES) {
1904 // Send a Bluetooth Restart message to reenable bluetooth
1905 Message restartMsg = mHandler.obtainMessage(
1906 MESSAGE_RESTART_BLUETOOTH_SERVICE);
1907 mHandler.sendMessageDelayed(restartMsg, ERROR_RESTART_TIME_MS);
1908 } else {
1909 // todo: notify user to power down and power up phone to make bluetooth work.
1910 }
1911 }
Mike Lockwood726d4de2014-10-28 14:06:28 -07001912
1913 @Override
Pavlin Radoslavov6e8faff2016-02-23 11:54:37 -08001914 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1915 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DUMP, TAG);
1916 String errorMsg = null;
1917 if (mBluetoothBinder == null) {
1918 errorMsg = "Bluetooth Service not connected";
1919 } else {
1920 try {
1921 mBluetoothBinder.dump(fd, args);
1922 } catch (RemoteException re) {
1923 errorMsg = "RemoteException while calling Bluetooth Service";
1924 }
Mike Lockwood726d4de2014-10-28 14:06:28 -07001925 }
Pavlin Radoslavov6e8faff2016-02-23 11:54:37 -08001926 if (errorMsg != null) {
1927 // Silently return if we are extracting metrics in Protobuf format
1928 if ((args.length > 0) && args[0].startsWith("--proto"))
1929 return;
1930 writer.println(errorMsg);
1931 }
Mike Lockwood726d4de2014-10-28 14:06:28 -07001932 }
fredc0f420372012-04-12 00:02:00 -07001933}