blob: 2a6f9d2b85696341b8525dd852669128effa9f02 [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;
Shijian Li5e7fc7c2017-01-11 17:32:12 +000031import android.content.ActivityNotFoundException;
fredc0f420372012-04-12 00:02:00 -070032import android.content.BroadcastReceiver;
33import android.content.ComponentName;
34import android.content.ContentResolver;
35import android.content.Context;
36import android.content.Intent;
37import android.content.IntentFilter;
38import android.content.ServiceConnection;
Svetoslav Ganovb1e2da72016-06-29 17:31:44 -070039import android.content.pm.ApplicationInfo;
Matthew Xie32ab77b2013-05-08 19:26:57 -070040import android.content.pm.PackageManager;
Benjamin Franze8b98922014-11-12 15:57:54 +000041import android.content.pm.UserInfo;
Wei Wange4a744b2015-06-11 17:50:29 -070042import android.database.ContentObserver;
Zhihai Xu40874a02012-10-08 17:57:03 -070043import android.os.Binder;
Svetoslav Ganovb1e2da72016-06-29 17:31:44 -070044import android.os.Build;
fredc0f420372012-04-12 00:02:00 -070045import android.os.Handler;
fredc0f420372012-04-12 00:02:00 -070046import android.os.IBinder;
Zhihai Xu40874a02012-10-08 17:57:03 -070047import android.os.Looper;
fredc0f420372012-04-12 00:02:00 -070048import android.os.Message;
Zhihai Xu40874a02012-10-08 17:57:03 -070049import android.os.Process;
fredcd6883532012-04-25 17:46:13 -070050import android.os.RemoteCallbackList;
fredc0f420372012-04-12 00:02:00 -070051import android.os.RemoteException;
Zhihai Xu40874a02012-10-08 17:57:03 -070052import android.os.SystemClock;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070053import android.os.UserHandle;
Benjamin Franze8b98922014-11-12 15:57:54 +000054import android.os.UserManager;
fredc0f420372012-04-12 00:02:00 -070055import android.provider.Settings;
Wei Wang67d84162015-04-26 17:04:29 -070056import android.provider.Settings.SettingNotFoundException;
Jeff Sharkey67609c72016-03-05 14:29:13 -070057import android.util.Slog;
Mike Lockwood726d4de2014-10-28 14:06:28 -070058
59import java.io.FileDescriptor;
60import java.io.PrintWriter;
Marie Janssen6689f332016-11-09 12:01:24 -080061import java.util.concurrent.ConcurrentHashMap;
Marie Janssena50cc712016-12-28 14:13:21 -080062import java.util.concurrent.locks.ReentrantReadWriteLock;
Benjamin Franze8b98922014-11-12 15:57:54 +000063import java.util.HashMap;
Marie Janssena50cc712016-12-28 14:13:21 -080064import java.util.LinkedList;
Benjamin Franze8b98922014-11-12 15:57:54 +000065import java.util.Map;
Miao Chou658bf2f2015-06-26 17:14:35 -070066
Marie Janssena50cc712016-12-28 14:13:21 -080067
fredc0f420372012-04-12 00:02:00 -070068class BluetoothManagerService extends IBluetoothManager.Stub {
69 private static final String TAG = "BluetoothManagerService";
Pavlin Radoslavov41401112016-06-27 15:25:18 -070070 private static final boolean DBG = true;
fredc0f420372012-04-12 00:02:00 -070071
fredc0f420372012-04-12 00:02:00 -070072 private static final String BLUETOOTH_ADMIN_PERM = android.Manifest.permission.BLUETOOTH_ADMIN;
73 private static final String BLUETOOTH_PERM = android.Manifest.permission.BLUETOOTH;
fredc0f420372012-04-12 00:02:00 -070074 private static final String ACTION_SERVICE_STATE_CHANGED="com.android.bluetooth.btservice.action.STATE_CHANGED";
75 private static final String EXTRA_ACTION="action";
Zhihai Xud31c3222012-10-31 16:08:57 -070076 private static final String SECURE_SETTINGS_BLUETOOTH_ADDR_VALID="bluetooth_addr_valid";
fredc0f420372012-04-12 00:02:00 -070077 private static final String SECURE_SETTINGS_BLUETOOTH_ADDRESS="bluetooth_address";
78 private static final String SECURE_SETTINGS_BLUETOOTH_NAME="bluetooth_name";
fredc0f420372012-04-12 00:02:00 -070079 private static final int TIMEOUT_BIND_MS = 3000; //Maximum msec to wait for a bind
80 private static final int TIMEOUT_SAVE_MS = 500; //Maximum msec to wait for a save
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +053081 //Maximum msec to wait for service restart
82 private static final int SERVICE_RESTART_TIME_MS = 200;
Zhihai Xudd9d17d2013-01-08 17:05:58 -080083 //Maximum msec to wait for restart due to error
84 private static final int ERROR_RESTART_TIME_MS = 3000;
Zhihai Xu40874a02012-10-08 17:57:03 -070085 //Maximum msec to delay MESSAGE_USER_SWITCHED
86 private static final int USER_SWITCHED_TIME_MS = 200;
Benjamin Franze8b98922014-11-12 15:57:54 +000087 // Delay for the addProxy function in msec
88 private static final int ADD_PROXY_DELAY_MS = 100;
fredc0f420372012-04-12 00:02:00 -070089
90 private static final int MESSAGE_ENABLE = 1;
91 private static final int MESSAGE_DISABLE = 2;
fredc649fe492012-04-19 01:07:18 -070092 private static final int MESSAGE_REGISTER_ADAPTER = 20;
93 private static final int MESSAGE_UNREGISTER_ADAPTER = 21;
94 private static final int MESSAGE_REGISTER_STATE_CHANGE_CALLBACK = 30;
95 private static final int MESSAGE_UNREGISTER_STATE_CHANGE_CALLBACK = 31;
96 private static final int MESSAGE_BLUETOOTH_SERVICE_CONNECTED = 40;
97 private static final int MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED = 41;
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +053098 private static final int MESSAGE_RESTART_BLUETOOTH_SERVICE = 42;
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -070099 private static final int MESSAGE_BLUETOOTH_STATE_CHANGE = 60;
100 private static final int MESSAGE_TIMEOUT_BIND = 100;
101 private static final int MESSAGE_TIMEOUT_UNBIND = 101;
Ajay Panicker4bb48302016-03-31 14:14:27 -0700102 private static final int MESSAGE_GET_NAME_AND_ADDRESS = 200;
Zhihai Xu40874a02012-10-08 17:57:03 -0700103 private static final int MESSAGE_USER_SWITCHED = 300;
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -0700104 private static final int MESSAGE_USER_UNLOCKED = 301;
Benjamin Franze8b98922014-11-12 15:57:54 +0000105 private static final int MESSAGE_ADD_PROXY_DELAYED = 400;
106 private static final int MESSAGE_BIND_PROFILE_SERVICE = 401;
Marie Janssenffcf88f2016-12-13 10:51:02 -0800107
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -0700108 private static final int MAX_SAVE_RETRIES = 3;
109 private static final int MAX_ERROR_RESTART_RETRIES = 6;
Zhihai Xudd9d17d2013-01-08 17:05:58 -0800110
Zhihai Xu401202b2012-12-03 11:36:21 -0800111 // Bluetooth persisted setting is off
112 private static final int BLUETOOTH_OFF=0;
113 // Bluetooth persisted setting is on
114 // and Airplane mode won't affect Bluetooth state at start up
115 private static final int BLUETOOTH_ON_BLUETOOTH=1;
116 // Bluetooth persisted setting is on
117 // but Airplane mode will affect Bluetooth state at start up
118 // and Airplane mode will have higher priority.
119 private static final int BLUETOOTH_ON_AIRPLANE=2;
fredc0f420372012-04-12 00:02:00 -0700120
Matthew Xieddf7e472013-03-01 18:41:02 -0800121 private static final int SERVICE_IBLUETOOTH = 1;
122 private static final int SERVICE_IBLUETOOTHGATT = 2;
123
fredc0f420372012-04-12 00:02:00 -0700124 private final Context mContext;
Matthew Xiecdce0b92012-07-12 19:06:15 -0700125
126 // Locks are not provided for mName and mAddress.
127 // They are accessed in handler or broadcast receiver, same thread context.
fredc0f420372012-04-12 00:02:00 -0700128 private String mAddress;
129 private String mName;
Matthew Xie6fde3092012-07-11 17:10:07 -0700130 private final ContentResolver mContentResolver;
131 private final RemoteCallbackList<IBluetoothManagerCallback> mCallbacks;
132 private final RemoteCallbackList<IBluetoothStateChangeCallback> mStateChangeCallbacks;
Marie Janssen9db28eb2016-01-12 16:05:15 -0800133 private IBinder mBluetoothBinder;
fredc649fe492012-04-19 01:07:18 -0700134 private IBluetooth mBluetooth;
Matthew Xieddf7e472013-03-01 18:41:02 -0800135 private IBluetoothGatt mBluetoothGatt;
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700136 private final ReentrantReadWriteLock mBluetoothLock =
137 new ReentrantReadWriteLock();
fredc649fe492012-04-19 01:07:18 -0700138 private boolean mBinding;
139 private boolean mUnbinding;
Marie Janssena50cc712016-12-28 14:13:21 -0800140
Zhihai Xu401202b2012-12-03 11:36:21 -0800141 // used inside handler thread
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700142 private boolean mQuietEnable = false;
Marie Janssena50cc712016-12-28 14:13:21 -0800143 private boolean mEnable;
144
145 /**
146 * Used for tracking apps that enabled / disabled Bluetooth.
147 */
148 private class ActiveLog {
149 private String mPackageName;
150 private boolean mEnable;
151 private long mTimestamp;
152
153 public ActiveLog(String packageName, boolean enable, long timestamp) {
154 mPackageName = packageName;
155 mEnable = enable;
156 mTimestamp = timestamp;
157 }
158
159 public long getTime() {
160 return mTimestamp;
161 }
162
163 public String toString() {
164 return android.text.format.DateFormat.format("MM-dd hh:mm:ss ", mTimestamp) +
165 (mEnable ? " Enabled " : " Disabled ") + " by " + mPackageName;
166 }
167
168 }
169
170 private LinkedList<ActiveLog> mActiveLogs;
171
172 // configuration from external IBinder call which is used to
Zhihai Xu401202b2012-12-03 11:36:21 -0800173 // synchronize with broadcast receiver.
174 private boolean mQuietEnableExternal;
Zhihai Xu401202b2012-12-03 11:36:21 -0800175 private boolean mEnableExternal;
Marie Janssena50cc712016-12-28 14:13:21 -0800176
177 // Map of apps registered to keep BLE scanning on.
178 private Map<IBinder, ClientDeathRecipient> mBleApps = new ConcurrentHashMap<IBinder, ClientDeathRecipient>();
179
Zhihai Xu40874a02012-10-08 17:57:03 -0700180 private int mState;
Zhihai Xu40874a02012-10-08 17:57:03 -0700181 private final BluetoothHandler mHandler;
Zhihai Xudd9d17d2013-01-08 17:05:58 -0800182 private int mErrorRecoveryRetryCounter;
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200183 private final int mSystemUiUid;
fredc0f420372012-04-12 00:02:00 -0700184
Benjamin Franze8b98922014-11-12 15:57:54 +0000185 // Save a ProfileServiceConnections object for each of the bound
186 // bluetooth profile services
187 private final Map <Integer, ProfileServiceConnections> mProfileServices =
188 new HashMap <Integer, ProfileServiceConnections>();
189
Svetoslav Ganovb1e2da72016-06-29 17:31:44 -0700190 private final boolean mPermissionReviewRequired;
191
fredc649fe492012-04-19 01:07:18 -0700192 private void registerForAirplaneMode(IntentFilter filter) {
193 final ContentResolver resolver = mContext.getContentResolver();
Christopher Tatec09cdce2012-09-10 16:50:14 -0700194 final String airplaneModeRadios = Settings.Global.getString(resolver,
195 Settings.Global.AIRPLANE_MODE_RADIOS);
196 final String toggleableRadios = Settings.Global.getString(resolver,
197 Settings.Global.AIRPLANE_MODE_TOGGLEABLE_RADIOS);
fredc649fe492012-04-19 01:07:18 -0700198 boolean mIsAirplaneSensitive = airplaneModeRadios == null ? true :
Christopher Tatec09cdce2012-09-10 16:50:14 -0700199 airplaneModeRadios.contains(Settings.Global.RADIO_BLUETOOTH);
fredc649fe492012-04-19 01:07:18 -0700200 if (mIsAirplaneSensitive) {
201 filter.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED);
202 }
203 }
204
Marie Janssena50cc712016-12-28 14:13:21 -0800205 private final IBluetoothCallback mBluetoothCallback = new IBluetoothCallback.Stub() {
fredcbf072a72012-05-09 16:52:50 -0700206 @Override
207 public void onBluetoothStateChange(int prevState, int newState) throws RemoteException {
208 Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_STATE_CHANGE,prevState,newState);
209 mHandler.sendMessage(msg);
210 }
211 };
212
213 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
fredc0f420372012-04-12 00:02:00 -0700214 @Override
215 public void onReceive(Context context, Intent intent) {
216 String action = intent.getAction();
fredcbf072a72012-05-09 16:52:50 -0700217 if (BluetoothAdapter.ACTION_LOCAL_NAME_CHANGED.equals(action)) {
fredc0f420372012-04-12 00:02:00 -0700218 String newName = intent.getStringExtra(BluetoothAdapter.EXTRA_LOCAL_NAME);
Jeff Sharkey67609c72016-03-05 14:29:13 -0700219 if (DBG) Slog.d(TAG, "Bluetooth Adapter name changed to " + newName);
fredc0f420372012-04-12 00:02:00 -0700220 if (newName != null) {
221 storeNameAndAddress(newName, null);
222 }
fredc649fe492012-04-19 01:07:18 -0700223 } else if (Intent.ACTION_AIRPLANE_MODE_CHANGED.equals(action)) {
Zhihai Xu401202b2012-12-03 11:36:21 -0800224 synchronized(mReceiver) {
225 if (isBluetoothPersistedStateOn()) {
226 if (isAirplaneModeOn()) {
227 persistBluetoothSetting(BLUETOOTH_ON_AIRPLANE);
228 } else {
229 persistBluetoothSetting(BLUETOOTH_ON_BLUETOOTH);
230 }
231 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800232
233 int st = BluetoothAdapter.STATE_OFF;
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700234 try {
235 mBluetoothLock.readLock().lock();
236 if (mBluetooth != null) {
Nitin Arorad055adb2015-03-02 15:03:51 -0800237 st = mBluetooth.getState();
Nitin Arorad055adb2015-03-02 15:03:51 -0800238 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700239 } catch (RemoteException e) {
240 Slog.e(TAG, "Unable to call getState", e);
241 } finally {
242 mBluetoothLock.readLock().unlock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800243 }
Marie Janssenffcf88f2016-12-13 10:51:02 -0800244 Slog.d(TAG, "State " + BluetoothAdapter.nameForState(st));
Nitin Arorad055adb2015-03-02 15:03:51 -0800245
Zhihai Xu401202b2012-12-03 11:36:21 -0800246 if (isAirplaneModeOn()) {
Nitin Arorad055adb2015-03-02 15:03:51 -0800247 // Clear registered LE apps to force shut-off
Marie Janssen6689f332016-11-09 12:01:24 -0800248 clearBleApps();
Nitin Arorad055adb2015-03-02 15:03:51 -0800249 if (st == BluetoothAdapter.STATE_BLE_ON) {
250 //if state is BLE_ON make sure you trigger disableBLE part
251 try {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700252 mBluetoothLock.readLock().lock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800253 if (mBluetooth != null) {
254 mBluetooth.onBrEdrDown();
Marie Janssena80d7452016-10-25 10:47:51 -0700255 mEnable = false;
Nitin Arorad055adb2015-03-02 15:03:51 -0800256 mEnableExternal = false;
257 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700258 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700259 Slog.e(TAG,"Unable to call onBrEdrDown", e);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700260 } finally {
Pavlin Radoslavov7ee53be2016-06-09 12:58:07 -0700261 mBluetoothLock.readLock().unlock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800262 }
263 } else if (st == BluetoothAdapter.STATE_ON){
264 // disable without persisting the setting
Jeff Sharkey67609c72016-03-05 14:29:13 -0700265 Slog.d(TAG, "Calling disable");
Marie Janssena50cc712016-12-28 14:13:21 -0800266 sendDisableMsg("airplane mode");
Nitin Arorad055adb2015-03-02 15:03:51 -0800267 }
Zhihai Xu401202b2012-12-03 11:36:21 -0800268 } else if (mEnableExternal) {
269 // enable without persisting the setting
Jeff Sharkey67609c72016-03-05 14:29:13 -0700270 Slog.d(TAG, "Calling enable");
Marie Janssena50cc712016-12-28 14:13:21 -0800271 sendEnableMsg(mQuietEnableExternal, "airplane mode");
Zhihai Xu401202b2012-12-03 11:36:21 -0800272 }
fredc649fe492012-04-19 01:07:18 -0700273 }
fredc0f420372012-04-12 00:02:00 -0700274 }
275 }
276 };
277
278 BluetoothManagerService(Context context) {
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700279 mHandler = new BluetoothHandler(IoThread.get().getLooper());
Zhihai Xu40874a02012-10-08 17:57:03 -0700280
fredc0f420372012-04-12 00:02:00 -0700281 mContext = context;
Svetoslav Ganovb1e2da72016-06-29 17:31:44 -0700282
283 mPermissionReviewRequired = Build.PERMISSIONS_REVIEW_REQUIRED
284 || context.getResources().getBoolean(
285 com.android.internal.R.bool.config_permissionReviewRequired);
286
Marie Janssena50cc712016-12-28 14:13:21 -0800287 mActiveLogs = new LinkedList<ActiveLog>();
fredc0f420372012-04-12 00:02:00 -0700288 mBluetooth = null;
Marie Janssen9db28eb2016-01-12 16:05:15 -0800289 mBluetoothBinder = null;
Nitin Arorad055adb2015-03-02 15:03:51 -0800290 mBluetoothGatt = null;
fredc0f420372012-04-12 00:02:00 -0700291 mBinding = false;
292 mUnbinding = false;
Zhihai Xu40874a02012-10-08 17:57:03 -0700293 mEnable = false;
294 mState = BluetoothAdapter.STATE_OFF;
Zhihai Xu401202b2012-12-03 11:36:21 -0800295 mQuietEnableExternal = false;
296 mEnableExternal = false;
fredc0f420372012-04-12 00:02:00 -0700297 mAddress = null;
298 mName = null;
Zhihai Xudd9d17d2013-01-08 17:05:58 -0800299 mErrorRecoveryRetryCounter = 0;
fredc0f420372012-04-12 00:02:00 -0700300 mContentResolver = context.getContentResolver();
Wei Wange4a744b2015-06-11 17:50:29 -0700301 // Observe BLE scan only mode settings change.
302 registerForBleScanModeChange();
fredcd6883532012-04-25 17:46:13 -0700303 mCallbacks = new RemoteCallbackList<IBluetoothManagerCallback>();
304 mStateChangeCallbacks = new RemoteCallbackList<IBluetoothStateChangeCallback>();
Miao Chou658bf2f2015-06-26 17:14:35 -0700305 IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_LOCAL_NAME_CHANGED);
Matthew Xie6fde3092012-07-11 17:10:07 -0700306 registerForAirplaneMode(filter);
Dianne Hackbornd83a0962014-05-02 16:28:33 -0700307 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
Matthew Xie6fde3092012-07-11 17:10:07 -0700308 mContext.registerReceiver(mReceiver, filter);
fredc0f420372012-04-12 00:02:00 -0700309 loadStoredNameAndAddress();
Zhihai Xu401202b2012-12-03 11:36:21 -0800310 if (isBluetoothPersistedStateOn()) {
Marie Janssen9fa24912016-10-18 10:04:24 -0700311 if (DBG) Slog.d(TAG, "Startup: Bluetooth persisted state is ON.");
Zhihai Xu401202b2012-12-03 11:36:21 -0800312 mEnableExternal = true;
fredc0f420372012-04-12 00:02:00 -0700313 }
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200314
Marie Janssena50cc712016-12-28 14:13:21 -0800315 int systemUiUid = -1;
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200316 try {
Marie Janssena50cc712016-12-28 14:13:21 -0800317 systemUiUid = mContext.getPackageManager().getPackageUidAsUser("com.android.systemui",
Jeff Sharkeyc5967e92016-01-07 18:50:29 -0700318 PackageManager.MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM);
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200319 } catch (PackageManager.NameNotFoundException e) {
Joe LaPennaacddf2b2015-09-04 12:52:42 -0700320 // Some platforms, such as wearables do not have a system ui.
Jeff Sharkey67609c72016-03-05 14:29:13 -0700321 Slog.w(TAG, "Unable to resolve SystemUI's UID.", e);
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200322 }
Marie Janssena50cc712016-12-28 14:13:21 -0800323 mSystemUiUid = systemUiUid;
fredc0f420372012-04-12 00:02:00 -0700324 }
325
fredc649fe492012-04-19 01:07:18 -0700326 /**
327 * Returns true if airplane mode is currently on
328 */
329 private final boolean isAirplaneModeOn() {
Christopher Tatec09cdce2012-09-10 16:50:14 -0700330 return Settings.Global.getInt(mContext.getContentResolver(),
331 Settings.Global.AIRPLANE_MODE_ON, 0) == 1;
fredc649fe492012-04-19 01:07:18 -0700332 }
333
334 /**
335 * Returns true if the Bluetooth saved state is "on"
336 */
337 private final boolean isBluetoothPersistedStateOn() {
Marie Janssen9fa24912016-10-18 10:04:24 -0700338 int state = Settings.Global.getInt(mContentResolver,
339 Settings.Global.BLUETOOTH_ON, -1);
340 if (DBG) Slog.d(TAG, "Bluetooth persisted state: " + state);
341 return state != BLUETOOTH_OFF;
Zhihai Xu401202b2012-12-03 11:36:21 -0800342 }
343
344 /**
345 * Returns true if the Bluetooth saved state is BLUETOOTH_ON_BLUETOOTH
346 */
347 private final boolean isBluetoothPersistedStateOnBluetooth() {
348 return Settings.Global.getInt(mContentResolver,
Andre Eisenbach8c184312016-09-06 18:03:10 -0700349 Settings.Global.BLUETOOTH_ON, BLUETOOTH_ON_BLUETOOTH) == BLUETOOTH_ON_BLUETOOTH;
fredc649fe492012-04-19 01:07:18 -0700350 }
351
352 /**
353 * Save the Bluetooth on/off state
fredc649fe492012-04-19 01:07:18 -0700354 */
Zhihai Xu401202b2012-12-03 11:36:21 -0800355 private void persistBluetoothSetting(int value) {
Marie Janssen9fa24912016-10-18 10:04:24 -0700356 if (DBG) Slog.d(TAG, "Persisting Bluetooth Setting: " + value);
Marie Janssenfa630682016-12-15 13:51:30 -0800357 // waive WRITE_SECURE_SETTINGS permission check
358 long callingIdentity = Binder.clearCallingIdentity();
Jeff Brownbf6f6f92012-09-25 15:03:20 -0700359 Settings.Global.putInt(mContext.getContentResolver(),
360 Settings.Global.BLUETOOTH_ON,
Zhihai Xu401202b2012-12-03 11:36:21 -0800361 value);
Marie Janssenfa630682016-12-15 13:51:30 -0800362 Binder.restoreCallingIdentity(callingIdentity);
fredc649fe492012-04-19 01:07:18 -0700363 }
364
365 /**
366 * Returns true if the Bluetooth Adapter's name and address is
367 * locally cached
368 * @return
369 */
fredc0f420372012-04-12 00:02:00 -0700370 private boolean isNameAndAddressSet() {
371 return mName !=null && mAddress!= null && mName.length()>0 && mAddress.length()>0;
372 }
373
fredc649fe492012-04-19 01:07:18 -0700374 /**
375 * Retrieve the Bluetooth Adapter's name and address and save it in
376 * in the local cache
377 */
fredc0f420372012-04-12 00:02:00 -0700378 private void loadStoredNameAndAddress() {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700379 if (DBG) Slog.d(TAG, "Loading stored name and address");
Zhihai Xud31c3222012-10-31 16:08:57 -0700380 if (mContext.getResources().getBoolean
381 (com.android.internal.R.bool.config_bluetooth_address_validation) &&
382 Settings.Secure.getInt(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDR_VALID, 0) == 0) {
383 // if the valid flag is not set, don't load the address and name
Jeff Sharkey67609c72016-03-05 14:29:13 -0700384 if (DBG) Slog.d(TAG, "invalid bluetooth name and address stored");
Zhihai Xud31c3222012-10-31 16:08:57 -0700385 return;
386 }
fredc0f420372012-04-12 00:02:00 -0700387 mName = Settings.Secure.getString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_NAME);
388 mAddress = Settings.Secure.getString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDRESS);
Jeff Sharkey67609c72016-03-05 14:29:13 -0700389 if (DBG) Slog.d(TAG, "Stored bluetooth Name=" + mName + ",Address=" + mAddress);
fredc0f420372012-04-12 00:02:00 -0700390 }
391
fredc649fe492012-04-19 01:07:18 -0700392 /**
393 * Save the Bluetooth name and address in the persistent store.
394 * Only non-null values will be saved.
395 * @param name
396 * @param address
397 */
fredc0f420372012-04-12 00:02:00 -0700398 private void storeNameAndAddress(String name, String address) {
399 if (name != null) {
400 Settings.Secure.putString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_NAME, name);
fredc0f420372012-04-12 00:02:00 -0700401 mName = name;
Jeff Sharkey67609c72016-03-05 14:29:13 -0700402 if (DBG) Slog.d(TAG,"Stored Bluetooth name: " +
fredc649fe492012-04-19 01:07:18 -0700403 Settings.Secure.getString(mContentResolver,SECURE_SETTINGS_BLUETOOTH_NAME));
fredc0f420372012-04-12 00:02:00 -0700404 }
405
406 if (address != null) {
407 Settings.Secure.putString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDRESS, address);
fredc0f420372012-04-12 00:02:00 -0700408 mAddress=address;
Jeff Sharkey67609c72016-03-05 14:29:13 -0700409 if (DBG) Slog.d(TAG,"Stored Bluetoothaddress: " +
fredc649fe492012-04-19 01:07:18 -0700410 Settings.Secure.getString(mContentResolver,SECURE_SETTINGS_BLUETOOTH_ADDRESS));
fredc0f420372012-04-12 00:02:00 -0700411 }
Zhihai Xud31c3222012-10-31 16:08:57 -0700412
413 if ((name != null) && (address != null)) {
414 Settings.Secure.putInt(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDR_VALID, 1);
415 }
fredc0f420372012-04-12 00:02:00 -0700416 }
417
418 public IBluetooth registerAdapter(IBluetoothManagerCallback callback){
Natalie Silvanovich55db6462014-05-01 16:12:23 -0700419 if (callback == null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700420 Slog.w(TAG, "Callback is null in registerAdapter");
Natalie Silvanovich55db6462014-05-01 16:12:23 -0700421 return null;
422 }
fredc0f420372012-04-12 00:02:00 -0700423 Message msg = mHandler.obtainMessage(MESSAGE_REGISTER_ADAPTER);
424 msg.obj = callback;
425 mHandler.sendMessage(msg);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700426
427 return mBluetooth;
fredc0f420372012-04-12 00:02:00 -0700428 }
429
430 public void unregisterAdapter(IBluetoothManagerCallback callback) {
Natalie Silvanovich55db6462014-05-01 16:12:23 -0700431 if (callback == null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700432 Slog.w(TAG, "Callback is null in unregisterAdapter");
Natalie Silvanovich55db6462014-05-01 16:12:23 -0700433 return;
434 }
fredc0f420372012-04-12 00:02:00 -0700435 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
436 "Need BLUETOOTH permission");
437 Message msg = mHandler.obtainMessage(MESSAGE_UNREGISTER_ADAPTER);
438 msg.obj = callback;
439 mHandler.sendMessage(msg);
440 }
441
442 public void registerStateChangeCallback(IBluetoothStateChangeCallback callback) {
443 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
444 "Need BLUETOOTH permission");
Marie Janssenffcf88f2016-12-13 10:51:02 -0800445 if (callback == null) {
446 Slog.w(TAG, "registerStateChangeCallback: Callback is null!");
447 return;
448 }
fredc0f420372012-04-12 00:02:00 -0700449 Message msg = mHandler.obtainMessage(MESSAGE_REGISTER_STATE_CHANGE_CALLBACK);
450 msg.obj = callback;
451 mHandler.sendMessage(msg);
452 }
453
454 public void unregisterStateChangeCallback(IBluetoothStateChangeCallback callback) {
455 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
456 "Need BLUETOOTH permission");
Marie Janssenffcf88f2016-12-13 10:51:02 -0800457 if (callback == null) {
458 Slog.w(TAG, "unregisterStateChangeCallback: Callback is null!");
459 return;
460 }
fredc0f420372012-04-12 00:02:00 -0700461 Message msg = mHandler.obtainMessage(MESSAGE_UNREGISTER_STATE_CHANGE_CALLBACK);
462 msg.obj = callback;
463 mHandler.sendMessage(msg);
464 }
465
466 public boolean isEnabled() {
Zhihai Xu6eb76522012-11-29 15:41:04 -0800467 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
468 (!checkIfCallerIsForegroundUser())) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700469 Slog.w(TAG,"isEnabled(): not allowed for non-active and non system user");
Zhihai Xu40874a02012-10-08 17:57:03 -0700470 return false;
471 }
472
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700473 try {
474 mBluetoothLock.readLock().lock();
475 if (mBluetooth != null) return mBluetooth.isEnabled();
476 } catch (RemoteException e) {
477 Slog.e(TAG, "isEnabled()", e);
478 } finally {
479 mBluetoothLock.readLock().unlock();
fredc0f420372012-04-12 00:02:00 -0700480 }
481 return false;
482 }
483
Christine Hallstrom995c90a2016-05-25 15:49:08 -0700484 public int getState() {
485 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
486 (!checkIfCallerIsForegroundUser())) {
Marie Janssenffcf88f2016-12-13 10:51:02 -0800487 Slog.w(TAG, "getState(): report OFF for non-active and non system user");
Christine Hallstrom995c90a2016-05-25 15:49:08 -0700488 return BluetoothAdapter.STATE_OFF;
489 }
490
491 try {
492 mBluetoothLock.readLock().lock();
493 if (mBluetooth != null) return mBluetooth.getState();
494 } catch (RemoteException e) {
495 Slog.e(TAG, "getState()", e);
496 } finally {
497 mBluetoothLock.readLock().unlock();
498 }
499 return BluetoothAdapter.STATE_OFF;
500 }
501
Nitin Arorad055adb2015-03-02 15:03:51 -0800502 class ClientDeathRecipient implements IBinder.DeathRecipient {
Marie Janssena50cc712016-12-28 14:13:21 -0800503 private String mPackageName;
504
505 public ClientDeathRecipient(String packageName) {
506 mPackageName = packageName;
507 }
508
Nitin Arorad055adb2015-03-02 15:03:51 -0800509 public void binderDied() {
Marie Janssena50cc712016-12-28 14:13:21 -0800510 if (DBG) Slog.d(TAG, "Binder is dead - unregister " + mPackageName);
Marie Janssen6689f332016-11-09 12:01:24 -0800511 if (isBleAppPresent()) {
512 // Nothing to do, another app is here.
513 return;
514 }
515 if (DBG) Slog.d(TAG, "Disabling LE only mode after application crash");
516 try {
517 mBluetoothLock.readLock().lock();
518 if (mBluetooth != null &&
519 mBluetooth.getState() == BluetoothAdapter.STATE_BLE_ON) {
520 mEnable = false;
521 mBluetooth.onBrEdrDown();
Nitin Arorad055adb2015-03-02 15:03:51 -0800522 }
Marie Janssen6689f332016-11-09 12:01:24 -0800523 } catch (RemoteException e) {
524 Slog.e(TAG,"Unable to call onBrEdrDown", e);
525 } finally {
526 mBluetoothLock.readLock().unlock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800527 }
528 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800529
Marie Janssena50cc712016-12-28 14:13:21 -0800530 public String getPackageName() {
531 return mPackageName;
532 }
533 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800534
Wei Wang67d84162015-04-26 17:04:29 -0700535 @Override
536 public boolean isBleScanAlwaysAvailable() {
Marie Janssena80d7452016-10-25 10:47:51 -0700537 if (isAirplaneModeOn() && !mEnable) {
538 return false;
539 }
Wei Wang67d84162015-04-26 17:04:29 -0700540 try {
541 return (Settings.Global.getInt(mContentResolver,
542 Settings.Global.BLE_SCAN_ALWAYS_AVAILABLE)) != 0;
543 } catch (SettingNotFoundException e) {
544 }
545 return false;
546 }
547
Wei Wange4a744b2015-06-11 17:50:29 -0700548 // Monitor change of BLE scan only mode settings.
549 private void registerForBleScanModeChange() {
550 ContentObserver contentObserver = new ContentObserver(null) {
551 @Override
552 public void onChange(boolean selfChange) {
Marie Janssen6689f332016-11-09 12:01:24 -0800553 if (isBleScanAlwaysAvailable()) {
554 // Nothing to do
555 return;
556 }
557 // BLE scan is not available.
558 disableBleScanMode();
559 clearBleApps();
560 try {
561 mBluetoothLock.readLock().lock();
562 if (mBluetooth != null) mBluetooth.onBrEdrDown();
563 } catch (RemoteException e) {
564 Slog.e(TAG, "error when disabling bluetooth", e);
565 } finally {
566 mBluetoothLock.readLock().unlock();
Wei Wange4a744b2015-06-11 17:50:29 -0700567 }
568 }
569 };
570
571 mContentResolver.registerContentObserver(
572 Settings.Global.getUriFor(Settings.Global.BLE_SCAN_ALWAYS_AVAILABLE),
573 false, contentObserver);
574 }
575
576 // Disable ble scan only mode.
577 private void disableBleScanMode() {
578 try {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700579 mBluetoothLock.writeLock().lock();
Wei Wange4a744b2015-06-11 17:50:29 -0700580 if (mBluetooth != null && (mBluetooth.getState() != BluetoothAdapter.STATE_ON)) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700581 if (DBG) Slog.d(TAG, "Reseting the mEnable flag for clean disable");
Wei Wange4a744b2015-06-11 17:50:29 -0700582 mEnable = false;
583 }
584 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700585 Slog.e(TAG, "getState()", e);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700586 } finally {
587 mBluetoothLock.writeLock().unlock();
Wei Wange4a744b2015-06-11 17:50:29 -0700588 }
589 }
590
Marie Janssena50cc712016-12-28 14:13:21 -0800591 public int updateBleAppCount(IBinder token, boolean enable, String packageName) {
592 ClientDeathRecipient r = mBleApps.get(token);
593 if (r == null && enable) {
594 ClientDeathRecipient deathRec = new ClientDeathRecipient(packageName);
595 try {
596 token.linkToDeath(deathRec, 0);
597 } catch (RemoteException ex) {
598 throw new IllegalArgumentException("BLE app (" + packageName + ") already dead!");
Nitin Arorad055adb2015-03-02 15:03:51 -0800599 }
Marie Janssena50cc712016-12-28 14:13:21 -0800600 mBleApps.put(token, deathRec);
601 if (DBG) Slog.d(TAG, "Registered for death of " + packageName);
602 } else if (!enable && r != null) {
603 // Unregister death recipient as the app goes away.
604 token.unlinkToDeath(r, 0);
605 mBleApps.remove(token);
606 if (DBG) Slog.d(TAG, "Unregistered for death of " + packageName);
Nitin Arorad055adb2015-03-02 15:03:51 -0800607 }
Marie Janssen6689f332016-11-09 12:01:24 -0800608 int appCount = mBleApps.size();
609 if (DBG) Slog.d(TAG, appCount + " registered Ble Apps");
610 if (appCount == 0 && mEnable) {
Wei Wange4a744b2015-06-11 17:50:29 -0700611 disableBleScanMode();
Nitin Arorad055adb2015-03-02 15:03:51 -0800612 }
Marie Janssen6689f332016-11-09 12:01:24 -0800613 return appCount;
Nitin Arorad055adb2015-03-02 15:03:51 -0800614 }
615
Wei Wange4a744b2015-06-11 17:50:29 -0700616 // Clear all apps using BLE scan only mode.
617 private void clearBleApps() {
Marie Janssen6689f332016-11-09 12:01:24 -0800618 mBleApps.clear();
Wei Wange4a744b2015-06-11 17:50:29 -0700619 }
620
Marie Janssena50cc712016-12-28 14:13:21 -0800621 /** @hide */
Nitin Arorad055adb2015-03-02 15:03:51 -0800622 public boolean isBleAppPresent() {
Marie Janssen6689f332016-11-09 12:01:24 -0800623 if (DBG) Slog.d(TAG, "isBleAppPresent() count: " + mBleApps.size());
624 return mBleApps.size() > 0;
Nitin Arorad055adb2015-03-02 15:03:51 -0800625 }
626
627 /**
Marie Janssenfa630682016-12-15 13:51:30 -0800628 * Action taken when GattService is turned on
Nitin Arorad055adb2015-03-02 15:03:51 -0800629 */
630 private void onBluetoothGattServiceUp() {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700631 if (DBG) Slog.d(TAG,"BluetoothGatt Service is Up");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700632 try {
633 mBluetoothLock.readLock().lock();
Marie Janssenfa630682016-12-15 13:51:30 -0800634 if (mBluetooth == null) {
635 if (DBG) Slog.w(TAG, "onBluetoothServiceUp: mBluetooth is null!");
636 return;
637 }
638 int st = mBluetooth.getState();
639 if (st != BluetoothAdapter.STATE_BLE_ON) {
640 if (DBG) Slog.v(TAG, "onBluetoothServiceUp: state isn't BLE_ON: " +
641 BluetoothAdapter.nameForState(st));
642 return;
643 }
644 if (isBluetoothPersistedStateOnBluetooth() || !isBleAppPresent()) {
645 // This triggers transition to STATE_ON
Nitin Arorad055adb2015-03-02 15:03:51 -0800646 mBluetooth.onLeServiceUp();
Nitin Arorad055adb2015-03-02 15:03:51 -0800647 persistBluetoothSetting(BLUETOOTH_ON_BLUETOOTH);
Nitin Arorad055adb2015-03-02 15:03:51 -0800648 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700649 } catch (RemoteException e) {
650 Slog.e(TAG,"Unable to call onServiceUp", e);
651 } finally {
652 mBluetoothLock.readLock().unlock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800653 }
654 }
655
656 /**
657 * Inform BluetoothAdapter instances that BREDR part is down
658 * and turn off all service and stack if no LE app needs it
659 */
660 private void sendBrEdrDownCallback() {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700661 if (DBG) Slog.d(TAG,"Calling sendBrEdrDownCallback callbacks");
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700662
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700663 if (mBluetooth == null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700664 Slog.w(TAG, "Bluetooth handle is null");
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700665 return;
666 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800667
668 if (isBleAppPresent() == false) {
669 try {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700670 mBluetoothLock.readLock().lock();
671 if (mBluetooth != null) mBluetooth.onBrEdrDown();
672 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700673 Slog.e(TAG, "Call to onBrEdrDown() failed.", e);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700674 } finally {
675 mBluetoothLock.readLock().unlock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800676 }
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700677 } else {
678 // Need to stay at BLE ON. Disconnect all Gatt connections
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700679 try {
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700680 mBluetoothGatt.unregAll();
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700681 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700682 Slog.e(TAG, "Unable to disconnect all apps.", e);
Nitin Arorad055adb2015-03-02 15:03:51 -0800683 }
684 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800685 }
686
Marie Janssena50cc712016-12-28 14:13:21 -0800687 public boolean enableNoAutoConnect(String packageName)
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700688 {
689 mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
690 "Need BLUETOOTH ADMIN permission");
Zhihai Xu40874a02012-10-08 17:57:03 -0700691
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700692 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700693 Slog.d(TAG,"enableNoAutoConnect(): mBluetooth =" + mBluetooth +
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700694 " mBinding = " + mBinding);
695 }
Martijn Coenen8385c5a2012-11-29 10:14:16 -0800696 int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
697
698 if (callingAppId != Process.NFC_UID) {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700699 throw new SecurityException("no permission to enable Bluetooth quietly");
700 }
Martijn Coenen8385c5a2012-11-29 10:14:16 -0800701
Zhihai Xu401202b2012-12-03 11:36:21 -0800702 synchronized(mReceiver) {
703 mQuietEnableExternal = true;
704 mEnableExternal = true;
Marie Janssena50cc712016-12-28 14:13:21 -0800705 sendEnableMsg(true, packageName);
Zhihai Xu401202b2012-12-03 11:36:21 -0800706 }
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700707 return true;
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700708 }
Ajay Panicker4bb48302016-03-31 14:14:27 -0700709
Svetoslav Ganovb1e2da72016-06-29 17:31:44 -0700710 public boolean enable(String packageName) throws RemoteException {
711 final int callingUid = Binder.getCallingUid();
712 final boolean callerSystem = UserHandle.getAppId(callingUid) == Process.SYSTEM_UID;
713
714 if (!callerSystem) {
715 if (!checkIfCallerIsForegroundUser()) {
716 Slog.w(TAG, "enable(): not allowed for non-active and non system user");
717 return false;
718 }
719
720 mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
721 "Need BLUETOOTH ADMIN permission");
722
Shijian Li5e7fc7c2017-01-11 17:32:12 +0000723 if (!isEnabled() && mPermissionReviewRequired
724 && startConsentUiIfNeeded(packageName, callingUid,
725 BluetoothAdapter.ACTION_REQUEST_ENABLE)) {
Svetoslav Ganovb1e2da72016-06-29 17:31:44 -0700726 return false;
727 }
fredcf2458862012-04-16 15:18:27 -0700728 }
729
Zhihai Xu401202b2012-12-03 11:36:21 -0800730 if (DBG) {
Marie Janssena50cc712016-12-28 14:13:21 -0800731 Slog.d(TAG,"enable(" + packageName + "): mBluetooth =" + mBluetooth +
Marie Janssenffcf88f2016-12-13 10:51:02 -0800732 " mBinding = " + mBinding + " mState = " +
733 BluetoothAdapter.nameForState(mState));
Sanket Agarwal090bf552016-04-21 14:10:55 -0700734 }
Zhihai Xu401202b2012-12-03 11:36:21 -0800735
736 synchronized(mReceiver) {
737 mQuietEnableExternal = false;
738 mEnableExternal = true;
739 // waive WRITE_SECURE_SETTINGS permission check
Marie Janssena50cc712016-12-28 14:13:21 -0800740 sendEnableMsg(false, packageName);
Zhihai Xu401202b2012-12-03 11:36:21 -0800741 }
Jeff Sharkey67609c72016-03-05 14:29:13 -0700742 if (DBG) Slog.d(TAG, "enable returning");
Zhihai Xu401202b2012-12-03 11:36:21 -0800743 return true;
fredc0f420372012-04-12 00:02:00 -0700744 }
745
Svetoslav Ganovb1e2da72016-06-29 17:31:44 -0700746 public boolean disable(String packageName, boolean persist) throws RemoteException {
747 final int callingUid = Binder.getCallingUid();
748 final boolean callerSystem = UserHandle.getAppId(callingUid) == Process.SYSTEM_UID;
Zhihai Xu40874a02012-10-08 17:57:03 -0700749
Svetoslav Ganovb1e2da72016-06-29 17:31:44 -0700750 if (!callerSystem) {
751 if (!checkIfCallerIsForegroundUser()) {
752 Slog.w(TAG, "disable(): not allowed for non-active and non system user");
753 return false;
754 }
755
756 mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
757 "Need BLUETOOTH ADMIN permission");
758
Shijian Li5e7fc7c2017-01-11 17:32:12 +0000759 if (isEnabled() && mPermissionReviewRequired
760 && startConsentUiIfNeeded(packageName, callingUid,
761 BluetoothAdapter.ACTION_REQUEST_DISABLE)) {
Svetoslav Ganovb1e2da72016-06-29 17:31:44 -0700762 return false;
763 }
Zhihai Xu40874a02012-10-08 17:57:03 -0700764 }
765
fredcf2458862012-04-16 15:18:27 -0700766 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700767 Slog.d(TAG,"disable(): mBluetooth = " + mBluetooth +
Matthew Xiecdce0b92012-07-12 19:06:15 -0700768 " mBinding = " + mBinding);
769 }
fredcf2458862012-04-16 15:18:27 -0700770
Zhihai Xu401202b2012-12-03 11:36:21 -0800771 synchronized(mReceiver) {
772 if (persist) {
Zhihai Xu401202b2012-12-03 11:36:21 -0800773 persistBluetoothSetting(BLUETOOTH_OFF);
Zhihai Xu401202b2012-12-03 11:36:21 -0800774 }
775 mEnableExternal = false;
Marie Janssena50cc712016-12-28 14:13:21 -0800776 sendDisableMsg(packageName);
Zhihai Xu401202b2012-12-03 11:36:21 -0800777 }
fredc0f420372012-04-12 00:02:00 -0700778 return true;
779 }
780
Shijian Li5e7fc7c2017-01-11 17:32:12 +0000781 private boolean startConsentUiIfNeeded(String packageName,
782 int callingUid, String intentAction) throws RemoteException {
Svetoslav Ganovb1e2da72016-06-29 17:31:44 -0700783 try {
784 // Validate the package only if we are going to use it
785 ApplicationInfo applicationInfo = mContext.getPackageManager()
786 .getApplicationInfoAsUser(packageName,
787 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
788 UserHandle.getUserId(callingUid));
789 if (applicationInfo.uid != callingUid) {
790 throw new SecurityException("Package " + callingUid
791 + " not in uid " + callingUid);
792 }
793
Ivan Podogovd2d32b12016-12-05 16:46:52 +0000794 Intent intent = new Intent(intentAction);
Shijian Li5e7fc7c2017-01-11 17:32:12 +0000795 intent.putExtra(Intent.EXTRA_PACKAGE_NAME, packageName);
796 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
797 | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
798 try {
799 mContext.startActivity(intent);
800 } catch (ActivityNotFoundException e) {
801 // Shouldn't happen
802 Slog.e(TAG, "Intent to handle action " + intentAction + " missing");
803 return false;
804 }
805 return true;
Svetoslav Ganovb1e2da72016-06-29 17:31:44 -0700806 } catch (PackageManager.NameNotFoundException e) {
807 throw new RemoteException(e.getMessage());
808 }
Svetoslav Ganovb1e2da72016-06-29 17:31:44 -0700809 }
810
fredc649fe492012-04-19 01:07:18 -0700811 public void unbindAndFinish() {
fredcf2458862012-04-16 15:18:27 -0700812 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700813 Slog.d(TAG,"unbindAndFinish(): " + mBluetooth +
Marie Janssenffcf88f2016-12-13 10:51:02 -0800814 " mBinding = " + mBinding + " mUnbinding = " + mUnbinding);
fredcf2458862012-04-16 15:18:27 -0700815 }
816
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700817 try {
818 mBluetoothLock.writeLock().lock();
fredc0f420372012-04-12 00:02:00 -0700819 if (mUnbinding) return;
820 mUnbinding = true;
Pavlin Radoslavove47ec142016-06-01 22:25:18 -0700821 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
Pavlin Radoslavovc7dda102016-09-21 17:28:11 -0700822 mHandler.removeMessages(MESSAGE_BIND_PROFILE_SERVICE);
Zhihai Xu40874a02012-10-08 17:57:03 -0700823 if (mBluetooth != null) {
Andre Eisenbach305fdab2015-11-11 21:43:26 -0800824 //Unregister callback object
825 try {
826 mBluetooth.unregisterCallback(mBluetoothCallback);
827 } catch (RemoteException re) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700828 Slog.e(TAG, "Unable to unregister BluetoothCallback",re);
fredcbf072a72012-05-09 16:52:50 -0700829 }
Marie Janssen9db28eb2016-01-12 16:05:15 -0800830 mBluetoothBinder = null;
fredcd6883532012-04-25 17:46:13 -0700831 mBluetooth = null;
fredc0f420372012-04-12 00:02:00 -0700832 mContext.unbindService(mConnection);
fredcd6883532012-04-25 17:46:13 -0700833 mUnbinding = false;
Zhihai Xu40874a02012-10-08 17:57:03 -0700834 mBinding = false;
fredcf2458862012-04-16 15:18:27 -0700835 } else {
Marie Janssenffcf88f2016-12-13 10:51:02 -0800836 mUnbinding = false;
fredc0f420372012-04-12 00:02:00 -0700837 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800838 mBluetoothGatt = null;
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700839 } finally {
840 mBluetoothLock.writeLock().unlock();
fredc0f420372012-04-12 00:02:00 -0700841 }
842 }
843
Matthew Xieddf7e472013-03-01 18:41:02 -0800844 public IBluetoothGatt getBluetoothGatt() {
845 // sync protection
846 return mBluetoothGatt;
847 }
848
Benjamin Franze8b98922014-11-12 15:57:54 +0000849 @Override
850 public boolean bindBluetoothProfileService(int bluetoothProfile,
851 IBluetoothProfileServiceConnection proxy) {
852 if (!mEnable) {
853 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700854 Slog.d(TAG, "Trying to bind to profile: " + bluetoothProfile +
Benjamin Franze8b98922014-11-12 15:57:54 +0000855 ", while Bluetooth was disabled");
856 }
857 return false;
858 }
859 synchronized (mProfileServices) {
860 ProfileServiceConnections psc = mProfileServices.get(new Integer(bluetoothProfile));
861 if (psc == null) {
862 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700863 Slog.d(TAG, "Creating new ProfileServiceConnections object for"
Benjamin Franze8b98922014-11-12 15:57:54 +0000864 + " profile: " + bluetoothProfile);
865 }
Benjamin Franz5b614592014-12-09 18:58:45 +0000866
867 if (bluetoothProfile != BluetoothProfile.HEADSET) return false;
868
869 Intent intent = new Intent(IBluetoothHeadset.class.getName());
Benjamin Franze8b98922014-11-12 15:57:54 +0000870 psc = new ProfileServiceConnections(intent);
Benjamin Franz5b614592014-12-09 18:58:45 +0000871 if (!psc.bindService()) return false;
872
Benjamin Franze8b98922014-11-12 15:57:54 +0000873 mProfileServices.put(new Integer(bluetoothProfile), psc);
Benjamin Franze8b98922014-11-12 15:57:54 +0000874 }
875 }
876
877 // Introducing a delay to give the client app time to prepare
878 Message addProxyMsg = mHandler.obtainMessage(MESSAGE_ADD_PROXY_DELAYED);
879 addProxyMsg.arg1 = bluetoothProfile;
880 addProxyMsg.obj = proxy;
881 mHandler.sendMessageDelayed(addProxyMsg, ADD_PROXY_DELAY_MS);
882 return true;
883 }
884
885 @Override
886 public void unbindBluetoothProfileService(int bluetoothProfile,
887 IBluetoothProfileServiceConnection proxy) {
888 synchronized (mProfileServices) {
889 ProfileServiceConnections psc = mProfileServices.get(new Integer(bluetoothProfile));
890 if (psc == null) {
891 return;
892 }
893 psc.removeProxy(proxy);
894 }
895 }
896
897 private void unbindAllBluetoothProfileServices() {
898 synchronized (mProfileServices) {
899 for (Integer i : mProfileServices.keySet()) {
900 ProfileServiceConnections psc = mProfileServices.get(i);
Benjamin Franz5b614592014-12-09 18:58:45 +0000901 try {
902 mContext.unbindService(psc);
903 } catch (IllegalArgumentException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700904 Slog.e(TAG, "Unable to unbind service with intent: " + psc.mIntent, e);
Benjamin Franz5b614592014-12-09 18:58:45 +0000905 }
Benjamin Franze8b98922014-11-12 15:57:54 +0000906 psc.removeAllProxies();
907 }
908 mProfileServices.clear();
909 }
910 }
911
912 /**
Miao Chou658bf2f2015-06-26 17:14:35 -0700913 * Send enable message and set adapter name and address. Called when the boot phase becomes
914 * PHASE_SYSTEM_SERVICES_READY.
915 */
916 public void handleOnBootPhase() {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700917 if (DBG) Slog.d(TAG, "Bluetooth boot completed");
Miao Chou658bf2f2015-06-26 17:14:35 -0700918 if (mEnableExternal && isBluetoothPersistedStateOnBluetooth()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700919 if (DBG) Slog.d(TAG, "Auto-enabling Bluetooth.");
Marie Janssena50cc712016-12-28 14:13:21 -0800920 sendEnableMsg(mQuietEnableExternal, "system boot");
Ajay Panickerbf796d82016-03-11 13:47:20 -0800921 } else if (!isNameAndAddressSet()) {
922 if (DBG) Slog.d(TAG, "Getting adapter name and address");
Ajay Panicker4bb48302016-03-31 14:14:27 -0700923 Message getMsg = mHandler.obtainMessage(MESSAGE_GET_NAME_AND_ADDRESS);
924 mHandler.sendMessage(getMsg);
Miao Chou658bf2f2015-06-26 17:14:35 -0700925 }
Miao Chou658bf2f2015-06-26 17:14:35 -0700926 }
927
928 /**
929 * Called when switching to a different foreground user.
930 */
931 public void handleOnSwitchUser(int userHandle) {
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -0700932 if (DBG) Slog.d(TAG, "User " + userHandle + " switched");
933 mHandler.obtainMessage(MESSAGE_USER_SWITCHED, userHandle, 0).sendToTarget();
934 }
935
936 /**
937 * Called when user is unlocked.
938 */
939 public void handleOnUnlockUser(int userHandle) {
940 if (DBG) Slog.d(TAG, "User " + userHandle + " unlocked");
941 mHandler.obtainMessage(MESSAGE_USER_UNLOCKED, userHandle, 0).sendToTarget();
Miao Chou658bf2f2015-06-26 17:14:35 -0700942 }
943
944 /**
Benjamin Franze8b98922014-11-12 15:57:54 +0000945 * This class manages the clients connected to a given ProfileService
946 * and maintains the connection with that service.
947 */
948 final private class ProfileServiceConnections implements ServiceConnection,
949 IBinder.DeathRecipient {
950 final RemoteCallbackList<IBluetoothProfileServiceConnection> mProxies =
951 new RemoteCallbackList <IBluetoothProfileServiceConnection>();
952 IBinder mService;
953 ComponentName mClassName;
954 Intent mIntent;
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700955 boolean mInvokingProxyCallbacks = false;
Benjamin Franze8b98922014-11-12 15:57:54 +0000956
957 ProfileServiceConnections(Intent intent) {
958 mService = null;
959 mClassName = null;
960 mIntent = intent;
961 }
962
Benjamin Franz5b614592014-12-09 18:58:45 +0000963 private boolean bindService() {
964 if (mIntent != null && mService == null &&
965 doBind(mIntent, this, 0, UserHandle.CURRENT_OR_SELF)) {
Benjamin Franze8b98922014-11-12 15:57:54 +0000966 Message msg = mHandler.obtainMessage(MESSAGE_BIND_PROFILE_SERVICE);
967 msg.obj = this;
968 mHandler.sendMessageDelayed(msg, TIMEOUT_BIND_MS);
Benjamin Franz5b614592014-12-09 18:58:45 +0000969 return true;
Benjamin Franze8b98922014-11-12 15:57:54 +0000970 }
Jeff Sharkey67609c72016-03-05 14:29:13 -0700971 Slog.w(TAG, "Unable to bind with intent: " + mIntent);
Benjamin Franz5b614592014-12-09 18:58:45 +0000972 return false;
Benjamin Franze8b98922014-11-12 15:57:54 +0000973 }
974
975 private void addProxy(IBluetoothProfileServiceConnection proxy) {
976 mProxies.register(proxy);
977 if (mService != null) {
978 try{
979 proxy.onServiceConnected(mClassName, mService);
980 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700981 Slog.e(TAG, "Unable to connect to proxy", e);
Benjamin Franze8b98922014-11-12 15:57:54 +0000982 }
983 } else {
984 if (!mHandler.hasMessages(MESSAGE_BIND_PROFILE_SERVICE, this)) {
985 Message msg = mHandler.obtainMessage(MESSAGE_BIND_PROFILE_SERVICE);
986 msg.obj = this;
987 mHandler.sendMessage(msg);
988 }
989 }
990 }
991
992 private void removeProxy(IBluetoothProfileServiceConnection proxy) {
993 if (proxy != null) {
994 if (mProxies.unregister(proxy)) {
995 try {
996 proxy.onServiceDisconnected(mClassName);
997 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700998 Slog.e(TAG, "Unable to disconnect proxy", e);
Benjamin Franze8b98922014-11-12 15:57:54 +0000999 }
1000 }
1001 } else {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001002 Slog.w(TAG, "Trying to remove a null proxy");
Benjamin Franze8b98922014-11-12 15:57:54 +00001003 }
1004 }
1005
1006 private void removeAllProxies() {
1007 onServiceDisconnected(mClassName);
1008 mProxies.kill();
1009 }
1010
1011 @Override
1012 public void onServiceConnected(ComponentName className, IBinder service) {
1013 // remove timeout message
1014 mHandler.removeMessages(MESSAGE_BIND_PROFILE_SERVICE, this);
1015 mService = service;
1016 mClassName = className;
1017 try {
1018 mService.linkToDeath(this, 0);
1019 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001020 Slog.e(TAG, "Unable to linkToDeath", e);
Benjamin Franze8b98922014-11-12 15:57:54 +00001021 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001022
1023 if (mInvokingProxyCallbacks) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001024 Slog.e(TAG, "Proxy callbacks already in progress.");
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001025 return;
Benjamin Franze8b98922014-11-12 15:57:54 +00001026 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001027 mInvokingProxyCallbacks = true;
1028
1029 final int n = mProxies.beginBroadcast();
1030 try {
1031 for (int i = 0; i < n; i++) {
1032 try {
1033 mProxies.getBroadcastItem(i).onServiceConnected(className, service);
1034 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001035 Slog.e(TAG, "Unable to connect to proxy", e);
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001036 }
1037 }
1038 } finally {
1039 mProxies.finishBroadcast();
1040 mInvokingProxyCallbacks = false;
1041 }
Benjamin Franze8b98922014-11-12 15:57:54 +00001042 }
1043
1044 @Override
1045 public void onServiceDisconnected(ComponentName className) {
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001046 if (mService == null) return;
Benjamin Franze8b98922014-11-12 15:57:54 +00001047 mService.unlinkToDeath(this, 0);
1048 mService = null;
1049 mClassName = null;
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001050
1051 if (mInvokingProxyCallbacks) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001052 Slog.e(TAG, "Proxy callbacks already in progress.");
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001053 return;
Benjamin Franze8b98922014-11-12 15:57:54 +00001054 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001055 mInvokingProxyCallbacks = true;
1056
1057 final int n = mProxies.beginBroadcast();
1058 try {
1059 for (int i = 0; i < n; i++) {
1060 try {
1061 mProxies.getBroadcastItem(i).onServiceDisconnected(className);
1062 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001063 Slog.e(TAG, "Unable to disconnect from proxy", e);
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001064 }
1065 }
1066 } finally {
1067 mProxies.finishBroadcast();
1068 mInvokingProxyCallbacks = false;
1069 }
Benjamin Franze8b98922014-11-12 15:57:54 +00001070 }
1071
1072 @Override
1073 public void binderDied() {
1074 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001075 Slog.w(TAG, "Profile service for profile: " + mClassName
Benjamin Franze8b98922014-11-12 15:57:54 +00001076 + " died.");
1077 }
1078 onServiceDisconnected(mClassName);
1079 // Trigger rebind
1080 Message msg = mHandler.obtainMessage(MESSAGE_BIND_PROFILE_SERVICE);
1081 msg.obj = this;
1082 mHandler.sendMessageDelayed(msg, TIMEOUT_BIND_MS);
1083 }
1084 }
1085
fredcbf072a72012-05-09 16:52:50 -07001086 private void sendBluetoothStateCallback(boolean isUp) {
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001087 try {
1088 int n = mStateChangeCallbacks.beginBroadcast();
Jeff Sharkey67609c72016-03-05 14:29:13 -07001089 if (DBG) Slog.d(TAG,"Broadcasting onBluetoothStateChange("+isUp+") to " + n + " receivers.");
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001090 for (int i=0; i <n;i++) {
1091 try {
1092 mStateChangeCallbacks.getBroadcastItem(i).onBluetoothStateChange(isUp);
1093 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001094 Slog.e(TAG, "Unable to call onBluetoothStateChange() on callback #" + i , e);
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001095 }
fredcbf072a72012-05-09 16:52:50 -07001096 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001097 } finally {
1098 mStateChangeCallbacks.finishBroadcast();
fredcbf072a72012-05-09 16:52:50 -07001099 }
fredcbf072a72012-05-09 16:52:50 -07001100 }
1101
1102 /**
Zhihai Xu40874a02012-10-08 17:57:03 -07001103 * Inform BluetoothAdapter instances that Adapter service is up
1104 */
1105 private void sendBluetoothServiceUpCallback() {
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001106 try {
1107 int n = mCallbacks.beginBroadcast();
Jeff Sharkey67609c72016-03-05 14:29:13 -07001108 Slog.d(TAG,"Broadcasting onBluetoothServiceUp() to " + n + " receivers.");
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001109 for (int i=0; i <n;i++) {
1110 try {
1111 mCallbacks.getBroadcastItem(i).onBluetoothServiceUp(mBluetooth);
1112 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001113 Slog.e(TAG, "Unable to call onBluetoothServiceUp() on callback #" + i, e);
Zhihai Xu40874a02012-10-08 17:57:03 -07001114 }
1115 }
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001116 } finally {
1117 mCallbacks.finishBroadcast();
Zhihai Xu40874a02012-10-08 17:57:03 -07001118 }
1119 }
1120 /**
fredcbf072a72012-05-09 16:52:50 -07001121 * Inform BluetoothAdapter instances that Adapter service is down
1122 */
1123 private void sendBluetoothServiceDownCallback() {
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001124 try {
1125 int n = mCallbacks.beginBroadcast();
Jeff Sharkey67609c72016-03-05 14:29:13 -07001126 Slog.d(TAG,"Broadcasting onBluetoothServiceDown() to " + n + " receivers.");
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001127 for (int i=0; i <n;i++) {
1128 try {
1129 mCallbacks.getBroadcastItem(i).onBluetoothServiceDown();
1130 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001131 Slog.e(TAG, "Unable to call onBluetoothServiceDown() on callback #" + i, e);
fredcd6883532012-04-25 17:46:13 -07001132 }
1133 }
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001134 } finally {
1135 mCallbacks.finishBroadcast();
fredcd6883532012-04-25 17:46:13 -07001136 }
1137 }
Svet Ganov408abf72015-05-12 19:13:36 -07001138
fredc0f420372012-04-12 00:02:00 -07001139 public String getAddress() {
Matthew Xieaf5ddbf2012-12-04 10:47:43 -08001140 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
Svet Ganov408abf72015-05-12 19:13:36 -07001141 "Need BLUETOOTH permission");
Zhihai Xu40874a02012-10-08 17:57:03 -07001142
Zhihai Xu6eb76522012-11-29 15:41:04 -08001143 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
Svet Ganov408abf72015-05-12 19:13:36 -07001144 (!checkIfCallerIsForegroundUser())) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001145 Slog.w(TAG,"getAddress(): not allowed for non-active and non system user");
Zhihai Xu6eb76522012-11-29 15:41:04 -08001146 return null;
Zhihai Xu40874a02012-10-08 17:57:03 -07001147 }
1148
Svet Ganov408abf72015-05-12 19:13:36 -07001149 if (mContext.checkCallingOrSelfPermission(Manifest.permission.LOCAL_MAC_ADDRESS)
1150 != PackageManager.PERMISSION_GRANTED) {
1151 return BluetoothAdapter.DEFAULT_MAC_ADDRESS;
1152 }
1153
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001154 try {
1155 mBluetoothLock.readLock().lock();
1156 if (mBluetooth != null) return mBluetooth.getAddress();
1157 } catch (RemoteException e) {
1158 Slog.e(TAG, "getAddress(): Unable to retrieve address remotely. Returning cached address", e);
1159 } finally {
1160 mBluetoothLock.readLock().unlock();
fredc116d1d462012-04-20 14:47:08 -07001161 }
Ajay Panickerbf796d82016-03-11 13:47:20 -08001162
Matthew Xiecdce0b92012-07-12 19:06:15 -07001163 // mAddress is accessed from outside.
1164 // It is alright without a lock. Here, bluetooth is off, no other thread is
1165 // changing mAddress
fredc0f420372012-04-12 00:02:00 -07001166 return mAddress;
1167 }
fredc649fe492012-04-19 01:07:18 -07001168
fredc0f420372012-04-12 00:02:00 -07001169 public String getName() {
Matthew Xieaf5ddbf2012-12-04 10:47:43 -08001170 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
1171 "Need BLUETOOTH permission");
Zhihai Xu40874a02012-10-08 17:57:03 -07001172
Zhihai Xu6eb76522012-11-29 15:41:04 -08001173 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
1174 (!checkIfCallerIsForegroundUser())) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001175 Slog.w(TAG,"getName(): not allowed for non-active and non system user");
Zhihai Xu6eb76522012-11-29 15:41:04 -08001176 return null;
Zhihai Xu40874a02012-10-08 17:57:03 -07001177 }
1178
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001179 try {
1180 mBluetoothLock.readLock().lock();
1181 if (mBluetooth != null) return mBluetooth.getName();
1182 } catch (RemoteException e) {
1183 Slog.e(TAG, "getName(): Unable to retrieve name remotely. Returning cached name", e);
1184 } finally {
1185 mBluetoothLock.readLock().unlock();
fredc116d1d462012-04-20 14:47:08 -07001186 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001187
Matthew Xiecdce0b92012-07-12 19:06:15 -07001188 // mName is accessed from outside.
1189 // It alright without a lock. Here, bluetooth is off, no other thread is
1190 // changing mName
fredc0f420372012-04-12 00:02:00 -07001191 return mName;
1192 }
1193
fredc0f420372012-04-12 00:02:00 -07001194 private class BluetoothServiceConnection implements ServiceConnection {
Marie Janssenffcf88f2016-12-13 10:51:02 -08001195 public void onServiceConnected(ComponentName componentName, IBinder service) {
1196 String name = componentName.getClassName();
1197 if (DBG) Slog.d(TAG, "BluetoothServiceConnection: " + name);
fredc0f420372012-04-12 00:02:00 -07001198 Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_SERVICE_CONNECTED);
Marie Janssenffcf88f2016-12-13 10:51:02 -08001199 if (name.equals("com.android.bluetooth.btservice.AdapterService")) {
Matthew Xieddf7e472013-03-01 18:41:02 -08001200 msg.arg1 = SERVICE_IBLUETOOTH;
Marie Janssenffcf88f2016-12-13 10:51:02 -08001201 } else if (name.equals("com.android.bluetooth.gatt.GattService")) {
Matthew Xieddf7e472013-03-01 18:41:02 -08001202 msg.arg1 = SERVICE_IBLUETOOTHGATT;
1203 } else {
Marie Janssenffcf88f2016-12-13 10:51:02 -08001204 Slog.e(TAG, "Unknown service connected: " + name);
Matthew Xieddf7e472013-03-01 18:41:02 -08001205 return;
1206 }
fredc0f420372012-04-12 00:02:00 -07001207 msg.obj = service;
1208 mHandler.sendMessage(msg);
1209 }
1210
Marie Janssenffcf88f2016-12-13 10:51:02 -08001211 public void onServiceDisconnected(ComponentName componentName) {
1212 // Called if we unexpectedly disconnect.
1213 String name = componentName.getClassName();
1214 if (DBG) Slog.d(TAG, "BluetoothServiceConnection, disconnected: " + name);
fredc0f420372012-04-12 00:02:00 -07001215 Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED);
Marie Janssenffcf88f2016-12-13 10:51:02 -08001216 if (name.equals("com.android.bluetooth.btservice.AdapterService")) {
Matthew Xieddf7e472013-03-01 18:41:02 -08001217 msg.arg1 = SERVICE_IBLUETOOTH;
Marie Janssenffcf88f2016-12-13 10:51:02 -08001218 } else if (name.equals("com.android.bluetooth.gatt.GattService")) {
Matthew Xieddf7e472013-03-01 18:41:02 -08001219 msg.arg1 = SERVICE_IBLUETOOTHGATT;
1220 } else {
Marie Janssenffcf88f2016-12-13 10:51:02 -08001221 Slog.e(TAG, "Unknown service disconnected: " + name);
Matthew Xieddf7e472013-03-01 18:41:02 -08001222 return;
1223 }
fredc0f420372012-04-12 00:02:00 -07001224 mHandler.sendMessage(msg);
1225 }
1226 }
1227
1228 private BluetoothServiceConnection mConnection = new BluetoothServiceConnection();
1229
Zhihai Xu40874a02012-10-08 17:57:03 -07001230 private class BluetoothHandler extends Handler {
Ajay Panicker4bb48302016-03-31 14:14:27 -07001231 boolean mGetNameAddressOnly = false;
1232
Zhihai Xu40874a02012-10-08 17:57:03 -07001233 public BluetoothHandler(Looper looper) {
1234 super(looper);
1235 }
1236
fredc0f420372012-04-12 00:02:00 -07001237 @Override
1238 public void handleMessage(Message msg) {
fredc0f420372012-04-12 00:02:00 -07001239 switch (msg.what) {
Ajay Panicker4bb48302016-03-31 14:14:27 -07001240 case MESSAGE_GET_NAME_AND_ADDRESS:
1241 if (DBG) Slog.d(TAG, "MESSAGE_GET_NAME_AND_ADDRESS");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001242 try {
1243 mBluetoothLock.writeLock().lock();
Ajay Panicker4bb48302016-03-31 14:14:27 -07001244 if ((mBluetooth == null) && (!mBinding)) {
1245 if (DBG) Slog.d(TAG, "Binding to service to get name and address");
1246 mGetNameAddressOnly = true;
1247 Message timeoutMsg = mHandler.obtainMessage(MESSAGE_TIMEOUT_BIND);
1248 mHandler.sendMessageDelayed(timeoutMsg, TIMEOUT_BIND_MS);
1249 Intent i = new Intent(IBluetooth.class.getName());
1250 if (!doBind(i, mConnection,
1251 Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT,
1252 UserHandle.CURRENT)) {
1253 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
1254 } else {
1255 mBinding = true;
1256 }
1257 } else if (mBluetooth != null) {
1258 try {
1259 storeNameAndAddress(mBluetooth.getName(),
1260 mBluetooth.getAddress());
1261 } catch (RemoteException re) {
1262 Slog.e(TAG, "Unable to grab names", re);
1263 }
1264 if (mGetNameAddressOnly && !mEnable) {
1265 unbindAndFinish();
1266 }
1267 mGetNameAddressOnly = false;
1268 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001269 } finally {
1270 mBluetoothLock.writeLock().unlock();
Ajay Panicker4bb48302016-03-31 14:14:27 -07001271 }
1272 break;
1273
Matthew Xiecdce0b92012-07-12 19:06:15 -07001274 case MESSAGE_ENABLE:
fredcf2458862012-04-16 15:18:27 -07001275 if (DBG) {
Marie Janssenffcf88f2016-12-13 10:51:02 -08001276 Slog.d(TAG, "MESSAGE_ENABLE(" + msg.arg1 + "): mBluetooth = " + mBluetooth);
fredc649fe492012-04-19 01:07:18 -07001277 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001278 mHandler.removeMessages(MESSAGE_RESTART_BLUETOOTH_SERVICE);
1279 mEnable = true;
Calvin Ona0b91d72016-06-15 17:58:23 -07001280
1281 // Use service interface to get the exact state
1282 try {
1283 mBluetoothLock.readLock().lock();
1284 if (mBluetooth != null) {
1285 int state = mBluetooth.getState();
1286 if (state == BluetoothAdapter.STATE_BLE_ON) {
Marie Janssenfa9bec92016-12-20 11:21:12 -08001287 Slog.w(TAG, "BT Enable in BLE_ON State, going to ON");
Calvin Ona0b91d72016-06-15 17:58:23 -07001288 mBluetooth.onLeServiceUp();
Marie Janssenfa9bec92016-12-20 11:21:12 -08001289 persistBluetoothSetting(BLUETOOTH_ON_BLUETOOTH);
Calvin Ona0b91d72016-06-15 17:58:23 -07001290 break;
1291 }
1292 }
1293 } catch (RemoteException e) {
1294 Slog.e(TAG, "", e);
1295 } finally {
1296 mBluetoothLock.readLock().unlock();
1297 }
1298
1299 mQuietEnable = (msg.arg1 == 1);
Pavlin Radoslavove47ec142016-06-01 22:25:18 -07001300 if (mBluetooth == null) {
Calvin Ona0b91d72016-06-15 17:58:23 -07001301 handleEnable(mQuietEnable);
Pavlin Radoslavove47ec142016-06-01 22:25:18 -07001302 } else {
1303 //
1304 // We need to wait until transitioned to STATE_OFF and
1305 // the previous Bluetooth process has exited. The
1306 // waiting period has three components:
1307 // (a) Wait until the local state is STATE_OFF. This
1308 // is accomplished by "waitForOnOff(false, true)".
1309 // (b) Wait until the STATE_OFF state is updated to
1310 // all components.
1311 // (c) Wait until the Bluetooth process exits, and
1312 // ActivityManager detects it.
1313 // The waiting for (b) and (c) is accomplished by
1314 // delaying the MESSAGE_RESTART_BLUETOOTH_SERVICE
1315 // message. On slower devices, that delay needs to be
1316 // on the order of (2 * SERVICE_RESTART_TIME_MS).
1317 //
1318 waitForOnOff(false, true);
Pavlin Radoslavove47ec142016-06-01 22:25:18 -07001319 Message restartMsg = mHandler.obtainMessage(
1320 MESSAGE_RESTART_BLUETOOTH_SERVICE);
1321 mHandler.sendMessageDelayed(restartMsg,
1322 2 * SERVICE_RESTART_TIME_MS);
1323 }
fredc649fe492012-04-19 01:07:18 -07001324 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001325
fredc0f420372012-04-12 00:02:00 -07001326 case MESSAGE_DISABLE:
Marie Janssenffcf88f2016-12-13 10:51:02 -08001327 if (DBG) Slog.d(TAG, "MESSAGE_DISABLE: mBluetooth = " + mBluetooth);
Zhihai Xu40874a02012-10-08 17:57:03 -07001328 mHandler.removeMessages(MESSAGE_RESTART_BLUETOOTH_SERVICE);
1329 if (mEnable && mBluetooth != null) {
1330 waitForOnOff(true, false);
1331 mEnable = false;
Zhihai Xu401202b2012-12-03 11:36:21 -08001332 handleDisable();
Zhihai Xu40874a02012-10-08 17:57:03 -07001333 waitForOnOff(false, false);
1334 } else {
1335 mEnable = false;
Zhihai Xu401202b2012-12-03 11:36:21 -08001336 handleDisable();
Zhihai Xu40874a02012-10-08 17:57:03 -07001337 }
fredc0f420372012-04-12 00:02:00 -07001338 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001339
fredc0f420372012-04-12 00:02:00 -07001340 case MESSAGE_REGISTER_ADAPTER:
1341 {
1342 IBluetoothManagerCallback callback = (IBluetoothManagerCallback) msg.obj;
Marie Janssenffcf88f2016-12-13 10:51:02 -08001343 mCallbacks.register(callback);
fredc0f420372012-04-12 00:02:00 -07001344 break;
Marie Janssenffcf88f2016-12-13 10:51:02 -08001345 }
fredc0f420372012-04-12 00:02:00 -07001346 case MESSAGE_UNREGISTER_ADAPTER:
1347 {
1348 IBluetoothManagerCallback callback = (IBluetoothManagerCallback) msg.obj;
Marie Janssenffcf88f2016-12-13 10:51:02 -08001349 mCallbacks.unregister(callback);
fredc0f420372012-04-12 00:02:00 -07001350 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001351 }
fredc0f420372012-04-12 00:02:00 -07001352 case MESSAGE_REGISTER_STATE_CHANGE_CALLBACK:
1353 {
1354 IBluetoothStateChangeCallback callback = (IBluetoothStateChangeCallback) msg.obj;
Marie Janssenffcf88f2016-12-13 10:51:02 -08001355 mStateChangeCallbacks.register(callback);
fredc0f420372012-04-12 00:02:00 -07001356 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001357 }
fredc0f420372012-04-12 00:02:00 -07001358 case MESSAGE_UNREGISTER_STATE_CHANGE_CALLBACK:
1359 {
1360 IBluetoothStateChangeCallback callback = (IBluetoothStateChangeCallback) msg.obj;
Marie Janssenffcf88f2016-12-13 10:51:02 -08001361 mStateChangeCallbacks.unregister(callback);
fredc0f420372012-04-12 00:02:00 -07001362 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001363 }
Benjamin Franze8b98922014-11-12 15:57:54 +00001364 case MESSAGE_ADD_PROXY_DELAYED:
1365 {
1366 ProfileServiceConnections psc = mProfileServices.get(
1367 new Integer(msg.arg1));
1368 if (psc == null) {
1369 break;
1370 }
1371 IBluetoothProfileServiceConnection proxy =
1372 (IBluetoothProfileServiceConnection) msg.obj;
1373 psc.addProxy(proxy);
1374 break;
1375 }
1376 case MESSAGE_BIND_PROFILE_SERVICE:
1377 {
1378 ProfileServiceConnections psc = (ProfileServiceConnections) msg.obj;
1379 removeMessages(MESSAGE_BIND_PROFILE_SERVICE, msg.obj);
1380 if (psc == null) {
1381 break;
1382 }
1383 psc.bindService();
1384 break;
1385 }
fredc0f420372012-04-12 00:02:00 -07001386 case MESSAGE_BLUETOOTH_SERVICE_CONNECTED:
1387 {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001388 if (DBG) Slog.d(TAG,"MESSAGE_BLUETOOTH_SERVICE_CONNECTED: " + msg.arg1);
fredc0f420372012-04-12 00:02:00 -07001389
1390 IBinder service = (IBinder) msg.obj;
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001391 try {
1392 mBluetoothLock.writeLock().lock();
Matthew Xieddf7e472013-03-01 18:41:02 -08001393 if (msg.arg1 == SERVICE_IBLUETOOTHGATT) {
1394 mBluetoothGatt = IBluetoothGatt.Stub.asInterface(service);
Nitin Arorad055adb2015-03-02 15:03:51 -08001395 onBluetoothGattServiceUp();
Matthew Xieddf7e472013-03-01 18:41:02 -08001396 break;
1397 } // else must be SERVICE_IBLUETOOTH
1398
1399 //Remove timeout
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001400 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
Matthew Xieddf7e472013-03-01 18:41:02 -08001401
fredc0f420372012-04-12 00:02:00 -07001402 mBinding = false;
Marie Janssen9db28eb2016-01-12 16:05:15 -08001403 mBluetoothBinder = service;
fredc0f420372012-04-12 00:02:00 -07001404 mBluetooth = IBluetooth.Stub.asInterface(service);
fredc0f420372012-04-12 00:02:00 -07001405
Ajay Panicker4bb48302016-03-31 14:14:27 -07001406 if (!isNameAndAddressSet()) {
1407 Message getMsg = mHandler.obtainMessage(MESSAGE_GET_NAME_AND_ADDRESS);
1408 mHandler.sendMessage(getMsg);
1409 if (mGetNameAddressOnly) return;
1410 }
1411
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001412 try {
1413 boolean enableHciSnoopLog = (Settings.Secure.getInt(mContentResolver,
1414 Settings.Secure.BLUETOOTH_HCI_LOG, 0) == 1);
1415 if (!mBluetooth.configHciSnoopLog(enableHciSnoopLog)) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001416 Slog.e(TAG,"IBluetooth.configHciSnoopLog return false");
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001417 }
1418 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001419 Slog.e(TAG,"Unable to call configHciSnoopLog", e);
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001420 }
1421
Matthew Xiecdce0b92012-07-12 19:06:15 -07001422 //Register callback object
fredcbf072a72012-05-09 16:52:50 -07001423 try {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001424 mBluetooth.registerCallback(mBluetoothCallback);
1425 } catch (RemoteException re) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001426 Slog.e(TAG, "Unable to register BluetoothCallback",re);
fredcbf072a72012-05-09 16:52:50 -07001427 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001428 //Inform BluetoothAdapter instances that service is up
Zhihai Xu40874a02012-10-08 17:57:03 -07001429 sendBluetoothServiceUpCallback();
1430
Matthew Xiecdce0b92012-07-12 19:06:15 -07001431 //Do enable request
1432 try {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001433 if (mQuietEnable == false) {
Marie Janssenffcf88f2016-12-13 10:51:02 -08001434 if (!mBluetooth.enable()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001435 Slog.e(TAG,"IBluetooth.enable() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001436 }
Marie Janssenffcf88f2016-12-13 10:51:02 -08001437 } else {
1438 if (!mBluetooth.enableNoAutoConnect()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001439 Slog.e(TAG,"IBluetooth.enableNoAutoConnect() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001440 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001441 }
1442 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001443 Slog.e(TAG,"Unable to call enable()",e);
Matthew Xiecdce0b92012-07-12 19:06:15 -07001444 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001445 } finally {
1446 mBluetoothLock.writeLock().unlock();
Freda8c6df02012-07-11 10:25:23 -07001447 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001448
1449 if (!mEnable) {
1450 waitForOnOff(true, false);
Zhihai Xu401202b2012-12-03 11:36:21 -08001451 handleDisable();
Zhihai Xu40874a02012-10-08 17:57:03 -07001452 waitForOnOff(false, false);
1453 }
fredc649fe492012-04-19 01:07:18 -07001454 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001455 }
fredcbf072a72012-05-09 16:52:50 -07001456 case MESSAGE_BLUETOOTH_STATE_CHANGE:
fredc0f420372012-04-12 00:02:00 -07001457 {
fredcbf072a72012-05-09 16:52:50 -07001458 int prevState = msg.arg1;
1459 int newState = msg.arg2;
Marie Janssenffcf88f2016-12-13 10:51:02 -08001460 if (DBG) {
1461 Slog.d(TAG, "MESSAGE_BLUETOOTH_STATE_CHANGE: " + BluetoothAdapter.nameForState(prevState) + " > " +
1462 BluetoothAdapter.nameForState(newState));
1463 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001464 mState = newState;
1465 bluetoothStateChangeHandler(prevState, newState);
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001466 // handle error state transition case from TURNING_ON to OFF
1467 // unbind and rebind bluetooth service and enable bluetooth
Nitin Arorad055adb2015-03-02 15:03:51 -08001468 if ((prevState == BluetoothAdapter.STATE_BLE_TURNING_ON) &&
Calvin Ona0b91d72016-06-15 17:58:23 -07001469 (newState == BluetoothAdapter.STATE_OFF) &&
1470 (mBluetooth != null) && mEnable) {
Marie Janssen6689f332016-11-09 12:01:24 -08001471 recoverBluetoothServiceFromError(false);
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001472 }
Nitin Arorad055adb2015-03-02 15:03:51 -08001473 if ((prevState == BluetoothAdapter.STATE_TURNING_ON) &&
Calvin Ona0b91d72016-06-15 17:58:23 -07001474 (newState == BluetoothAdapter.STATE_BLE_ON) &&
1475 (mBluetooth != null) && mEnable) {
Marie Janssen6689f332016-11-09 12:01:24 -08001476 recoverBluetoothServiceFromError(true);
Nitin Arorad055adb2015-03-02 15:03:51 -08001477 }
Calvin Ona0b91d72016-06-15 17:58:23 -07001478 // If we tried to enable BT while BT was in the process of shutting down,
1479 // wait for the BT process to fully tear down and then force a restart
1480 // here. This is a bit of a hack (b/29363429).
1481 if ((prevState == BluetoothAdapter.STATE_BLE_TURNING_OFF) &&
1482 (newState == BluetoothAdapter.STATE_OFF)) {
1483 if (mEnable) {
1484 Slog.d(TAG, "Entering STATE_OFF but mEnabled is true; restarting.");
1485 waitForOnOff(false, true);
1486 Message restartMsg = mHandler.obtainMessage(
1487 MESSAGE_RESTART_BLUETOOTH_SERVICE);
1488 mHandler.sendMessageDelayed(restartMsg, 2 * SERVICE_RESTART_TIME_MS);
1489 }
1490 }
Nitin Arorad055adb2015-03-02 15:03:51 -08001491 if (newState == BluetoothAdapter.STATE_ON ||
Calvin Ona0b91d72016-06-15 17:58:23 -07001492 newState == BluetoothAdapter.STATE_BLE_ON) {
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001493 // bluetooth is working, reset the counter
1494 if (mErrorRecoveryRetryCounter != 0) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001495 Slog.w(TAG, "bluetooth is recovered from error");
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001496 mErrorRecoveryRetryCounter = 0;
1497 }
1498 }
fredc649fe492012-04-19 01:07:18 -07001499 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001500 }
fredc0f420372012-04-12 00:02:00 -07001501 case MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED:
1502 {
Marie Janssenffcf88f2016-12-13 10:51:02 -08001503 Slog.e(TAG, "MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED(" + msg.arg1 + ")");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001504 try {
1505 mBluetoothLock.writeLock().lock();
Matthew Xieddf7e472013-03-01 18:41:02 -08001506 if (msg.arg1 == SERVICE_IBLUETOOTH) {
1507 // if service is unbinded already, do nothing and return
1508 if (mBluetooth == null) break;
1509 mBluetooth = null;
1510 } else if (msg.arg1 == SERVICE_IBLUETOOTHGATT) {
1511 mBluetoothGatt = null;
1512 break;
1513 } else {
Marie Janssenffcf88f2016-12-13 10:51:02 -08001514 Slog.e(TAG, "Unknown argument for service disconnect!");
Matthew Xieddf7e472013-03-01 18:41:02 -08001515 break;
1516 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001517 } finally {
1518 mBluetoothLock.writeLock().unlock();
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301519 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001520
1521 if (mEnable) {
1522 mEnable = false;
1523 // Send a Bluetooth Restart message
1524 Message restartMsg = mHandler.obtainMessage(
1525 MESSAGE_RESTART_BLUETOOTH_SERVICE);
1526 mHandler.sendMessageDelayed(restartMsg,
1527 SERVICE_RESTART_TIME_MS);
1528 }
1529
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001530 sendBluetoothServiceDownCallback();
Zhihai Xu40874a02012-10-08 17:57:03 -07001531
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001532 // Send BT state broadcast to update
1533 // the BT icon correctly
1534 if ((mState == BluetoothAdapter.STATE_TURNING_ON) ||
Calvin Ona0b91d72016-06-15 17:58:23 -07001535 (mState == BluetoothAdapter.STATE_ON)) {
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001536 bluetoothStateChangeHandler(BluetoothAdapter.STATE_ON,
1537 BluetoothAdapter.STATE_TURNING_OFF);
1538 mState = BluetoothAdapter.STATE_TURNING_OFF;
Zhihai Xu40874a02012-10-08 17:57:03 -07001539 }
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001540 if (mState == BluetoothAdapter.STATE_TURNING_OFF) {
1541 bluetoothStateChangeHandler(BluetoothAdapter.STATE_TURNING_OFF,
1542 BluetoothAdapter.STATE_OFF);
1543 }
1544
1545 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
1546 mState = BluetoothAdapter.STATE_OFF;
fredc649fe492012-04-19 01:07:18 -07001547 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001548 }
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301549 case MESSAGE_RESTART_BLUETOOTH_SERVICE:
1550 {
Marie Janssenffcf88f2016-12-13 10:51:02 -08001551 Slog.d(TAG, "MESSAGE_RESTART_BLUETOOTH_SERVICE");
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301552 /* Enable without persisting the setting as
1553 it doesnt change when IBluetooth
1554 service restarts */
Zhihai Xu40874a02012-10-08 17:57:03 -07001555 mEnable = true;
Zhihai Xu401202b2012-12-03 11:36:21 -08001556 handleEnable(mQuietEnable);
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301557 break;
1558 }
Marie Janssenffcf88f2016-12-13 10:51:02 -08001559 case MESSAGE_TIMEOUT_BIND: {
1560 Slog.e(TAG, "MESSAGE_TIMEOUT_BIND");
1561 mBluetoothLock.writeLock().lock();
1562 mBinding = false;
1563 mBluetoothLock.writeLock().unlock();
1564 break;
1565 }
fredc0f420372012-04-12 00:02:00 -07001566 case MESSAGE_TIMEOUT_UNBIND:
1567 {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001568 Slog.e(TAG, "MESSAGE_TIMEOUT_UNBIND");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001569 mBluetoothLock.writeLock().lock();
1570 mUnbinding = false;
1571 mBluetoothLock.writeLock().unlock();
fredc649fe492012-04-19 01:07:18 -07001572 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001573 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001574
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001575 case MESSAGE_USER_SWITCHED: {
1576 if (DBG) Slog.d(TAG, "MESSAGE_USER_SWITCHED");
Zhihai Xu40874a02012-10-08 17:57:03 -07001577 mHandler.removeMessages(MESSAGE_USER_SWITCHED);
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001578
Zhihai Xu40874a02012-10-08 17:57:03 -07001579 /* disable and enable BT when detect a user switch */
1580 if (mEnable && mBluetooth != null) {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001581 try {
1582 mBluetoothLock.readLock().lock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001583 if (mBluetooth != null) {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001584 mBluetooth.unregisterCallback(mBluetoothCallback);
Zhihai Xu40874a02012-10-08 17:57:03 -07001585 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001586 } catch (RemoteException re) {
1587 Slog.e(TAG, "Unable to unregister", re);
1588 } finally {
1589 mBluetoothLock.readLock().unlock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001590 }
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001591
1592 if (mState == BluetoothAdapter.STATE_TURNING_OFF) {
1593 // MESSAGE_USER_SWITCHED happened right after MESSAGE_ENABLE
1594 bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_OFF);
1595 mState = BluetoothAdapter.STATE_OFF;
1596 }
1597 if (mState == BluetoothAdapter.STATE_OFF) {
1598 bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_TURNING_ON);
1599 mState = BluetoothAdapter.STATE_TURNING_ON;
1600 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001601
1602 waitForOnOff(true, false);
1603
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001604 if (mState == BluetoothAdapter.STATE_TURNING_ON) {
1605 bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_ON);
1606 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001607
Benjamin Franze8b98922014-11-12 15:57:54 +00001608 unbindAllBluetoothProfileServices();
Zhihai Xu40874a02012-10-08 17:57:03 -07001609 // disable
Zhihai Xu401202b2012-12-03 11:36:21 -08001610 handleDisable();
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001611 // Pbap service need receive STATE_TURNING_OFF intent to close
1612 bluetoothStateChangeHandler(BluetoothAdapter.STATE_ON,
1613 BluetoothAdapter.STATE_TURNING_OFF);
Zhihai Xu40874a02012-10-08 17:57:03 -07001614
Pavlin Radoslavov41401112016-06-27 15:25:18 -07001615 boolean didDisableTimeout = !waitForOnOff(false, true);
Zhihai Xu40874a02012-10-08 17:57:03 -07001616
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001617 bluetoothStateChangeHandler(BluetoothAdapter.STATE_TURNING_OFF,
Zhihai Xu40874a02012-10-08 17:57:03 -07001618 BluetoothAdapter.STATE_OFF);
Zhihai Xu40874a02012-10-08 17:57:03 -07001619 sendBluetoothServiceDownCallback();
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001620
Pavlin Radoslavove957a8a2016-05-24 15:28:41 -07001621 try {
1622 mBluetoothLock.writeLock().lock();
1623 if (mBluetooth != null) {
1624 mBluetooth = null;
1625 // Unbind
1626 mContext.unbindService(mConnection);
1627 }
1628 mBluetoothGatt = null;
1629 } finally {
1630 mBluetoothLock.writeLock().unlock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001631 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001632
Pavlin Radoslavov41401112016-06-27 15:25:18 -07001633 //
1634 // If disabling Bluetooth times out, wait for an
1635 // additional amount of time to ensure the process is
1636 // shut down completely before attempting to restart.
1637 //
1638 if (didDisableTimeout) {
1639 SystemClock.sleep(3000);
1640 } else {
1641 SystemClock.sleep(100);
1642 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001643
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001644 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
1645 mState = BluetoothAdapter.STATE_OFF;
Zhihai Xu40874a02012-10-08 17:57:03 -07001646 // enable
Zhihai Xu401202b2012-12-03 11:36:21 -08001647 handleEnable(mQuietEnable);
John Spurlock8a985d22014-02-25 09:40:05 -05001648 } else if (mBinding || mBluetooth != null) {
Zhihai Xu40874a02012-10-08 17:57:03 -07001649 Message userMsg = mHandler.obtainMessage(MESSAGE_USER_SWITCHED);
1650 userMsg.arg2 = 1 + msg.arg2;
Marie Janssenffcf88f2016-12-13 10:51:02 -08001651 // if user is switched when service is binding retry after a delay
Zhihai Xu40874a02012-10-08 17:57:03 -07001652 mHandler.sendMessageDelayed(userMsg, USER_SWITCHED_TIME_MS);
1653 if (DBG) {
Marie Janssenffcf88f2016-12-13 10:51:02 -08001654 Slog.d(TAG, "Retry MESSAGE_USER_SWITCHED " + userMsg.arg2);
Zhihai Xu40874a02012-10-08 17:57:03 -07001655 }
John Spurlock8a985d22014-02-25 09:40:05 -05001656 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001657 break;
1658 }
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001659 case MESSAGE_USER_UNLOCKED: {
1660 if (DBG) Slog.d(TAG, "MESSAGE_USER_UNLOCKED");
1661 mHandler.removeMessages(MESSAGE_USER_SWITCHED);
1662
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001663 if (mEnable && !mBinding && (mBluetooth == null)) {
1664 // We should be connected, but we gave up for some
1665 // reason; maybe the Bluetooth service wasn't encryption
1666 // aware, so try binding again.
1667 if (DBG) Slog.d(TAG, "Enabled but not bound; retrying after unlock");
1668 handleEnable(mQuietEnable);
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001669 }
1670 }
fredc0f420372012-04-12 00:02:00 -07001671 }
1672 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001673 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001674
Zhihai Xu401202b2012-12-03 11:36:21 -08001675 private void handleEnable(boolean quietMode) {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001676 mQuietEnable = quietMode;
1677
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001678 try {
1679 mBluetoothLock.writeLock().lock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001680 if ((mBluetooth == null) && (!mBinding)) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001681 //Start bind timeout and bind
1682 Message timeoutMsg=mHandler.obtainMessage(MESSAGE_TIMEOUT_BIND);
1683 mHandler.sendMessageDelayed(timeoutMsg,TIMEOUT_BIND_MS);
Matthew Xiecdce0b92012-07-12 19:06:15 -07001684 Intent i = new Intent(IBluetooth.class.getName());
Dianne Hackbornce09f5a2014-10-10 15:03:13 -07001685 if (!doBind(i, mConnection,Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT,
1686 UserHandle.CURRENT)) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001687 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
Zhihai Xu40874a02012-10-08 17:57:03 -07001688 } else {
1689 mBinding = true;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001690 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001691 } else if (mBluetooth != null) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001692 //Enable bluetooth
1693 try {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001694 if (!mQuietEnable) {
1695 if(!mBluetooth.enable()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001696 Slog.e(TAG,"IBluetooth.enable() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001697 }
1698 }
1699 else {
1700 if(!mBluetooth.enableNoAutoConnect()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001701 Slog.e(TAG,"IBluetooth.enableNoAutoConnect() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001702 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001703 }
1704 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001705 Slog.e(TAG,"Unable to call enable()",e);
Matthew Xiecdce0b92012-07-12 19:06:15 -07001706 }
1707 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001708 } finally {
1709 mBluetoothLock.writeLock().unlock();
Matthew Xiecdce0b92012-07-12 19:06:15 -07001710 }
1711 }
1712
Dianne Hackborn221ea892013-08-04 16:50:16 -07001713 boolean doBind(Intent intent, ServiceConnection conn, int flags, UserHandle user) {
1714 ComponentName comp = intent.resolveSystemService(mContext.getPackageManager(), 0);
1715 intent.setComponent(comp);
1716 if (comp == null || !mContext.bindServiceAsUser(intent, conn, flags, user)) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001717 Slog.e(TAG, "Fail to bind to: " + intent);
Dianne Hackborn221ea892013-08-04 16:50:16 -07001718 return false;
1719 }
1720 return true;
1721 }
1722
Zhihai Xu401202b2012-12-03 11:36:21 -08001723 private void handleDisable() {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001724 try {
1725 mBluetoothLock.readLock().lock();
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001726 if (mBluetooth != null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001727 if (DBG) Slog.d(TAG,"Sending off request.");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001728 if (!mBluetooth.disable()) {
1729 Slog.e(TAG,"IBluetooth.disable() returned false");
Matthew Xiecdce0b92012-07-12 19:06:15 -07001730 }
1731 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001732 } catch (RemoteException e) {
1733 Slog.e(TAG,"Unable to call disable()",e);
1734 } finally {
1735 mBluetoothLock.readLock().unlock();
Matthew Xiecdce0b92012-07-12 19:06:15 -07001736 }
1737 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001738
1739 private boolean checkIfCallerIsForegroundUser() {
1740 int foregroundUser;
1741 int callingUser = UserHandle.getCallingUserId();
Martijn Coenen8385c5a2012-11-29 10:14:16 -08001742 int callingUid = Binder.getCallingUid();
Zhihai Xu40874a02012-10-08 17:57:03 -07001743 long callingIdentity = Binder.clearCallingIdentity();
Benjamin Franze8b98922014-11-12 15:57:54 +00001744 UserManager um = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
1745 UserInfo ui = um.getProfileParent(callingUser);
1746 int parentUser = (ui != null) ? ui.id : UserHandle.USER_NULL;
Martijn Coenen8385c5a2012-11-29 10:14:16 -08001747 int callingAppId = UserHandle.getAppId(callingUid);
Zhihai Xu40874a02012-10-08 17:57:03 -07001748 boolean valid = false;
1749 try {
1750 foregroundUser = ActivityManager.getCurrentUser();
Martijn Coenen8385c5a2012-11-29 10:14:16 -08001751 valid = (callingUser == foregroundUser) ||
Benjamin Franze8b98922014-11-12 15:57:54 +00001752 parentUser == foregroundUser ||
Adrian Roosbd9a9a52014-08-18 15:31:57 +02001753 callingAppId == Process.NFC_UID ||
1754 callingAppId == mSystemUiUid;
Marie Janssenffcf88f2016-12-13 10:51:02 -08001755 if (DBG && !valid) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001756 Slog.d(TAG, "checkIfCallerIsForegroundUser: valid=" + valid
Zhihai Xu40874a02012-10-08 17:57:03 -07001757 + " callingUser=" + callingUser
Benjamin Franze8b98922014-11-12 15:57:54 +00001758 + " parentUser=" + parentUser
Zhihai Xu40874a02012-10-08 17:57:03 -07001759 + " foregroundUser=" + foregroundUser);
1760 }
1761 } finally {
1762 Binder.restoreCallingIdentity(callingIdentity);
1763 }
1764 return valid;
1765 }
1766
Nitin Arorad055adb2015-03-02 15:03:51 -08001767 private void sendBleStateChanged(int prevState, int newState) {
Marie Janssenffcf88f2016-12-13 10:51:02 -08001768 if (DBG) Slog.d(TAG,"Sending BLE State Change: " + BluetoothAdapter.nameForState(prevState) +
1769 " > " + BluetoothAdapter.nameForState(newState));
Nitin Arorad055adb2015-03-02 15:03:51 -08001770 // Send broadcast message to everyone else
1771 Intent intent = new Intent(BluetoothAdapter.ACTION_BLE_STATE_CHANGED);
1772 intent.putExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE, prevState);
1773 intent.putExtra(BluetoothAdapter.EXTRA_STATE, newState);
1774 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1775 mContext.sendBroadcastAsUser(intent, UserHandle.ALL, BLUETOOTH_PERM);
1776 }
1777
Zhihai Xu40874a02012-10-08 17:57:03 -07001778 private void bluetoothStateChangeHandler(int prevState, int newState) {
Nitin Arorad055adb2015-03-02 15:03:51 -08001779 boolean isStandardBroadcast = true;
Marie Janssenffcf88f2016-12-13 10:51:02 -08001780 if (prevState == newState) { // No change. Nothing to do.
1781 return;
1782 }
1783 // Notify all proxy objects first of adapter state change
1784 if (newState == BluetoothAdapter.STATE_BLE_ON ||
1785 newState == BluetoothAdapter.STATE_OFF) {
1786 boolean intermediate_off = (prevState == BluetoothAdapter.STATE_TURNING_OFF
1787 && newState == BluetoothAdapter.STATE_BLE_ON);
Zhihai Xu40874a02012-10-08 17:57:03 -07001788
Marie Janssenffcf88f2016-12-13 10:51:02 -08001789 if (newState == BluetoothAdapter.STATE_OFF) {
1790 // If Bluetooth is off, send service down event to proxy objects, and unbind
1791 if (DBG) Slog.d(TAG, "Bluetooth is complete send Service Down");
1792 sendBluetoothServiceDownCallback();
1793 unbindAndFinish();
Nitin Arorad055adb2015-03-02 15:03:51 -08001794 sendBleStateChanged(prevState, newState);
Marie Janssenffcf88f2016-12-13 10:51:02 -08001795 // Don't broadcast as it has already been broadcast before
Nitin Arorad055adb2015-03-02 15:03:51 -08001796 isStandardBroadcast = false;
1797
Marie Janssenffcf88f2016-12-13 10:51:02 -08001798 } else if (!intermediate_off) {
1799 // connect to GattService
1800 if (DBG) Slog.d(TAG, "Bluetooth is in LE only mode");
1801 if (mBluetoothGatt != null) {
1802 if (DBG) Slog.d(TAG, "Calling BluetoothGattServiceUp");
1803 onBluetoothGattServiceUp();
1804 } else {
1805 if (DBG) Slog.d(TAG, "Binding Bluetooth GATT service");
1806 if (mContext.getPackageManager().hasSystemFeature(
1807 PackageManager.FEATURE_BLUETOOTH_LE)) {
1808 Intent i = new Intent(IBluetoothGatt.class.getName());
1809 doBind(i, mConnection, Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT, UserHandle.CURRENT);
1810 }
Nitin Arorad055adb2015-03-02 15:03:51 -08001811 }
Marie Janssenffcf88f2016-12-13 10:51:02 -08001812 sendBleStateChanged(prevState, newState);
1813 //Don't broadcase this as std intent
1814 isStandardBroadcast = false;
1815
1816 } else if (intermediate_off) {
1817 if (DBG) Slog.d(TAG, "Intermediate off, back to LE only mode");
1818 // For LE only mode, broadcast as is
1819 sendBleStateChanged(prevState, newState);
1820 sendBluetoothStateCallback(false); // BT is OFF for general users
1821 // Broadcast as STATE_OFF
1822 newState = BluetoothAdapter.STATE_OFF;
1823 sendBrEdrDownCallback();
Nitin Arorad055adb2015-03-02 15:03:51 -08001824 }
Marie Janssenffcf88f2016-12-13 10:51:02 -08001825 } else if (newState == BluetoothAdapter.STATE_ON) {
1826 boolean isUp = (newState == BluetoothAdapter.STATE_ON);
1827 sendBluetoothStateCallback(isUp);
1828 sendBleStateChanged(prevState, newState);
1829
1830 } else if (newState == BluetoothAdapter.STATE_BLE_TURNING_ON ||
1831 newState == BluetoothAdapter.STATE_BLE_TURNING_OFF ) {
1832 sendBleStateChanged(prevState, newState);
1833 isStandardBroadcast = false;
1834
1835 } else if (newState == BluetoothAdapter.STATE_TURNING_ON ||
1836 newState == BluetoothAdapter.STATE_TURNING_OFF) {
1837 sendBleStateChanged(prevState, newState);
1838 }
1839
1840 if (isStandardBroadcast) {
1841 if (prevState == BluetoothAdapter.STATE_BLE_ON) {
1842 // Show prevState of BLE_ON as OFF to standard users
1843 prevState = BluetoothAdapter.STATE_OFF;
1844 }
1845 Intent intent = new Intent(BluetoothAdapter.ACTION_STATE_CHANGED);
1846 intent.putExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE, prevState);
1847 intent.putExtra(BluetoothAdapter.EXTRA_STATE, newState);
1848 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1849 mContext.sendBroadcastAsUser(intent, UserHandle.ALL, BLUETOOTH_PERM);
Zhihai Xu40874a02012-10-08 17:57:03 -07001850 }
1851 }
1852
1853 /**
1854 * if on is true, wait for state become ON
1855 * if off is true, wait for state become OFF
1856 * if both on and off are false, wait for state not ON
1857 */
1858 private boolean waitForOnOff(boolean on, boolean off) {
1859 int i = 0;
1860 while (i < 10) {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001861 try {
1862 mBluetoothLock.readLock().lock();
1863 if (mBluetooth == null) break;
1864 if (on) {
1865 if (mBluetooth.getState() == BluetoothAdapter.STATE_ON) return true;
1866 } else if (off) {
1867 if (mBluetooth.getState() == BluetoothAdapter.STATE_OFF) return true;
1868 } else {
1869 if (mBluetooth.getState() != BluetoothAdapter.STATE_ON) return true;
Zhihai Xu40874a02012-10-08 17:57:03 -07001870 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001871 } catch (RemoteException e) {
1872 Slog.e(TAG, "getState()", e);
1873 break;
1874 } finally {
1875 mBluetoothLock.readLock().unlock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001876 }
1877 if (on || off) {
1878 SystemClock.sleep(300);
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07001879 } else {
Zhihai Xu40874a02012-10-08 17:57:03 -07001880 SystemClock.sleep(50);
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07001881 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001882 i++;
1883 }
Jeff Sharkey67609c72016-03-05 14:29:13 -07001884 Slog.e(TAG,"waitForOnOff time out");
Zhihai Xu40874a02012-10-08 17:57:03 -07001885 return false;
1886 }
Zhihai Xu681ae7f2012-11-12 15:14:18 -08001887
Marie Janssena50cc712016-12-28 14:13:21 -08001888 private void sendDisableMsg(String packageName) {
Zhihai Xu401202b2012-12-03 11:36:21 -08001889 mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_DISABLE));
Marie Janssena50cc712016-12-28 14:13:21 -08001890 addActiveLog(packageName, false);
Zhihai Xu401202b2012-12-03 11:36:21 -08001891 }
1892
Marie Janssena50cc712016-12-28 14:13:21 -08001893 private void sendEnableMsg(boolean quietMode, String packageName) {
Zhihai Xu401202b2012-12-03 11:36:21 -08001894 mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_ENABLE,
1895 quietMode ? 1 : 0, 0));
Marie Janssena50cc712016-12-28 14:13:21 -08001896 addActiveLog(packageName, true);
1897 }
1898
1899 private void addActiveLog(String packageName, boolean enable) {
1900 synchronized (mActiveLogs) {
1901 if (mActiveLogs.size() > 10) {
1902 mActiveLogs.remove();
1903 }
1904 mActiveLogs.add(new ActiveLog(packageName, enable, System.currentTimeMillis()));
1905 }
Zhihai Xu401202b2012-12-03 11:36:21 -08001906 }
1907
Marie Janssen6689f332016-11-09 12:01:24 -08001908 private void recoverBluetoothServiceFromError(boolean clearBle) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001909 Slog.e(TAG,"recoverBluetoothServiceFromError");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001910 try {
1911 mBluetoothLock.readLock().lock();
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001912 if (mBluetooth != null) {
1913 //Unregister callback object
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001914 mBluetooth.unregisterCallback(mBluetoothCallback);
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001915 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001916 } catch (RemoteException re) {
1917 Slog.e(TAG, "Unable to unregister", re);
1918 } finally {
1919 mBluetoothLock.readLock().unlock();
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001920 }
1921
1922 SystemClock.sleep(500);
1923
1924 // disable
1925 handleDisable();
1926
1927 waitForOnOff(false, true);
1928
1929 sendBluetoothServiceDownCallback();
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001930
Pavlin Radoslavove957a8a2016-05-24 15:28:41 -07001931 try {
1932 mBluetoothLock.writeLock().lock();
1933 if (mBluetooth != null) {
1934 mBluetooth = null;
1935 // Unbind
1936 mContext.unbindService(mConnection);
1937 }
1938 mBluetoothGatt = null;
1939 } finally {
1940 mBluetoothLock.writeLock().unlock();
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001941 }
1942
1943 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
1944 mState = BluetoothAdapter.STATE_OFF;
1945
Marie Janssen6689f332016-11-09 12:01:24 -08001946 if (clearBle) {
1947 clearBleApps();
1948 }
1949
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001950 mEnable = false;
1951
1952 if (mErrorRecoveryRetryCounter++ < MAX_ERROR_RESTART_RETRIES) {
1953 // Send a Bluetooth Restart message to reenable bluetooth
1954 Message restartMsg = mHandler.obtainMessage(
1955 MESSAGE_RESTART_BLUETOOTH_SERVICE);
1956 mHandler.sendMessageDelayed(restartMsg, ERROR_RESTART_TIME_MS);
1957 } else {
1958 // todo: notify user to power down and power up phone to make bluetooth work.
1959 }
1960 }
Mike Lockwood726d4de2014-10-28 14:06:28 -07001961
1962 @Override
Pavlin Radoslavov6e8faff2016-02-23 11:54:37 -08001963 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1964 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DUMP, TAG);
1965 String errorMsg = null;
Marie Janssena50cc712016-12-28 14:13:21 -08001966
1967 boolean protoOut = (args.length > 0) && args[0].startsWith("--proto");
1968
1969 if (!protoOut) {
1970 writer.println("Bluetooth Status");
1971 writer.println(" enabled: " + isEnabled());
1972 writer.println(" state: " + BluetoothAdapter.nameForState(mState));
1973 writer.println(" address: " + mAddress);
1974 writer.println(" name: " + mName);
1975 if (mEnable) {
1976 long onDuration = System.currentTimeMillis() - mActiveLogs.getLast().getTime();
1977 String onDurationString = String.format("%02d:%02d:%02d.%03d",
1978 (int)(onDuration / (1000 * 60 * 60)),
1979 (int)((onDuration / (1000 * 60)) % 60),
1980 (int)((onDuration / 1000) % 60),
1981 (int)(onDuration % 1000));
1982 writer.println(" time since enabled: " + onDurationString + "\n");
1983 }
1984
1985 writer.println("Enable log:");
1986 for (ActiveLog log : mActiveLogs) {
1987 writer.println(log);
1988 }
1989
1990 writer.println("\n" + mBleApps.size() + " BLE Apps registered:");
1991 for (ClientDeathRecipient app : mBleApps.values()) {
1992 writer.println(app.getPackageName());
1993 }
1994
1995 writer.flush();
1996 }
1997
Pavlin Radoslavov6e8faff2016-02-23 11:54:37 -08001998 if (mBluetoothBinder == null) {
1999 errorMsg = "Bluetooth Service not connected";
2000 } else {
2001 try {
2002 mBluetoothBinder.dump(fd, args);
2003 } catch (RemoteException re) {
Marie Janssena50cc712016-12-28 14:13:21 -08002004 errorMsg = "RemoteException while dumping Bluetooth Service";
Pavlin Radoslavov6e8faff2016-02-23 11:54:37 -08002005 }
Mike Lockwood726d4de2014-10-28 14:06:28 -07002006 }
Pavlin Radoslavov6e8faff2016-02-23 11:54:37 -08002007 if (errorMsg != null) {
2008 // Silently return if we are extracting metrics in Protobuf format
Marie Janssena50cc712016-12-28 14:13:21 -08002009 if (protoOut) return;
Pavlin Radoslavov6e8faff2016-02-23 11:54:37 -08002010 writer.println(errorMsg);
2011 }
Mike Lockwood726d4de2014-10-28 14:06:28 -07002012 }
fredc0f420372012-04-12 00:02:00 -07002013}