blob: bfbd8cb38d854f8dd775e7e7f0a97622a0e964ac [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
Ivan Podogovd2d32b12016-12-05 16:46:52 +0000679 if (!isEnabled() && mPermissionReviewRequired) {
680 startConsentUi(packageName, callingUid, BluetoothAdapter.ACTION_REQUEST_ENABLE);
Svetoslav Ganovb1e2da72016-06-29 17:31:44 -0700681 return false;
682 }
fredcf2458862012-04-16 15:18:27 -0700683 }
684
Zhihai Xu401202b2012-12-03 11:36:21 -0800685 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700686 Slog.d(TAG,"enable(): mBluetooth =" + mBluetooth +
Sanket Agarwal090bf552016-04-21 14:10:55 -0700687 " mBinding = " + mBinding + " mState = " + mState);
688 }
Zhihai Xu401202b2012-12-03 11:36:21 -0800689
690 synchronized(mReceiver) {
691 mQuietEnableExternal = false;
692 mEnableExternal = true;
693 // waive WRITE_SECURE_SETTINGS permission check
Zhihai Xu401202b2012-12-03 11:36:21 -0800694 sendEnableMsg(false);
695 }
Jeff Sharkey67609c72016-03-05 14:29:13 -0700696 if (DBG) Slog.d(TAG, "enable returning");
Zhihai Xu401202b2012-12-03 11:36:21 -0800697 return true;
fredc0f420372012-04-12 00:02:00 -0700698 }
699
Svetoslav Ganovb1e2da72016-06-29 17:31:44 -0700700 public boolean disable(String packageName, boolean persist) throws RemoteException {
701 final int callingUid = Binder.getCallingUid();
702 final boolean callerSystem = UserHandle.getAppId(callingUid) == Process.SYSTEM_UID;
Zhihai Xu40874a02012-10-08 17:57:03 -0700703
Svetoslav Ganovb1e2da72016-06-29 17:31:44 -0700704 if (!callerSystem) {
705 if (!checkIfCallerIsForegroundUser()) {
706 Slog.w(TAG, "disable(): not allowed for non-active and non system user");
707 return false;
708 }
709
710 mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
711 "Need BLUETOOTH ADMIN permission");
712
Ivan Podogovd2d32b12016-12-05 16:46:52 +0000713 if (isEnabled() && mPermissionReviewRequired) {
714 startConsentUi(packageName, callingUid, BluetoothAdapter.ACTION_REQUEST_DISABLE);
Svetoslav Ganovb1e2da72016-06-29 17:31:44 -0700715 return false;
716 }
Zhihai Xu40874a02012-10-08 17:57:03 -0700717 }
718
fredcf2458862012-04-16 15:18:27 -0700719 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700720 Slog.d(TAG,"disable(): mBluetooth = " + mBluetooth +
Matthew Xiecdce0b92012-07-12 19:06:15 -0700721 " mBinding = " + mBinding);
722 }
fredcf2458862012-04-16 15:18:27 -0700723
Zhihai Xu401202b2012-12-03 11:36:21 -0800724 synchronized(mReceiver) {
725 if (persist) {
726 // waive WRITE_SECURE_SETTINGS permission check
727 long callingIdentity = Binder.clearCallingIdentity();
728 persistBluetoothSetting(BLUETOOTH_OFF);
729 Binder.restoreCallingIdentity(callingIdentity);
730 }
731 mEnableExternal = false;
732 sendDisableMsg();
733 }
fredc0f420372012-04-12 00:02:00 -0700734 return true;
735 }
736
Ivan Podogovd2d32b12016-12-05 16:46:52 +0000737 private void startConsentUi(String packageName, int callingUid, String intentAction)
738 throws RemoteException {
Svetoslav Ganovb1e2da72016-06-29 17:31:44 -0700739 try {
740 // Validate the package only if we are going to use it
741 ApplicationInfo applicationInfo = mContext.getPackageManager()
742 .getApplicationInfoAsUser(packageName,
743 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
744 UserHandle.getUserId(callingUid));
745 if (applicationInfo.uid != callingUid) {
746 throw new SecurityException("Package " + callingUid
747 + " not in uid " + callingUid);
748 }
749
Ivan Podogovd2d32b12016-12-05 16:46:52 +0000750 // Permission review mode, trigger a user prompt
751 Intent intent = new Intent(intentAction);
752 mContext.startActivity(intent);
Svetoslav Ganovb1e2da72016-06-29 17:31:44 -0700753 } catch (PackageManager.NameNotFoundException e) {
754 throw new RemoteException(e.getMessage());
755 }
Svetoslav Ganovb1e2da72016-06-29 17:31:44 -0700756 }
757
fredc649fe492012-04-19 01:07:18 -0700758 public void unbindAndFinish() {
fredcf2458862012-04-16 15:18:27 -0700759 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700760 Slog.d(TAG,"unbindAndFinish(): " + mBluetooth +
Matthew Xiecdce0b92012-07-12 19:06:15 -0700761 " mBinding = " + mBinding);
fredcf2458862012-04-16 15:18:27 -0700762 }
763
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700764 try {
765 mBluetoothLock.writeLock().lock();
fredc0f420372012-04-12 00:02:00 -0700766 if (mUnbinding) return;
767 mUnbinding = true;
Pavlin Radoslavove47ec142016-06-01 22:25:18 -0700768 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
Pavlin Radoslavovc7dda102016-09-21 17:28:11 -0700769 mHandler.removeMessages(MESSAGE_BIND_PROFILE_SERVICE);
Zhihai Xu40874a02012-10-08 17:57:03 -0700770 if (mBluetooth != null) {
Andre Eisenbach305fdab2015-11-11 21:43:26 -0800771 //Unregister callback object
772 try {
773 mBluetooth.unregisterCallback(mBluetoothCallback);
774 } catch (RemoteException re) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700775 Slog.e(TAG, "Unable to unregister BluetoothCallback",re);
fredcbf072a72012-05-09 16:52:50 -0700776 }
Andre Eisenbach305fdab2015-11-11 21:43:26 -0800777
Jeff Sharkey67609c72016-03-05 14:29:13 -0700778 if (DBG) Slog.d(TAG, "Sending unbind request.");
Marie Janssen9db28eb2016-01-12 16:05:15 -0800779 mBluetoothBinder = null;
fredcd6883532012-04-25 17:46:13 -0700780 mBluetooth = null;
781 //Unbind
fredc0f420372012-04-12 00:02:00 -0700782 mContext.unbindService(mConnection);
fredcd6883532012-04-25 17:46:13 -0700783 mUnbinding = false;
Zhihai Xu40874a02012-10-08 17:57:03 -0700784 mBinding = false;
fredcf2458862012-04-16 15:18:27 -0700785 } else {
786 mUnbinding=false;
fredc0f420372012-04-12 00:02:00 -0700787 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800788 mBluetoothGatt = null;
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700789 } finally {
790 mBluetoothLock.writeLock().unlock();
fredc0f420372012-04-12 00:02:00 -0700791 }
792 }
793
Matthew Xieddf7e472013-03-01 18:41:02 -0800794 public IBluetoothGatt getBluetoothGatt() {
795 // sync protection
796 return mBluetoothGatt;
797 }
798
Benjamin Franze8b98922014-11-12 15:57:54 +0000799 @Override
800 public boolean bindBluetoothProfileService(int bluetoothProfile,
801 IBluetoothProfileServiceConnection proxy) {
802 if (!mEnable) {
803 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700804 Slog.d(TAG, "Trying to bind to profile: " + bluetoothProfile +
Benjamin Franze8b98922014-11-12 15:57:54 +0000805 ", while Bluetooth was disabled");
806 }
807 return false;
808 }
809 synchronized (mProfileServices) {
810 ProfileServiceConnections psc = mProfileServices.get(new Integer(bluetoothProfile));
811 if (psc == null) {
812 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700813 Slog.d(TAG, "Creating new ProfileServiceConnections object for"
Benjamin Franze8b98922014-11-12 15:57:54 +0000814 + " profile: " + bluetoothProfile);
815 }
Benjamin Franz5b614592014-12-09 18:58:45 +0000816
817 if (bluetoothProfile != BluetoothProfile.HEADSET) return false;
818
819 Intent intent = new Intent(IBluetoothHeadset.class.getName());
Benjamin Franze8b98922014-11-12 15:57:54 +0000820 psc = new ProfileServiceConnections(intent);
Benjamin Franz5b614592014-12-09 18:58:45 +0000821 if (!psc.bindService()) return false;
822
Benjamin Franze8b98922014-11-12 15:57:54 +0000823 mProfileServices.put(new Integer(bluetoothProfile), psc);
Benjamin Franze8b98922014-11-12 15:57:54 +0000824 }
825 }
826
827 // Introducing a delay to give the client app time to prepare
828 Message addProxyMsg = mHandler.obtainMessage(MESSAGE_ADD_PROXY_DELAYED);
829 addProxyMsg.arg1 = bluetoothProfile;
830 addProxyMsg.obj = proxy;
831 mHandler.sendMessageDelayed(addProxyMsg, ADD_PROXY_DELAY_MS);
832 return true;
833 }
834
835 @Override
836 public void unbindBluetoothProfileService(int bluetoothProfile,
837 IBluetoothProfileServiceConnection proxy) {
838 synchronized (mProfileServices) {
839 ProfileServiceConnections psc = mProfileServices.get(new Integer(bluetoothProfile));
840 if (psc == null) {
841 return;
842 }
843 psc.removeProxy(proxy);
844 }
845 }
846
847 private void unbindAllBluetoothProfileServices() {
848 synchronized (mProfileServices) {
849 for (Integer i : mProfileServices.keySet()) {
850 ProfileServiceConnections psc = mProfileServices.get(i);
Benjamin Franz5b614592014-12-09 18:58:45 +0000851 try {
852 mContext.unbindService(psc);
853 } catch (IllegalArgumentException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700854 Slog.e(TAG, "Unable to unbind service with intent: " + psc.mIntent, e);
Benjamin Franz5b614592014-12-09 18:58:45 +0000855 }
Benjamin Franze8b98922014-11-12 15:57:54 +0000856 psc.removeAllProxies();
857 }
858 mProfileServices.clear();
859 }
860 }
861
862 /**
Miao Chou658bf2f2015-06-26 17:14:35 -0700863 * Send enable message and set adapter name and address. Called when the boot phase becomes
864 * PHASE_SYSTEM_SERVICES_READY.
865 */
866 public void handleOnBootPhase() {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700867 if (DBG) Slog.d(TAG, "Bluetooth boot completed");
Miao Chou658bf2f2015-06-26 17:14:35 -0700868 if (mEnableExternal && isBluetoothPersistedStateOnBluetooth()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700869 if (DBG) Slog.d(TAG, "Auto-enabling Bluetooth.");
Miao Chou658bf2f2015-06-26 17:14:35 -0700870 sendEnableMsg(mQuietEnableExternal);
Ajay Panickerbf796d82016-03-11 13:47:20 -0800871 } else if (!isNameAndAddressSet()) {
872 if (DBG) Slog.d(TAG, "Getting adapter name and address");
Ajay Panicker4bb48302016-03-31 14:14:27 -0700873 Message getMsg = mHandler.obtainMessage(MESSAGE_GET_NAME_AND_ADDRESS);
874 mHandler.sendMessage(getMsg);
Miao Chou658bf2f2015-06-26 17:14:35 -0700875 }
Miao Chou658bf2f2015-06-26 17:14:35 -0700876 }
877
878 /**
879 * Called when switching to a different foreground user.
880 */
881 public void handleOnSwitchUser(int userHandle) {
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -0700882 if (DBG) Slog.d(TAG, "User " + userHandle + " switched");
883 mHandler.obtainMessage(MESSAGE_USER_SWITCHED, userHandle, 0).sendToTarget();
884 }
885
886 /**
887 * Called when user is unlocked.
888 */
889 public void handleOnUnlockUser(int userHandle) {
890 if (DBG) Slog.d(TAG, "User " + userHandle + " unlocked");
891 mHandler.obtainMessage(MESSAGE_USER_UNLOCKED, userHandle, 0).sendToTarget();
Miao Chou658bf2f2015-06-26 17:14:35 -0700892 }
893
894 /**
Benjamin Franze8b98922014-11-12 15:57:54 +0000895 * This class manages the clients connected to a given ProfileService
896 * and maintains the connection with that service.
897 */
898 final private class ProfileServiceConnections implements ServiceConnection,
899 IBinder.DeathRecipient {
900 final RemoteCallbackList<IBluetoothProfileServiceConnection> mProxies =
901 new RemoteCallbackList <IBluetoothProfileServiceConnection>();
902 IBinder mService;
903 ComponentName mClassName;
904 Intent mIntent;
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700905 boolean mInvokingProxyCallbacks = false;
Benjamin Franze8b98922014-11-12 15:57:54 +0000906
907 ProfileServiceConnections(Intent intent) {
908 mService = null;
909 mClassName = null;
910 mIntent = intent;
911 }
912
Benjamin Franz5b614592014-12-09 18:58:45 +0000913 private boolean bindService() {
914 if (mIntent != null && mService == null &&
915 doBind(mIntent, this, 0, UserHandle.CURRENT_OR_SELF)) {
Benjamin Franze8b98922014-11-12 15:57:54 +0000916 Message msg = mHandler.obtainMessage(MESSAGE_BIND_PROFILE_SERVICE);
917 msg.obj = this;
918 mHandler.sendMessageDelayed(msg, TIMEOUT_BIND_MS);
Benjamin Franz5b614592014-12-09 18:58:45 +0000919 return true;
Benjamin Franze8b98922014-11-12 15:57:54 +0000920 }
Jeff Sharkey67609c72016-03-05 14:29:13 -0700921 Slog.w(TAG, "Unable to bind with intent: " + mIntent);
Benjamin Franz5b614592014-12-09 18:58:45 +0000922 return false;
Benjamin Franze8b98922014-11-12 15:57:54 +0000923 }
924
925 private void addProxy(IBluetoothProfileServiceConnection proxy) {
926 mProxies.register(proxy);
927 if (mService != null) {
928 try{
929 proxy.onServiceConnected(mClassName, mService);
930 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700931 Slog.e(TAG, "Unable to connect to proxy", e);
Benjamin Franze8b98922014-11-12 15:57:54 +0000932 }
933 } else {
934 if (!mHandler.hasMessages(MESSAGE_BIND_PROFILE_SERVICE, this)) {
935 Message msg = mHandler.obtainMessage(MESSAGE_BIND_PROFILE_SERVICE);
936 msg.obj = this;
937 mHandler.sendMessage(msg);
938 }
939 }
940 }
941
942 private void removeProxy(IBluetoothProfileServiceConnection proxy) {
943 if (proxy != null) {
944 if (mProxies.unregister(proxy)) {
945 try {
946 proxy.onServiceDisconnected(mClassName);
947 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700948 Slog.e(TAG, "Unable to disconnect proxy", e);
Benjamin Franze8b98922014-11-12 15:57:54 +0000949 }
950 }
951 } else {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700952 Slog.w(TAG, "Trying to remove a null proxy");
Benjamin Franze8b98922014-11-12 15:57:54 +0000953 }
954 }
955
956 private void removeAllProxies() {
957 onServiceDisconnected(mClassName);
958 mProxies.kill();
959 }
960
961 @Override
962 public void onServiceConnected(ComponentName className, IBinder service) {
963 // remove timeout message
964 mHandler.removeMessages(MESSAGE_BIND_PROFILE_SERVICE, this);
965 mService = service;
966 mClassName = className;
967 try {
968 mService.linkToDeath(this, 0);
969 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700970 Slog.e(TAG, "Unable to linkToDeath", e);
Benjamin Franze8b98922014-11-12 15:57:54 +0000971 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700972
973 if (mInvokingProxyCallbacks) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700974 Slog.e(TAG, "Proxy callbacks already in progress.");
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700975 return;
Benjamin Franze8b98922014-11-12 15:57:54 +0000976 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700977 mInvokingProxyCallbacks = true;
978
979 final int n = mProxies.beginBroadcast();
980 try {
981 for (int i = 0; i < n; i++) {
982 try {
983 mProxies.getBroadcastItem(i).onServiceConnected(className, service);
984 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700985 Slog.e(TAG, "Unable to connect to proxy", e);
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700986 }
987 }
988 } finally {
989 mProxies.finishBroadcast();
990 mInvokingProxyCallbacks = false;
991 }
Benjamin Franze8b98922014-11-12 15:57:54 +0000992 }
993
994 @Override
995 public void onServiceDisconnected(ComponentName className) {
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700996 if (mService == null) return;
Benjamin Franze8b98922014-11-12 15:57:54 +0000997 mService.unlinkToDeath(this, 0);
998 mService = null;
999 mClassName = null;
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001000
1001 if (mInvokingProxyCallbacks) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001002 Slog.e(TAG, "Proxy callbacks already in progress.");
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001003 return;
Benjamin Franze8b98922014-11-12 15:57:54 +00001004 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001005 mInvokingProxyCallbacks = true;
1006
1007 final int n = mProxies.beginBroadcast();
1008 try {
1009 for (int i = 0; i < n; i++) {
1010 try {
1011 mProxies.getBroadcastItem(i).onServiceDisconnected(className);
1012 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001013 Slog.e(TAG, "Unable to disconnect from proxy", e);
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001014 }
1015 }
1016 } finally {
1017 mProxies.finishBroadcast();
1018 mInvokingProxyCallbacks = false;
1019 }
Benjamin Franze8b98922014-11-12 15:57:54 +00001020 }
1021
1022 @Override
1023 public void binderDied() {
1024 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001025 Slog.w(TAG, "Profile service for profile: " + mClassName
Benjamin Franze8b98922014-11-12 15:57:54 +00001026 + " died.");
1027 }
1028 onServiceDisconnected(mClassName);
1029 // Trigger rebind
1030 Message msg = mHandler.obtainMessage(MESSAGE_BIND_PROFILE_SERVICE);
1031 msg.obj = this;
1032 mHandler.sendMessageDelayed(msg, TIMEOUT_BIND_MS);
1033 }
1034 }
1035
fredcbf072a72012-05-09 16:52:50 -07001036 private void sendBluetoothStateCallback(boolean isUp) {
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001037 try {
1038 int n = mStateChangeCallbacks.beginBroadcast();
Jeff Sharkey67609c72016-03-05 14:29:13 -07001039 if (DBG) Slog.d(TAG,"Broadcasting onBluetoothStateChange("+isUp+") to " + n + " receivers.");
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001040 for (int i=0; i <n;i++) {
1041 try {
1042 mStateChangeCallbacks.getBroadcastItem(i).onBluetoothStateChange(isUp);
1043 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001044 Slog.e(TAG, "Unable to call onBluetoothStateChange() on callback #" + i , e);
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001045 }
fredcbf072a72012-05-09 16:52:50 -07001046 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001047 } finally {
1048 mStateChangeCallbacks.finishBroadcast();
fredcbf072a72012-05-09 16:52:50 -07001049 }
fredcbf072a72012-05-09 16:52:50 -07001050 }
1051
1052 /**
Zhihai Xu40874a02012-10-08 17:57:03 -07001053 * Inform BluetoothAdapter instances that Adapter service is up
1054 */
1055 private void sendBluetoothServiceUpCallback() {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001056 if (DBG) Slog.d(TAG,"Calling onBluetoothServiceUp callbacks");
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001057 try {
1058 int n = mCallbacks.beginBroadcast();
Jeff Sharkey67609c72016-03-05 14:29:13 -07001059 Slog.d(TAG,"Broadcasting onBluetoothServiceUp() to " + n + " receivers.");
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001060 for (int i=0; i <n;i++) {
1061 try {
1062 mCallbacks.getBroadcastItem(i).onBluetoothServiceUp(mBluetooth);
1063 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001064 Slog.e(TAG, "Unable to call onBluetoothServiceUp() on callback #" + i, e);
Zhihai Xu40874a02012-10-08 17:57:03 -07001065 }
1066 }
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001067 } finally {
1068 mCallbacks.finishBroadcast();
Zhihai Xu40874a02012-10-08 17:57:03 -07001069 }
1070 }
1071 /**
fredcbf072a72012-05-09 16:52:50 -07001072 * Inform BluetoothAdapter instances that Adapter service is down
1073 */
1074 private void sendBluetoothServiceDownCallback() {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001075 if (DBG) Slog.d(TAG,"Calling onBluetoothServiceDown callbacks");
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001076 try {
1077 int n = mCallbacks.beginBroadcast();
Jeff Sharkey67609c72016-03-05 14:29:13 -07001078 Slog.d(TAG,"Broadcasting onBluetoothServiceDown() to " + n + " receivers.");
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001079 for (int i=0; i <n;i++) {
1080 try {
1081 mCallbacks.getBroadcastItem(i).onBluetoothServiceDown();
1082 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001083 Slog.e(TAG, "Unable to call onBluetoothServiceDown() on callback #" + i, e);
fredcd6883532012-04-25 17:46:13 -07001084 }
1085 }
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001086 } finally {
1087 mCallbacks.finishBroadcast();
fredcd6883532012-04-25 17:46:13 -07001088 }
1089 }
Svet Ganov408abf72015-05-12 19:13:36 -07001090
fredc0f420372012-04-12 00:02:00 -07001091 public String getAddress() {
Matthew Xieaf5ddbf2012-12-04 10:47:43 -08001092 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
Svet Ganov408abf72015-05-12 19:13:36 -07001093 "Need BLUETOOTH permission");
Zhihai Xu40874a02012-10-08 17:57:03 -07001094
Zhihai Xu6eb76522012-11-29 15:41:04 -08001095 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
Svet Ganov408abf72015-05-12 19:13:36 -07001096 (!checkIfCallerIsForegroundUser())) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001097 Slog.w(TAG,"getAddress(): not allowed for non-active and non system user");
Zhihai Xu6eb76522012-11-29 15:41:04 -08001098 return null;
Zhihai Xu40874a02012-10-08 17:57:03 -07001099 }
1100
Svet Ganov408abf72015-05-12 19:13:36 -07001101 if (mContext.checkCallingOrSelfPermission(Manifest.permission.LOCAL_MAC_ADDRESS)
1102 != PackageManager.PERMISSION_GRANTED) {
1103 return BluetoothAdapter.DEFAULT_MAC_ADDRESS;
1104 }
1105
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001106 try {
1107 mBluetoothLock.readLock().lock();
1108 if (mBluetooth != null) return mBluetooth.getAddress();
1109 } catch (RemoteException e) {
1110 Slog.e(TAG, "getAddress(): Unable to retrieve address remotely. Returning cached address", e);
1111 } finally {
1112 mBluetoothLock.readLock().unlock();
fredc116d1d462012-04-20 14:47:08 -07001113 }
Ajay Panickerbf796d82016-03-11 13:47:20 -08001114
Matthew Xiecdce0b92012-07-12 19:06:15 -07001115 // mAddress is accessed from outside.
1116 // It is alright without a lock. Here, bluetooth is off, no other thread is
1117 // changing mAddress
fredc0f420372012-04-12 00:02:00 -07001118 return mAddress;
1119 }
fredc649fe492012-04-19 01:07:18 -07001120
fredc0f420372012-04-12 00:02:00 -07001121 public String getName() {
Matthew Xieaf5ddbf2012-12-04 10:47:43 -08001122 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
1123 "Need BLUETOOTH permission");
Zhihai Xu40874a02012-10-08 17:57:03 -07001124
Zhihai Xu6eb76522012-11-29 15:41:04 -08001125 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
1126 (!checkIfCallerIsForegroundUser())) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001127 Slog.w(TAG,"getName(): not allowed for non-active and non system user");
Zhihai Xu6eb76522012-11-29 15:41:04 -08001128 return null;
Zhihai Xu40874a02012-10-08 17:57:03 -07001129 }
1130
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001131 try {
1132 mBluetoothLock.readLock().lock();
1133 if (mBluetooth != null) return mBluetooth.getName();
1134 } catch (RemoteException e) {
1135 Slog.e(TAG, "getName(): Unable to retrieve name remotely. Returning cached name", e);
1136 } finally {
1137 mBluetoothLock.readLock().unlock();
fredc116d1d462012-04-20 14:47:08 -07001138 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001139
Matthew Xiecdce0b92012-07-12 19:06:15 -07001140 // mName is accessed from outside.
1141 // It alright without a lock. Here, bluetooth is off, no other thread is
1142 // changing mName
fredc0f420372012-04-12 00:02:00 -07001143 return mName;
1144 }
1145
fredc0f420372012-04-12 00:02:00 -07001146 private class BluetoothServiceConnection implements ServiceConnection {
fredc0f420372012-04-12 00:02:00 -07001147 public void onServiceConnected(ComponentName className, IBinder service) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001148 if (DBG) Slog.d(TAG, "BluetoothServiceConnection: " + className.getClassName());
fredc0f420372012-04-12 00:02:00 -07001149 Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_SERVICE_CONNECTED);
Matthew Xieddf7e472013-03-01 18:41:02 -08001150 // TBD if (className.getClassName().equals(IBluetooth.class.getName())) {
1151 if (className.getClassName().equals("com.android.bluetooth.btservice.AdapterService")) {
1152 msg.arg1 = SERVICE_IBLUETOOTH;
1153 // } else if (className.getClassName().equals(IBluetoothGatt.class.getName())) {
1154 } else if (className.getClassName().equals("com.android.bluetooth.gatt.GattService")) {
1155 msg.arg1 = SERVICE_IBLUETOOTHGATT;
1156 } else {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001157 Slog.e(TAG, "Unknown service connected: " + className.getClassName());
Matthew Xieddf7e472013-03-01 18:41:02 -08001158 return;
1159 }
fredc0f420372012-04-12 00:02:00 -07001160 msg.obj = service;
1161 mHandler.sendMessage(msg);
1162 }
1163
1164 public void onServiceDisconnected(ComponentName className) {
fredc0f420372012-04-12 00:02:00 -07001165 // Called if we unexpected disconnected.
Jeff Sharkey67609c72016-03-05 14:29:13 -07001166 if (DBG) Slog.d(TAG, "BluetoothServiceConnection, disconnected: " +
Matthew Xieddf7e472013-03-01 18:41:02 -08001167 className.getClassName());
fredc0f420372012-04-12 00:02:00 -07001168 Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED);
Matthew Xieddf7e472013-03-01 18:41:02 -08001169 if (className.getClassName().equals("com.android.bluetooth.btservice.AdapterService")) {
1170 msg.arg1 = SERVICE_IBLUETOOTH;
1171 } else if (className.getClassName().equals("com.android.bluetooth.gatt.GattService")) {
1172 msg.arg1 = SERVICE_IBLUETOOTHGATT;
1173 } else {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001174 Slog.e(TAG, "Unknown service disconnected: " + className.getClassName());
Matthew Xieddf7e472013-03-01 18:41:02 -08001175 return;
1176 }
fredc0f420372012-04-12 00:02:00 -07001177 mHandler.sendMessage(msg);
1178 }
1179 }
1180
1181 private BluetoothServiceConnection mConnection = new BluetoothServiceConnection();
1182
Zhihai Xu40874a02012-10-08 17:57:03 -07001183 private class BluetoothHandler extends Handler {
Ajay Panicker4bb48302016-03-31 14:14:27 -07001184 boolean mGetNameAddressOnly = false;
1185
Zhihai Xu40874a02012-10-08 17:57:03 -07001186 public BluetoothHandler(Looper looper) {
1187 super(looper);
1188 }
1189
fredc0f420372012-04-12 00:02:00 -07001190 @Override
1191 public void handleMessage(Message msg) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001192 if (DBG) Slog.d (TAG, "Message: " + msg.what);
fredc0f420372012-04-12 00:02:00 -07001193 switch (msg.what) {
Ajay Panicker4bb48302016-03-31 14:14:27 -07001194 case MESSAGE_GET_NAME_AND_ADDRESS:
1195 if (DBG) Slog.d(TAG, "MESSAGE_GET_NAME_AND_ADDRESS");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001196 try {
1197 mBluetoothLock.writeLock().lock();
Ajay Panicker4bb48302016-03-31 14:14:27 -07001198 if ((mBluetooth == null) && (!mBinding)) {
1199 if (DBG) Slog.d(TAG, "Binding to service to get name and address");
1200 mGetNameAddressOnly = true;
1201 Message timeoutMsg = mHandler.obtainMessage(MESSAGE_TIMEOUT_BIND);
1202 mHandler.sendMessageDelayed(timeoutMsg, TIMEOUT_BIND_MS);
1203 Intent i = new Intent(IBluetooth.class.getName());
1204 if (!doBind(i, mConnection,
1205 Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT,
1206 UserHandle.CURRENT)) {
1207 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
1208 } else {
1209 mBinding = true;
1210 }
1211 } else if (mBluetooth != null) {
1212 try {
1213 storeNameAndAddress(mBluetooth.getName(),
1214 mBluetooth.getAddress());
1215 } catch (RemoteException re) {
1216 Slog.e(TAG, "Unable to grab names", re);
1217 }
1218 if (mGetNameAddressOnly && !mEnable) {
1219 unbindAndFinish();
1220 }
1221 mGetNameAddressOnly = false;
1222 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001223 } finally {
1224 mBluetoothLock.writeLock().unlock();
Ajay Panicker4bb48302016-03-31 14:14:27 -07001225 }
1226 break;
1227
Matthew Xiecdce0b92012-07-12 19:06:15 -07001228 case MESSAGE_ENABLE:
fredcf2458862012-04-16 15:18:27 -07001229 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001230 Slog.d(TAG, "MESSAGE_ENABLE: mBluetooth = " + mBluetooth);
fredc649fe492012-04-19 01:07:18 -07001231 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001232 mHandler.removeMessages(MESSAGE_RESTART_BLUETOOTH_SERVICE);
1233 mEnable = true;
Calvin Ona0b91d72016-06-15 17:58:23 -07001234
1235 // Use service interface to get the exact state
1236 try {
1237 mBluetoothLock.readLock().lock();
1238 if (mBluetooth != null) {
1239 int state = mBluetooth.getState();
1240 if (state == BluetoothAdapter.STATE_BLE_ON) {
1241 Slog.w(TAG, "BT is in BLE_ON State");
1242 mBluetooth.onLeServiceUp();
1243 break;
1244 }
1245 }
1246 } catch (RemoteException e) {
1247 Slog.e(TAG, "", e);
1248 } finally {
1249 mBluetoothLock.readLock().unlock();
1250 }
1251
1252 mQuietEnable = (msg.arg1 == 1);
Pavlin Radoslavove47ec142016-06-01 22:25:18 -07001253 if (mBluetooth == null) {
Calvin Ona0b91d72016-06-15 17:58:23 -07001254 handleEnable(mQuietEnable);
Pavlin Radoslavove47ec142016-06-01 22:25:18 -07001255 } else {
1256 //
1257 // We need to wait until transitioned to STATE_OFF and
1258 // the previous Bluetooth process has exited. The
1259 // waiting period has three components:
1260 // (a) Wait until the local state is STATE_OFF. This
1261 // is accomplished by "waitForOnOff(false, true)".
1262 // (b) Wait until the STATE_OFF state is updated to
1263 // all components.
1264 // (c) Wait until the Bluetooth process exits, and
1265 // ActivityManager detects it.
1266 // The waiting for (b) and (c) is accomplished by
1267 // delaying the MESSAGE_RESTART_BLUETOOTH_SERVICE
1268 // message. On slower devices, that delay needs to be
1269 // on the order of (2 * SERVICE_RESTART_TIME_MS).
1270 //
1271 waitForOnOff(false, true);
Pavlin Radoslavove47ec142016-06-01 22:25:18 -07001272 Message restartMsg = mHandler.obtainMessage(
1273 MESSAGE_RESTART_BLUETOOTH_SERVICE);
1274 mHandler.sendMessageDelayed(restartMsg,
1275 2 * SERVICE_RESTART_TIME_MS);
1276 }
fredc649fe492012-04-19 01:07:18 -07001277 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001278
fredc0f420372012-04-12 00:02:00 -07001279 case MESSAGE_DISABLE:
Zhihai Xu40874a02012-10-08 17:57:03 -07001280 mHandler.removeMessages(MESSAGE_RESTART_BLUETOOTH_SERVICE);
1281 if (mEnable && mBluetooth != null) {
1282 waitForOnOff(true, false);
1283 mEnable = false;
Zhihai Xu401202b2012-12-03 11:36:21 -08001284 handleDisable();
Zhihai Xu40874a02012-10-08 17:57:03 -07001285 waitForOnOff(false, false);
1286 } else {
1287 mEnable = false;
Zhihai Xu401202b2012-12-03 11:36:21 -08001288 handleDisable();
Zhihai Xu40874a02012-10-08 17:57:03 -07001289 }
fredc0f420372012-04-12 00:02:00 -07001290 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001291
fredc0f420372012-04-12 00:02:00 -07001292 case MESSAGE_REGISTER_ADAPTER:
1293 {
1294 IBluetoothManagerCallback callback = (IBluetoothManagerCallback) msg.obj;
fredcd6883532012-04-25 17:46:13 -07001295 boolean added = mCallbacks.register(callback);
Jeff Sharkey67609c72016-03-05 14:29:13 -07001296 Slog.d(TAG,"Added callback: " + (callback == null? "null": callback) +":" +added );
fredc0f420372012-04-12 00:02:00 -07001297 }
1298 break;
1299 case MESSAGE_UNREGISTER_ADAPTER:
1300 {
1301 IBluetoothManagerCallback callback = (IBluetoothManagerCallback) msg.obj;
fredcd6883532012-04-25 17:46:13 -07001302 boolean removed = mCallbacks.unregister(callback);
Jeff Sharkey67609c72016-03-05 14:29:13 -07001303 Slog.d(TAG,"Removed callback: " + (callback == null? "null": callback) +":" + removed);
fredc0f420372012-04-12 00:02:00 -07001304 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001305 }
fredc0f420372012-04-12 00:02:00 -07001306 case MESSAGE_REGISTER_STATE_CHANGE_CALLBACK:
1307 {
1308 IBluetoothStateChangeCallback callback = (IBluetoothStateChangeCallback) msg.obj;
Matthew Xie9b693992013-10-10 11:21:40 -07001309 if (callback != null) {
1310 mStateChangeCallbacks.register(callback);
1311 }
fredc0f420372012-04-12 00:02:00 -07001312 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001313 }
fredc0f420372012-04-12 00:02:00 -07001314 case MESSAGE_UNREGISTER_STATE_CHANGE_CALLBACK:
1315 {
1316 IBluetoothStateChangeCallback callback = (IBluetoothStateChangeCallback) msg.obj;
Matthew Xie9b693992013-10-10 11:21:40 -07001317 if (callback != null) {
1318 mStateChangeCallbacks.unregister(callback);
1319 }
fredc0f420372012-04-12 00:02:00 -07001320 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001321 }
Benjamin Franze8b98922014-11-12 15:57:54 +00001322 case MESSAGE_ADD_PROXY_DELAYED:
1323 {
1324 ProfileServiceConnections psc = mProfileServices.get(
1325 new Integer(msg.arg1));
1326 if (psc == null) {
1327 break;
1328 }
1329 IBluetoothProfileServiceConnection proxy =
1330 (IBluetoothProfileServiceConnection) msg.obj;
1331 psc.addProxy(proxy);
1332 break;
1333 }
1334 case MESSAGE_BIND_PROFILE_SERVICE:
1335 {
1336 ProfileServiceConnections psc = (ProfileServiceConnections) msg.obj;
1337 removeMessages(MESSAGE_BIND_PROFILE_SERVICE, msg.obj);
1338 if (psc == null) {
1339 break;
1340 }
1341 psc.bindService();
1342 break;
1343 }
fredc0f420372012-04-12 00:02:00 -07001344 case MESSAGE_BLUETOOTH_SERVICE_CONNECTED:
1345 {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001346 if (DBG) Slog.d(TAG,"MESSAGE_BLUETOOTH_SERVICE_CONNECTED: " + msg.arg1);
fredc0f420372012-04-12 00:02:00 -07001347
1348 IBinder service = (IBinder) msg.obj;
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001349 try {
1350 mBluetoothLock.writeLock().lock();
Matthew Xieddf7e472013-03-01 18:41:02 -08001351 if (msg.arg1 == SERVICE_IBLUETOOTHGATT) {
1352 mBluetoothGatt = IBluetoothGatt.Stub.asInterface(service);
Nitin Arorad055adb2015-03-02 15:03:51 -08001353 onBluetoothGattServiceUp();
Matthew Xieddf7e472013-03-01 18:41:02 -08001354 break;
1355 } // else must be SERVICE_IBLUETOOTH
1356
1357 //Remove timeout
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001358 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
Matthew Xieddf7e472013-03-01 18:41:02 -08001359
fredc0f420372012-04-12 00:02:00 -07001360 mBinding = false;
Marie Janssen9db28eb2016-01-12 16:05:15 -08001361 mBluetoothBinder = service;
fredc0f420372012-04-12 00:02:00 -07001362 mBluetooth = IBluetooth.Stub.asInterface(service);
fredc0f420372012-04-12 00:02:00 -07001363
Ajay Panicker4bb48302016-03-31 14:14:27 -07001364 if (!isNameAndAddressSet()) {
1365 Message getMsg = mHandler.obtainMessage(MESSAGE_GET_NAME_AND_ADDRESS);
1366 mHandler.sendMessage(getMsg);
1367 if (mGetNameAddressOnly) return;
1368 }
1369
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001370 try {
1371 boolean enableHciSnoopLog = (Settings.Secure.getInt(mContentResolver,
1372 Settings.Secure.BLUETOOTH_HCI_LOG, 0) == 1);
1373 if (!mBluetooth.configHciSnoopLog(enableHciSnoopLog)) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001374 Slog.e(TAG,"IBluetooth.configHciSnoopLog return false");
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001375 }
1376 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001377 Slog.e(TAG,"Unable to call configHciSnoopLog", e);
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001378 }
1379
Matthew Xiecdce0b92012-07-12 19:06:15 -07001380 //Register callback object
fredcbf072a72012-05-09 16:52:50 -07001381 try {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001382 mBluetooth.registerCallback(mBluetoothCallback);
1383 } catch (RemoteException re) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001384 Slog.e(TAG, "Unable to register BluetoothCallback",re);
fredcbf072a72012-05-09 16:52:50 -07001385 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001386 //Inform BluetoothAdapter instances that service is up
Zhihai Xu40874a02012-10-08 17:57:03 -07001387 sendBluetoothServiceUpCallback();
1388
Matthew Xiecdce0b92012-07-12 19:06:15 -07001389 //Do enable request
1390 try {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001391 if (mQuietEnable == false) {
1392 if(!mBluetooth.enable()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001393 Slog.e(TAG,"IBluetooth.enable() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001394 }
1395 }
1396 else
1397 {
1398 if(!mBluetooth.enableNoAutoConnect()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001399 Slog.e(TAG,"IBluetooth.enableNoAutoConnect() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001400 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001401 }
1402 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001403 Slog.e(TAG,"Unable to call enable()",e);
Matthew Xiecdce0b92012-07-12 19:06:15 -07001404 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001405 } finally {
1406 mBluetoothLock.writeLock().unlock();
Freda8c6df02012-07-11 10:25:23 -07001407 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001408
1409 if (!mEnable) {
1410 waitForOnOff(true, false);
Zhihai Xu401202b2012-12-03 11:36:21 -08001411 handleDisable();
Zhihai Xu40874a02012-10-08 17:57:03 -07001412 waitForOnOff(false, false);
1413 }
fredc649fe492012-04-19 01:07:18 -07001414 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001415 }
fredc649fe492012-04-19 01:07:18 -07001416 case MESSAGE_TIMEOUT_BIND: {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001417 Slog.e(TAG, "MESSAGE_TIMEOUT_BIND");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001418 mBluetoothLock.writeLock().lock();
1419 mBinding = false;
1420 mBluetoothLock.writeLock().unlock();
1421
fredc649fe492012-04-19 01:07:18 -07001422 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001423 }
fredcbf072a72012-05-09 16:52:50 -07001424 case MESSAGE_BLUETOOTH_STATE_CHANGE:
fredc0f420372012-04-12 00:02:00 -07001425 {
fredcbf072a72012-05-09 16:52:50 -07001426 int prevState = msg.arg1;
1427 int newState = msg.arg2;
Marie Janssen9fa24912016-10-18 10:04:24 -07001428 if (DBG) Slog.d(TAG, "MESSAGE_BLUETOOTH_STATE_CHANGE: prevState = " + prevState + ", newState =" + newState);
Zhihai Xu40874a02012-10-08 17:57:03 -07001429 mState = newState;
1430 bluetoothStateChangeHandler(prevState, newState);
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001431 // handle error state transition case from TURNING_ON to OFF
1432 // unbind and rebind bluetooth service and enable bluetooth
Nitin Arorad055adb2015-03-02 15:03:51 -08001433 if ((prevState == BluetoothAdapter.STATE_BLE_TURNING_ON) &&
Calvin Ona0b91d72016-06-15 17:58:23 -07001434 (newState == BluetoothAdapter.STATE_OFF) &&
1435 (mBluetooth != null) && mEnable) {
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001436 recoverBluetoothServiceFromError();
1437 }
Nitin Arorad055adb2015-03-02 15:03:51 -08001438 if ((prevState == BluetoothAdapter.STATE_TURNING_ON) &&
Calvin Ona0b91d72016-06-15 17:58:23 -07001439 (newState == BluetoothAdapter.STATE_BLE_ON) &&
1440 (mBluetooth != null) && mEnable) {
Nitin Arorad055adb2015-03-02 15:03:51 -08001441 recoverBluetoothServiceFromError();
1442 }
Calvin Ona0b91d72016-06-15 17:58:23 -07001443 // If we tried to enable BT while BT was in the process of shutting down,
1444 // wait for the BT process to fully tear down and then force a restart
1445 // here. This is a bit of a hack (b/29363429).
1446 if ((prevState == BluetoothAdapter.STATE_BLE_TURNING_OFF) &&
1447 (newState == BluetoothAdapter.STATE_OFF)) {
1448 if (mEnable) {
1449 Slog.d(TAG, "Entering STATE_OFF but mEnabled is true; restarting.");
1450 waitForOnOff(false, true);
1451 Message restartMsg = mHandler.obtainMessage(
1452 MESSAGE_RESTART_BLUETOOTH_SERVICE);
1453 mHandler.sendMessageDelayed(restartMsg, 2 * SERVICE_RESTART_TIME_MS);
1454 }
1455 }
Nitin Arorad055adb2015-03-02 15:03:51 -08001456 if (newState == BluetoothAdapter.STATE_ON ||
Calvin Ona0b91d72016-06-15 17:58:23 -07001457 newState == BluetoothAdapter.STATE_BLE_ON) {
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001458 // bluetooth is working, reset the counter
1459 if (mErrorRecoveryRetryCounter != 0) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001460 Slog.w(TAG, "bluetooth is recovered from error");
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001461 mErrorRecoveryRetryCounter = 0;
1462 }
1463 }
fredc649fe492012-04-19 01:07:18 -07001464 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001465 }
fredc0f420372012-04-12 00:02:00 -07001466 case MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED:
1467 {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001468 Slog.e(TAG, "MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED: " + msg.arg1);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001469 try {
1470 mBluetoothLock.writeLock().lock();
Matthew Xieddf7e472013-03-01 18:41:02 -08001471 if (msg.arg1 == SERVICE_IBLUETOOTH) {
1472 // if service is unbinded already, do nothing and return
1473 if (mBluetooth == null) break;
1474 mBluetooth = null;
1475 } else if (msg.arg1 == SERVICE_IBLUETOOTHGATT) {
1476 mBluetoothGatt = null;
1477 break;
1478 } else {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001479 Slog.e(TAG, "Bad msg.arg1: " + msg.arg1);
Matthew Xieddf7e472013-03-01 18:41:02 -08001480 break;
1481 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001482 } finally {
1483 mBluetoothLock.writeLock().unlock();
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301484 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001485
1486 if (mEnable) {
1487 mEnable = false;
1488 // Send a Bluetooth Restart message
1489 Message restartMsg = mHandler.obtainMessage(
1490 MESSAGE_RESTART_BLUETOOTH_SERVICE);
1491 mHandler.sendMessageDelayed(restartMsg,
1492 SERVICE_RESTART_TIME_MS);
1493 }
1494
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001495 sendBluetoothServiceDownCallback();
Zhihai Xu40874a02012-10-08 17:57:03 -07001496
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001497 // Send BT state broadcast to update
1498 // the BT icon correctly
1499 if ((mState == BluetoothAdapter.STATE_TURNING_ON) ||
Calvin Ona0b91d72016-06-15 17:58:23 -07001500 (mState == BluetoothAdapter.STATE_ON)) {
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001501 bluetoothStateChangeHandler(BluetoothAdapter.STATE_ON,
1502 BluetoothAdapter.STATE_TURNING_OFF);
1503 mState = BluetoothAdapter.STATE_TURNING_OFF;
Zhihai Xu40874a02012-10-08 17:57:03 -07001504 }
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001505 if (mState == BluetoothAdapter.STATE_TURNING_OFF) {
1506 bluetoothStateChangeHandler(BluetoothAdapter.STATE_TURNING_OFF,
1507 BluetoothAdapter.STATE_OFF);
1508 }
1509
1510 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
1511 mState = BluetoothAdapter.STATE_OFF;
fredc649fe492012-04-19 01:07:18 -07001512 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001513 }
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301514 case MESSAGE_RESTART_BLUETOOTH_SERVICE:
1515 {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001516 Slog.d(TAG, "MESSAGE_RESTART_BLUETOOTH_SERVICE:"
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301517 +" Restart IBluetooth service");
1518 /* Enable without persisting the setting as
1519 it doesnt change when IBluetooth
1520 service restarts */
Zhihai Xu40874a02012-10-08 17:57:03 -07001521 mEnable = true;
Zhihai Xu401202b2012-12-03 11:36:21 -08001522 handleEnable(mQuietEnable);
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301523 break;
1524 }
1525
fredc0f420372012-04-12 00:02:00 -07001526 case MESSAGE_TIMEOUT_UNBIND:
1527 {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001528 Slog.e(TAG, "MESSAGE_TIMEOUT_UNBIND");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001529 mBluetoothLock.writeLock().lock();
1530 mUnbinding = false;
1531 mBluetoothLock.writeLock().unlock();
fredc649fe492012-04-19 01:07:18 -07001532 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001533 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001534
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001535 case MESSAGE_USER_SWITCHED: {
1536 if (DBG) Slog.d(TAG, "MESSAGE_USER_SWITCHED");
Zhihai Xu40874a02012-10-08 17:57:03 -07001537 mHandler.removeMessages(MESSAGE_USER_SWITCHED);
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001538
Zhihai Xu40874a02012-10-08 17:57:03 -07001539 /* disable and enable BT when detect a user switch */
1540 if (mEnable && mBluetooth != null) {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001541 try {
1542 mBluetoothLock.readLock().lock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001543 if (mBluetooth != null) {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001544 mBluetooth.unregisterCallback(mBluetoothCallback);
Zhihai Xu40874a02012-10-08 17:57:03 -07001545 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001546 } catch (RemoteException re) {
1547 Slog.e(TAG, "Unable to unregister", re);
1548 } finally {
1549 mBluetoothLock.readLock().unlock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001550 }
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001551
1552 if (mState == BluetoothAdapter.STATE_TURNING_OFF) {
1553 // MESSAGE_USER_SWITCHED happened right after MESSAGE_ENABLE
1554 bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_OFF);
1555 mState = BluetoothAdapter.STATE_OFF;
1556 }
1557 if (mState == BluetoothAdapter.STATE_OFF) {
1558 bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_TURNING_ON);
1559 mState = BluetoothAdapter.STATE_TURNING_ON;
1560 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001561
1562 waitForOnOff(true, false);
1563
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001564 if (mState == BluetoothAdapter.STATE_TURNING_ON) {
1565 bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_ON);
1566 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001567
Benjamin Franze8b98922014-11-12 15:57:54 +00001568 unbindAllBluetoothProfileServices();
Zhihai Xu40874a02012-10-08 17:57:03 -07001569 // disable
Zhihai Xu401202b2012-12-03 11:36:21 -08001570 handleDisable();
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001571 // Pbap service need receive STATE_TURNING_OFF intent to close
1572 bluetoothStateChangeHandler(BluetoothAdapter.STATE_ON,
1573 BluetoothAdapter.STATE_TURNING_OFF);
Zhihai Xu40874a02012-10-08 17:57:03 -07001574
Pavlin Radoslavov41401112016-06-27 15:25:18 -07001575 boolean didDisableTimeout = !waitForOnOff(false, true);
Zhihai Xu40874a02012-10-08 17:57:03 -07001576
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001577 bluetoothStateChangeHandler(BluetoothAdapter.STATE_TURNING_OFF,
Zhihai Xu40874a02012-10-08 17:57:03 -07001578 BluetoothAdapter.STATE_OFF);
Zhihai Xu40874a02012-10-08 17:57:03 -07001579 sendBluetoothServiceDownCallback();
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001580
Pavlin Radoslavove957a8a2016-05-24 15:28:41 -07001581 try {
1582 mBluetoothLock.writeLock().lock();
1583 if (mBluetooth != null) {
1584 mBluetooth = null;
1585 // Unbind
1586 mContext.unbindService(mConnection);
1587 }
1588 mBluetoothGatt = null;
1589 } finally {
1590 mBluetoothLock.writeLock().unlock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001591 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001592
Pavlin Radoslavov41401112016-06-27 15:25:18 -07001593 //
1594 // If disabling Bluetooth times out, wait for an
1595 // additional amount of time to ensure the process is
1596 // shut down completely before attempting to restart.
1597 //
1598 if (didDisableTimeout) {
1599 SystemClock.sleep(3000);
1600 } else {
1601 SystemClock.sleep(100);
1602 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001603
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001604 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
1605 mState = BluetoothAdapter.STATE_OFF;
Zhihai Xu40874a02012-10-08 17:57:03 -07001606 // enable
Zhihai Xu401202b2012-12-03 11:36:21 -08001607 handleEnable(mQuietEnable);
John Spurlock8a985d22014-02-25 09:40:05 -05001608 } else if (mBinding || mBluetooth != null) {
Zhihai Xu40874a02012-10-08 17:57:03 -07001609 Message userMsg = mHandler.obtainMessage(MESSAGE_USER_SWITCHED);
1610 userMsg.arg2 = 1 + msg.arg2;
1611 // if user is switched when service is being binding
1612 // delay sending MESSAGE_USER_SWITCHED
1613 mHandler.sendMessageDelayed(userMsg, USER_SWITCHED_TIME_MS);
1614 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001615 Slog.d(TAG, "delay MESSAGE_USER_SWITCHED " + userMsg.arg2);
Zhihai Xu40874a02012-10-08 17:57:03 -07001616 }
John Spurlock8a985d22014-02-25 09:40:05 -05001617 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001618 break;
1619 }
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001620 case MESSAGE_USER_UNLOCKED: {
1621 if (DBG) Slog.d(TAG, "MESSAGE_USER_UNLOCKED");
1622 mHandler.removeMessages(MESSAGE_USER_SWITCHED);
1623
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001624 if (mEnable && !mBinding && (mBluetooth == null)) {
1625 // We should be connected, but we gave up for some
1626 // reason; maybe the Bluetooth service wasn't encryption
1627 // aware, so try binding again.
1628 if (DBG) Slog.d(TAG, "Enabled but not bound; retrying after unlock");
1629 handleEnable(mQuietEnable);
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001630 }
1631 }
fredc0f420372012-04-12 00:02:00 -07001632 }
1633 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001634 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001635
Zhihai Xu401202b2012-12-03 11:36:21 -08001636 private void handleEnable(boolean quietMode) {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001637 mQuietEnable = quietMode;
1638
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001639 try {
1640 mBluetoothLock.writeLock().lock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001641 if ((mBluetooth == null) && (!mBinding)) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001642 //Start bind timeout and bind
1643 Message timeoutMsg=mHandler.obtainMessage(MESSAGE_TIMEOUT_BIND);
1644 mHandler.sendMessageDelayed(timeoutMsg,TIMEOUT_BIND_MS);
Matthew Xiecdce0b92012-07-12 19:06:15 -07001645 Intent i = new Intent(IBluetooth.class.getName());
Dianne Hackbornce09f5a2014-10-10 15:03:13 -07001646 if (!doBind(i, mConnection,Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT,
1647 UserHandle.CURRENT)) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001648 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
Zhihai Xu40874a02012-10-08 17:57:03 -07001649 } else {
1650 mBinding = true;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001651 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001652 } else if (mBluetooth != null) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001653 //Enable bluetooth
1654 try {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001655 if (!mQuietEnable) {
1656 if(!mBluetooth.enable()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001657 Slog.e(TAG,"IBluetooth.enable() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001658 }
1659 }
1660 else {
1661 if(!mBluetooth.enableNoAutoConnect()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001662 Slog.e(TAG,"IBluetooth.enableNoAutoConnect() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001663 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001664 }
1665 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001666 Slog.e(TAG,"Unable to call enable()",e);
Matthew Xiecdce0b92012-07-12 19:06:15 -07001667 }
1668 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001669 } finally {
1670 mBluetoothLock.writeLock().unlock();
Matthew Xiecdce0b92012-07-12 19:06:15 -07001671 }
1672 }
1673
Dianne Hackborn221ea892013-08-04 16:50:16 -07001674 boolean doBind(Intent intent, ServiceConnection conn, int flags, UserHandle user) {
1675 ComponentName comp = intent.resolveSystemService(mContext.getPackageManager(), 0);
1676 intent.setComponent(comp);
1677 if (comp == null || !mContext.bindServiceAsUser(intent, conn, flags, user)) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001678 Slog.e(TAG, "Fail to bind to: " + intent);
Dianne Hackborn221ea892013-08-04 16:50:16 -07001679 return false;
1680 }
1681 return true;
1682 }
1683
Zhihai Xu401202b2012-12-03 11:36:21 -08001684 private void handleDisable() {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001685 try {
1686 mBluetoothLock.readLock().lock();
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001687 if (mBluetooth != null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001688 if (DBG) Slog.d(TAG,"Sending off request.");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001689 if (!mBluetooth.disable()) {
1690 Slog.e(TAG,"IBluetooth.disable() returned false");
Matthew Xiecdce0b92012-07-12 19:06:15 -07001691 }
1692 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001693 } catch (RemoteException e) {
1694 Slog.e(TAG,"Unable to call disable()",e);
1695 } finally {
1696 mBluetoothLock.readLock().unlock();
Matthew Xiecdce0b92012-07-12 19:06:15 -07001697 }
1698 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001699
1700 private boolean checkIfCallerIsForegroundUser() {
1701 int foregroundUser;
1702 int callingUser = UserHandle.getCallingUserId();
Martijn Coenen8385c5a2012-11-29 10:14:16 -08001703 int callingUid = Binder.getCallingUid();
Zhihai Xu40874a02012-10-08 17:57:03 -07001704 long callingIdentity = Binder.clearCallingIdentity();
Benjamin Franze8b98922014-11-12 15:57:54 +00001705 UserManager um = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
1706 UserInfo ui = um.getProfileParent(callingUser);
1707 int parentUser = (ui != null) ? ui.id : UserHandle.USER_NULL;
Martijn Coenen8385c5a2012-11-29 10:14:16 -08001708 int callingAppId = UserHandle.getAppId(callingUid);
Zhihai Xu40874a02012-10-08 17:57:03 -07001709 boolean valid = false;
1710 try {
1711 foregroundUser = ActivityManager.getCurrentUser();
Martijn Coenen8385c5a2012-11-29 10:14:16 -08001712 valid = (callingUser == foregroundUser) ||
Benjamin Franze8b98922014-11-12 15:57:54 +00001713 parentUser == foregroundUser ||
Adrian Roosbd9a9a52014-08-18 15:31:57 +02001714 callingAppId == Process.NFC_UID ||
1715 callingAppId == mSystemUiUid;
Zhihai Xu40874a02012-10-08 17:57:03 -07001716 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001717 Slog.d(TAG, "checkIfCallerIsForegroundUser: valid=" + valid
Zhihai Xu40874a02012-10-08 17:57:03 -07001718 + " callingUser=" + callingUser
Benjamin Franze8b98922014-11-12 15:57:54 +00001719 + " parentUser=" + parentUser
Zhihai Xu40874a02012-10-08 17:57:03 -07001720 + " foregroundUser=" + foregroundUser);
1721 }
1722 } finally {
1723 Binder.restoreCallingIdentity(callingIdentity);
1724 }
1725 return valid;
1726 }
1727
Nitin Arorad055adb2015-03-02 15:03:51 -08001728 private void sendBleStateChanged(int prevState, int newState) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001729 if (DBG) Slog.d(TAG,"BLE State Change Intent: " + prevState + " -> " + newState);
Nitin Arorad055adb2015-03-02 15:03:51 -08001730 // Send broadcast message to everyone else
1731 Intent intent = new Intent(BluetoothAdapter.ACTION_BLE_STATE_CHANGED);
1732 intent.putExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE, prevState);
1733 intent.putExtra(BluetoothAdapter.EXTRA_STATE, newState);
1734 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1735 mContext.sendBroadcastAsUser(intent, UserHandle.ALL, BLUETOOTH_PERM);
1736 }
1737
Zhihai Xu40874a02012-10-08 17:57:03 -07001738 private void bluetoothStateChangeHandler(int prevState, int newState) {
Nitin Arorad055adb2015-03-02 15:03:51 -08001739 boolean isStandardBroadcast = true;
Marie Janssen9fa24912016-10-18 10:04:24 -07001740 if (DBG) Slog.d(TAG, "bluetoothStateChangeHandler: " + prevState + " -> " + newState);
Zhihai Xu40874a02012-10-08 17:57:03 -07001741 if (prevState != newState) {
1742 //Notify all proxy objects first of adapter state change
Calvin Ona0b91d72016-06-15 17:58:23 -07001743 if (newState == BluetoothAdapter.STATE_BLE_ON ||
1744 newState == BluetoothAdapter.STATE_OFF) {
Nitin Arorad055adb2015-03-02 15:03:51 -08001745 boolean intermediate_off = (prevState == BluetoothAdapter.STATE_TURNING_OFF
1746 && newState == BluetoothAdapter.STATE_BLE_ON);
Zhihai Xu40874a02012-10-08 17:57:03 -07001747
Nitin Arorad055adb2015-03-02 15:03:51 -08001748 if (newState == BluetoothAdapter.STATE_OFF) {
1749 // If Bluetooth is off, send service down event to proxy objects, and unbind
Jeff Sharkey67609c72016-03-05 14:29:13 -07001750 if (DBG) Slog.d(TAG, "Bluetooth is complete turn off");
Pavlin Radoslavove47ec142016-06-01 22:25:18 -07001751 sendBluetoothServiceDownCallback();
1752 unbindAndFinish();
1753 sendBleStateChanged(prevState, newState);
1754 // Don't broadcast as it has already been broadcast before
1755 isStandardBroadcast = false;
Nitin Arorad055adb2015-03-02 15:03:51 -08001756
1757 } else if (!intermediate_off) {
1758 // connect to GattService
Jeff Sharkey67609c72016-03-05 14:29:13 -07001759 if (DBG) Slog.d(TAG, "Bluetooth is in LE only mode");
Nitin Arorad055adb2015-03-02 15:03:51 -08001760 if (mBluetoothGatt != null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001761 if (DBG) Slog.d(TAG, "Calling BluetoothGattServiceUp");
Nitin Arorad055adb2015-03-02 15:03:51 -08001762 onBluetoothGattServiceUp();
1763 } else {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001764 if (DBG) Slog.d(TAG, "Binding Bluetooth GATT service");
Nitin Arorad055adb2015-03-02 15:03:51 -08001765 if (mContext.getPackageManager().hasSystemFeature(
1766 PackageManager.FEATURE_BLUETOOTH_LE)) {
1767 Intent i = new Intent(IBluetoothGatt.class.getName());
1768 doBind(i, mConnection, Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT, UserHandle.CURRENT);
1769 }
1770 }
1771 sendBleStateChanged(prevState, newState);
1772 //Don't broadcase this as std intent
1773 isStandardBroadcast = false;
1774
1775 } else if (intermediate_off){
Jeff Sharkey67609c72016-03-05 14:29:13 -07001776 if (DBG) Slog.d(TAG, "Intermediate off, back to LE only mode");
Nitin Arorad055adb2015-03-02 15:03:51 -08001777 // For LE only mode, broadcast as is
1778 sendBleStateChanged(prevState, newState);
1779 sendBluetoothStateCallback(false); // BT is OFF for general users
1780 // Broadcast as STATE_OFF
1781 newState = BluetoothAdapter.STATE_OFF;
1782 sendBrEdrDownCallback();
Zhihai Xu40874a02012-10-08 17:57:03 -07001783 }
Nitin Arorad055adb2015-03-02 15:03:51 -08001784 } else if (newState == BluetoothAdapter.STATE_ON) {
1785 boolean isUp = (newState==BluetoothAdapter.STATE_ON);
1786 sendBluetoothStateCallback(isUp);
1787 sendBleStateChanged(prevState, newState);
1788
Calvin Ona0b91d72016-06-15 17:58:23 -07001789 } else if (newState == BluetoothAdapter.STATE_BLE_TURNING_ON ||
1790 newState == BluetoothAdapter.STATE_BLE_TURNING_OFF ) {
Nitin Arorad055adb2015-03-02 15:03:51 -08001791 sendBleStateChanged(prevState, newState);
1792 isStandardBroadcast = false;
1793
Calvin Ona0b91d72016-06-15 17:58:23 -07001794 } else if (newState == BluetoothAdapter.STATE_TURNING_ON ||
1795 newState == BluetoothAdapter.STATE_TURNING_OFF) {
Nitin Arorad055adb2015-03-02 15:03:51 -08001796 sendBleStateChanged(prevState, newState);
Zhihai Xu40874a02012-10-08 17:57:03 -07001797 }
1798
Nitin Arorad055adb2015-03-02 15:03:51 -08001799 if (isStandardBroadcast) {
1800 if (prevState == BluetoothAdapter.STATE_BLE_ON) {
1801 // Show prevState of BLE_ON as OFF to standard users
1802 prevState = BluetoothAdapter.STATE_OFF;
1803 }
1804 Intent intent = new Intent(BluetoothAdapter.ACTION_STATE_CHANGED);
1805 intent.putExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE, prevState);
1806 intent.putExtra(BluetoothAdapter.EXTRA_STATE, newState);
1807 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1808 mContext.sendBroadcastAsUser(intent, UserHandle.ALL, BLUETOOTH_PERM);
1809 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001810 }
1811 }
1812
1813 /**
1814 * if on is true, wait for state become ON
1815 * if off is true, wait for state become OFF
1816 * if both on and off are false, wait for state not ON
1817 */
1818 private boolean waitForOnOff(boolean on, boolean off) {
1819 int i = 0;
1820 while (i < 10) {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001821 try {
1822 mBluetoothLock.readLock().lock();
1823 if (mBluetooth == null) break;
1824 if (on) {
1825 if (mBluetooth.getState() == BluetoothAdapter.STATE_ON) return true;
1826 } else if (off) {
1827 if (mBluetooth.getState() == BluetoothAdapter.STATE_OFF) return true;
1828 } else {
1829 if (mBluetooth.getState() != BluetoothAdapter.STATE_ON) return true;
Zhihai Xu40874a02012-10-08 17:57:03 -07001830 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001831 } catch (RemoteException e) {
1832 Slog.e(TAG, "getState()", e);
1833 break;
1834 } finally {
1835 mBluetoothLock.readLock().unlock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001836 }
1837 if (on || off) {
1838 SystemClock.sleep(300);
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07001839 } else {
Zhihai Xu40874a02012-10-08 17:57:03 -07001840 SystemClock.sleep(50);
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07001841 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001842 i++;
1843 }
Jeff Sharkey67609c72016-03-05 14:29:13 -07001844 Slog.e(TAG,"waitForOnOff time out");
Zhihai Xu40874a02012-10-08 17:57:03 -07001845 return false;
1846 }
Zhihai Xu681ae7f2012-11-12 15:14:18 -08001847
Zhihai Xu401202b2012-12-03 11:36:21 -08001848 private void sendDisableMsg() {
1849 mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_DISABLE));
1850 }
1851
1852 private void sendEnableMsg(boolean quietMode) {
1853 mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_ENABLE,
1854 quietMode ? 1 : 0, 0));
1855 }
1856
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001857 private void recoverBluetoothServiceFromError() {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001858 Slog.e(TAG,"recoverBluetoothServiceFromError");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001859 try {
1860 mBluetoothLock.readLock().lock();
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001861 if (mBluetooth != null) {
1862 //Unregister callback object
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001863 mBluetooth.unregisterCallback(mBluetoothCallback);
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001864 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001865 } catch (RemoteException re) {
1866 Slog.e(TAG, "Unable to unregister", re);
1867 } finally {
1868 mBluetoothLock.readLock().unlock();
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001869 }
1870
1871 SystemClock.sleep(500);
1872
1873 // disable
1874 handleDisable();
1875
1876 waitForOnOff(false, true);
1877
1878 sendBluetoothServiceDownCallback();
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001879
Pavlin Radoslavove957a8a2016-05-24 15:28:41 -07001880 try {
1881 mBluetoothLock.writeLock().lock();
1882 if (mBluetooth != null) {
1883 mBluetooth = null;
1884 // Unbind
1885 mContext.unbindService(mConnection);
1886 }
1887 mBluetoothGatt = null;
1888 } finally {
1889 mBluetoothLock.writeLock().unlock();
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001890 }
1891
1892 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
1893 mState = BluetoothAdapter.STATE_OFF;
1894
1895 mEnable = false;
1896
1897 if (mErrorRecoveryRetryCounter++ < MAX_ERROR_RESTART_RETRIES) {
1898 // Send a Bluetooth Restart message to reenable bluetooth
1899 Message restartMsg = mHandler.obtainMessage(
1900 MESSAGE_RESTART_BLUETOOTH_SERVICE);
1901 mHandler.sendMessageDelayed(restartMsg, ERROR_RESTART_TIME_MS);
1902 } else {
1903 // todo: notify user to power down and power up phone to make bluetooth work.
1904 }
1905 }
Mike Lockwood726d4de2014-10-28 14:06:28 -07001906
1907 @Override
Pavlin Radoslavov6e8faff2016-02-23 11:54:37 -08001908 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1909 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DUMP, TAG);
1910 String errorMsg = null;
1911 if (mBluetoothBinder == null) {
1912 errorMsg = "Bluetooth Service not connected";
1913 } else {
1914 try {
1915 mBluetoothBinder.dump(fd, args);
1916 } catch (RemoteException re) {
1917 errorMsg = "RemoteException while calling Bluetooth Service";
1918 }
Mike Lockwood726d4de2014-10-28 14:06:28 -07001919 }
Pavlin Radoslavov6e8faff2016-02-23 11:54:37 -08001920 if (errorMsg != null) {
1921 // Silently return if we are extracting metrics in Protobuf format
1922 if ((args.length > 0) && args[0].startsWith("--proto"))
1923 return;
1924 writer.println(errorMsg);
1925 }
Mike Lockwood726d4de2014-10-28 14:06:28 -07001926 }
fredc0f420372012-04-12 00:02:00 -07001927}