blob: adc59de87f23af772d658d456b2b1e39d76e18c5 [file] [log] [blame]
fredc0f420372012-04-12 00:02:00 -07001/*
Zhihai Xufa0fd392012-10-23 17:31:56 -07002 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
fredc0f420372012-04-12 00:02:00 -070015 */
16
17package com.android.server;
18
Svet Ganov408abf72015-05-12 19:13:36 -070019import android.Manifest;
Zhihai Xu40874a02012-10-08 17:57:03 -070020import android.app.ActivityManager;
fredc0f420372012-04-12 00:02:00 -070021import android.bluetooth.BluetoothAdapter;
Benjamin Franze8b98922014-11-12 15:57:54 +000022import android.bluetooth.BluetoothProfile;
fredc0f420372012-04-12 00:02:00 -070023import android.bluetooth.IBluetooth;
fredcbf072a72012-05-09 16:52:50 -070024import android.bluetooth.IBluetoothCallback;
Wei Wange4a744b2015-06-11 17:50:29 -070025import android.bluetooth.IBluetoothGatt;
Benjamin Franze8b98922014-11-12 15:57:54 +000026import android.bluetooth.IBluetoothHeadset;
fredc0f420372012-04-12 00:02:00 -070027import android.bluetooth.IBluetoothManager;
28import android.bluetooth.IBluetoothManagerCallback;
Benjamin Franze8b98922014-11-12 15:57:54 +000029import android.bluetooth.IBluetoothProfileServiceConnection;
fredc0f420372012-04-12 00:02:00 -070030import android.bluetooth.IBluetoothStateChangeCallback;
fredc0f420372012-04-12 00:02:00 -070031import android.content.BroadcastReceiver;
32import android.content.ComponentName;
33import android.content.ContentResolver;
34import android.content.Context;
35import android.content.Intent;
36import android.content.IntentFilter;
37import android.content.ServiceConnection;
Svetoslav Ganovc2ac5bd2016-06-29 17:31:44 -070038import android.content.pm.ApplicationInfo;
Matthew Xie32ab77b2013-05-08 19:26:57 -070039import android.content.pm.PackageManager;
Benjamin Franze8b98922014-11-12 15:57:54 +000040import android.content.pm.UserInfo;
Wei Wange4a744b2015-06-11 17:50:29 -070041import android.database.ContentObserver;
Zhihai Xu40874a02012-10-08 17:57:03 -070042import android.os.Binder;
Lenka Trochtova13a05192016-12-02 12:19:39 +010043import android.os.Bundle;
Svetoslav Ganovc2ac5bd2016-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;
Lenka Trochtova13a05192016-12-02 12:19:39 +010055import android.os.UserManagerInternal;
56import android.os.UserManagerInternal.UserRestrictionsListener;
fredc0f420372012-04-12 00:02:00 -070057import android.provider.Settings;
Wei Wang67d84162015-04-26 17:04:29 -070058import android.provider.Settings.SettingNotFoundException;
Jeff Sharkey67609c72016-03-05 14:29:13 -070059import android.util.Slog;
Mike Lockwood726d4de2014-10-28 14:06:28 -070060
61import java.io.FileDescriptor;
62import java.io.PrintWriter;
Marie Janssen2977c3e2016-11-09 12:01:24 -080063import java.util.concurrent.ConcurrentHashMap;
Marie Janssen59804562016-12-28 14:13:21 -080064import java.util.concurrent.locks.ReentrantReadWriteLock;
Benjamin Franze8b98922014-11-12 15:57:54 +000065import java.util.HashMap;
Marie Janssen59804562016-12-28 14:13:21 -080066import java.util.LinkedList;
Benjamin Franze8b98922014-11-12 15:57:54 +000067import java.util.Map;
Miao Chou658bf2f2015-06-26 17:14:35 -070068
Marie Janssen59804562016-12-28 14:13:21 -080069
fredc0f420372012-04-12 00:02:00 -070070class BluetoothManagerService extends IBluetoothManager.Stub {
71 private static final String TAG = "BluetoothManagerService";
Pavlin Radoslavov41401112016-06-27 15:25:18 -070072 private static final boolean DBG = true;
fredc0f420372012-04-12 00:02:00 -070073
fredc0f420372012-04-12 00:02:00 -070074 private static final String BLUETOOTH_ADMIN_PERM = android.Manifest.permission.BLUETOOTH_ADMIN;
75 private static final String BLUETOOTH_PERM = android.Manifest.permission.BLUETOOTH;
fredc0f420372012-04-12 00:02:00 -070076 private static final String ACTION_SERVICE_STATE_CHANGED="com.android.bluetooth.btservice.action.STATE_CHANGED";
77 private static final String EXTRA_ACTION="action";
Zhihai Xud31c3222012-10-31 16:08:57 -070078 private static final String SECURE_SETTINGS_BLUETOOTH_ADDR_VALID="bluetooth_addr_valid";
fredc0f420372012-04-12 00:02:00 -070079 private static final String SECURE_SETTINGS_BLUETOOTH_ADDRESS="bluetooth_address";
80 private static final String SECURE_SETTINGS_BLUETOOTH_NAME="bluetooth_name";
fredc0f420372012-04-12 00:02:00 -070081 private static final int TIMEOUT_BIND_MS = 3000; //Maximum msec to wait for a bind
82 private static final int TIMEOUT_SAVE_MS = 500; //Maximum msec to wait for a save
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +053083 //Maximum msec to wait for service restart
84 private static final int SERVICE_RESTART_TIME_MS = 200;
Zhihai Xudd9d17d2013-01-08 17:05:58 -080085 //Maximum msec to wait for restart due to error
86 private static final int ERROR_RESTART_TIME_MS = 3000;
Zhihai Xu40874a02012-10-08 17:57:03 -070087 //Maximum msec to delay MESSAGE_USER_SWITCHED
88 private static final int USER_SWITCHED_TIME_MS = 200;
Benjamin Franze8b98922014-11-12 15:57:54 +000089 // Delay for the addProxy function in msec
90 private static final int ADD_PROXY_DELAY_MS = 100;
fredc0f420372012-04-12 00:02:00 -070091
92 private static final int MESSAGE_ENABLE = 1;
93 private static final int MESSAGE_DISABLE = 2;
fredc649fe492012-04-19 01:07:18 -070094 private static final int MESSAGE_REGISTER_ADAPTER = 20;
95 private static final int MESSAGE_UNREGISTER_ADAPTER = 21;
96 private static final int MESSAGE_REGISTER_STATE_CHANGE_CALLBACK = 30;
97 private static final int MESSAGE_UNREGISTER_STATE_CHANGE_CALLBACK = 31;
98 private static final int MESSAGE_BLUETOOTH_SERVICE_CONNECTED = 40;
99 private static final int MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED = 41;
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +0530100 private static final int MESSAGE_RESTART_BLUETOOTH_SERVICE = 42;
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -0700101 private static final int MESSAGE_BLUETOOTH_STATE_CHANGE = 60;
102 private static final int MESSAGE_TIMEOUT_BIND = 100;
103 private static final int MESSAGE_TIMEOUT_UNBIND = 101;
Ajay Panicker4bb48302016-03-31 14:14:27 -0700104 private static final int MESSAGE_GET_NAME_AND_ADDRESS = 200;
Zhihai Xu40874a02012-10-08 17:57:03 -0700105 private static final int MESSAGE_USER_SWITCHED = 300;
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -0700106 private static final int MESSAGE_USER_UNLOCKED = 301;
Benjamin Franze8b98922014-11-12 15:57:54 +0000107 private static final int MESSAGE_ADD_PROXY_DELAYED = 400;
108 private static final int MESSAGE_BIND_PROFILE_SERVICE = 401;
Marie Janssencb21ad72016-12-13 10:51:02 -0800109
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -0700110 private static final int MAX_SAVE_RETRIES = 3;
111 private static final int MAX_ERROR_RESTART_RETRIES = 6;
Zhihai Xudd9d17d2013-01-08 17:05:58 -0800112
Zhihai Xu401202b2012-12-03 11:36:21 -0800113 // Bluetooth persisted setting is off
114 private static final int BLUETOOTH_OFF=0;
115 // Bluetooth persisted setting is on
116 // and Airplane mode won't affect Bluetooth state at start up
117 private static final int BLUETOOTH_ON_BLUETOOTH=1;
118 // Bluetooth persisted setting is on
119 // but Airplane mode will affect Bluetooth state at start up
120 // and Airplane mode will have higher priority.
121 private static final int BLUETOOTH_ON_AIRPLANE=2;
fredc0f420372012-04-12 00:02:00 -0700122
Matthew Xieddf7e472013-03-01 18:41:02 -0800123 private static final int SERVICE_IBLUETOOTH = 1;
124 private static final int SERVICE_IBLUETOOTHGATT = 2;
125
fredc0f420372012-04-12 00:02:00 -0700126 private final Context mContext;
Matthew Xiecdce0b92012-07-12 19:06:15 -0700127
128 // Locks are not provided for mName and mAddress.
129 // They are accessed in handler or broadcast receiver, same thread context.
fredc0f420372012-04-12 00:02:00 -0700130 private String mAddress;
131 private String mName;
Matthew Xie6fde3092012-07-11 17:10:07 -0700132 private final ContentResolver mContentResolver;
133 private final RemoteCallbackList<IBluetoothManagerCallback> mCallbacks;
134 private final RemoteCallbackList<IBluetoothStateChangeCallback> mStateChangeCallbacks;
Marie Janssen9db28eb2016-01-12 16:05:15 -0800135 private IBinder mBluetoothBinder;
fredc649fe492012-04-19 01:07:18 -0700136 private IBluetooth mBluetooth;
Matthew Xieddf7e472013-03-01 18:41:02 -0800137 private IBluetoothGatt mBluetoothGatt;
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700138 private final ReentrantReadWriteLock mBluetoothLock =
139 new ReentrantReadWriteLock();
fredc649fe492012-04-19 01:07:18 -0700140 private boolean mBinding;
141 private boolean mUnbinding;
Marie Janssen59804562016-12-28 14:13:21 -0800142
Zhihai Xu401202b2012-12-03 11:36:21 -0800143 // used inside handler thread
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700144 private boolean mQuietEnable = false;
Marie Janssen59804562016-12-28 14:13:21 -0800145 private boolean mEnable;
146
147 /**
148 * Used for tracking apps that enabled / disabled Bluetooth.
149 */
150 private class ActiveLog {
151 private String mPackageName;
152 private boolean mEnable;
153 private long mTimestamp;
154
155 public ActiveLog(String packageName, boolean enable, long timestamp) {
156 mPackageName = packageName;
157 mEnable = enable;
158 mTimestamp = timestamp;
159 }
160
161 public long getTime() {
162 return mTimestamp;
163 }
164
165 public String toString() {
166 return android.text.format.DateFormat.format("MM-dd hh:mm:ss ", mTimestamp) +
167 (mEnable ? " Enabled " : " Disabled ") + " by " + mPackageName;
168 }
169
170 }
171
172 private LinkedList<ActiveLog> mActiveLogs;
173
174 // configuration from external IBinder call which is used to
Zhihai Xu401202b2012-12-03 11:36:21 -0800175 // synchronize with broadcast receiver.
176 private boolean mQuietEnableExternal;
Zhihai Xu401202b2012-12-03 11:36:21 -0800177 private boolean mEnableExternal;
Marie Janssen59804562016-12-28 14:13:21 -0800178
179 // Map of apps registered to keep BLE scanning on.
180 private Map<IBinder, ClientDeathRecipient> mBleApps = new ConcurrentHashMap<IBinder, ClientDeathRecipient>();
181
Zhihai Xu40874a02012-10-08 17:57:03 -0700182 private int mState;
Zhihai Xu40874a02012-10-08 17:57:03 -0700183 private final BluetoothHandler mHandler;
Zhihai Xudd9d17d2013-01-08 17:05:58 -0800184 private int mErrorRecoveryRetryCounter;
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200185 private final int mSystemUiUid;
fredc0f420372012-04-12 00:02:00 -0700186
Benjamin Franze8b98922014-11-12 15:57:54 +0000187 // Save a ProfileServiceConnections object for each of the bound
188 // bluetooth profile services
189 private final Map <Integer, ProfileServiceConnections> mProfileServices =
190 new HashMap <Integer, ProfileServiceConnections>();
191
Svetoslav Ganovc2ac5bd2016-06-29 17:31:44 -0700192 private final boolean mPermissionReviewRequired;
193
fredc649fe492012-04-19 01:07:18 -0700194 private void registerForAirplaneMode(IntentFilter filter) {
195 final ContentResolver resolver = mContext.getContentResolver();
Christopher Tatec09cdce2012-09-10 16:50:14 -0700196 final String airplaneModeRadios = Settings.Global.getString(resolver,
197 Settings.Global.AIRPLANE_MODE_RADIOS);
198 final String toggleableRadios = Settings.Global.getString(resolver,
199 Settings.Global.AIRPLANE_MODE_TOGGLEABLE_RADIOS);
fredc649fe492012-04-19 01:07:18 -0700200 boolean mIsAirplaneSensitive = airplaneModeRadios == null ? true :
Christopher Tatec09cdce2012-09-10 16:50:14 -0700201 airplaneModeRadios.contains(Settings.Global.RADIO_BLUETOOTH);
fredc649fe492012-04-19 01:07:18 -0700202 if (mIsAirplaneSensitive) {
203 filter.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED);
204 }
205 }
206
Marie Janssen59804562016-12-28 14:13:21 -0800207 private final IBluetoothCallback mBluetoothCallback = new IBluetoothCallback.Stub() {
fredcbf072a72012-05-09 16:52:50 -0700208 @Override
209 public void onBluetoothStateChange(int prevState, int newState) throws RemoteException {
210 Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_STATE_CHANGE,prevState,newState);
211 mHandler.sendMessage(msg);
212 }
213 };
214
Lenka Trochtova13a05192016-12-02 12:19:39 +0100215 private final UserRestrictionsListener mUserRestrictionsListener =
216 new UserRestrictionsListener() {
217 @Override
218 public void onUserRestrictionsChanged(int userId, Bundle newRestrictions,
219 Bundle prevRestrictions) {
220 final boolean bluetoothDisallowed =
221 newRestrictions.getBoolean(UserManager.DISALLOW_BLUETOOTH);
222 if ((mEnable || mEnableExternal) && bluetoothDisallowed) {
Svetoslav Ganovc2ac5bd2016-06-29 17:31:44 -0700223 try {
224 disable("android.os.UserManagerInternal", true);
225 } catch (RemoteException e) {
226 // Shouldn't happen: startConsentUiIfNeeded not called
227 // when from system.
228 }
Lenka Trochtova13a05192016-12-02 12:19:39 +0100229 }
230 }
231 };
232
fredcbf072a72012-05-09 16:52:50 -0700233 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
fredc0f420372012-04-12 00:02:00 -0700234 @Override
235 public void onReceive(Context context, Intent intent) {
236 String action = intent.getAction();
fredcbf072a72012-05-09 16:52:50 -0700237 if (BluetoothAdapter.ACTION_LOCAL_NAME_CHANGED.equals(action)) {
fredc0f420372012-04-12 00:02:00 -0700238 String newName = intent.getStringExtra(BluetoothAdapter.EXTRA_LOCAL_NAME);
Jeff Sharkey67609c72016-03-05 14:29:13 -0700239 if (DBG) Slog.d(TAG, "Bluetooth Adapter name changed to " + newName);
fredc0f420372012-04-12 00:02:00 -0700240 if (newName != null) {
241 storeNameAndAddress(newName, null);
242 }
fredc649fe492012-04-19 01:07:18 -0700243 } else if (Intent.ACTION_AIRPLANE_MODE_CHANGED.equals(action)) {
Zhihai Xu401202b2012-12-03 11:36:21 -0800244 synchronized(mReceiver) {
245 if (isBluetoothPersistedStateOn()) {
246 if (isAirplaneModeOn()) {
247 persistBluetoothSetting(BLUETOOTH_ON_AIRPLANE);
248 } else {
249 persistBluetoothSetting(BLUETOOTH_ON_BLUETOOTH);
250 }
251 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800252
253 int st = BluetoothAdapter.STATE_OFF;
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700254 try {
255 mBluetoothLock.readLock().lock();
256 if (mBluetooth != null) {
Nitin Arorad055adb2015-03-02 15:03:51 -0800257 st = mBluetooth.getState();
Nitin Arorad055adb2015-03-02 15:03:51 -0800258 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700259 } catch (RemoteException e) {
260 Slog.e(TAG, "Unable to call getState", e);
261 } finally {
262 mBluetoothLock.readLock().unlock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800263 }
Marie Janssencb21ad72016-12-13 10:51:02 -0800264 Slog.d(TAG, "State " + BluetoothAdapter.nameForState(st));
Nitin Arorad055adb2015-03-02 15:03:51 -0800265
Zhihai Xu401202b2012-12-03 11:36:21 -0800266 if (isAirplaneModeOn()) {
Nitin Arorad055adb2015-03-02 15:03:51 -0800267 // Clear registered LE apps to force shut-off
Marie Janssen2977c3e2016-11-09 12:01:24 -0800268 clearBleApps();
Nitin Arorad055adb2015-03-02 15:03:51 -0800269 if (st == BluetoothAdapter.STATE_BLE_ON) {
270 //if state is BLE_ON make sure you trigger disableBLE part
271 try {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700272 mBluetoothLock.readLock().lock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800273 if (mBluetooth != null) {
274 mBluetooth.onBrEdrDown();
Marie Janssen6a383a72016-10-25 10:47:51 -0700275 mEnable = false;
Nitin Arorad055adb2015-03-02 15:03:51 -0800276 mEnableExternal = false;
277 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700278 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700279 Slog.e(TAG,"Unable to call onBrEdrDown", e);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700280 } finally {
Pavlin Radoslavov7ee53be2016-06-09 12:58:07 -0700281 mBluetoothLock.readLock().unlock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800282 }
283 } else if (st == BluetoothAdapter.STATE_ON){
284 // disable without persisting the setting
Jeff Sharkey67609c72016-03-05 14:29:13 -0700285 Slog.d(TAG, "Calling disable");
Marie Janssen59804562016-12-28 14:13:21 -0800286 sendDisableMsg("airplane mode");
Nitin Arorad055adb2015-03-02 15:03:51 -0800287 }
Zhihai Xu401202b2012-12-03 11:36:21 -0800288 } else if (mEnableExternal) {
289 // enable without persisting the setting
Jeff Sharkey67609c72016-03-05 14:29:13 -0700290 Slog.d(TAG, "Calling enable");
Marie Janssen59804562016-12-28 14:13:21 -0800291 sendEnableMsg(mQuietEnableExternal, "airplane mode");
Zhihai Xu401202b2012-12-03 11:36:21 -0800292 }
fredc649fe492012-04-19 01:07:18 -0700293 }
fredc0f420372012-04-12 00:02:00 -0700294 }
295 }
296 };
297
298 BluetoothManagerService(Context context) {
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700299 mHandler = new BluetoothHandler(IoThread.get().getLooper());
Zhihai Xu40874a02012-10-08 17:57:03 -0700300
fredc0f420372012-04-12 00:02:00 -0700301 mContext = context;
Svetoslav Ganovc2ac5bd2016-06-29 17:31:44 -0700302
303 mPermissionReviewRequired = Build.PERMISSIONS_REVIEW_REQUIRED
304 || context.getResources().getBoolean(
305 com.android.internal.R.bool.config_permissionReviewRequired);
306
Marie Janssen59804562016-12-28 14:13:21 -0800307 mActiveLogs = new LinkedList<ActiveLog>();
fredc0f420372012-04-12 00:02:00 -0700308 mBluetooth = null;
Marie Janssen9db28eb2016-01-12 16:05:15 -0800309 mBluetoothBinder = null;
Nitin Arorad055adb2015-03-02 15:03:51 -0800310 mBluetoothGatt = null;
fredc0f420372012-04-12 00:02:00 -0700311 mBinding = false;
312 mUnbinding = false;
Zhihai Xu40874a02012-10-08 17:57:03 -0700313 mEnable = false;
314 mState = BluetoothAdapter.STATE_OFF;
Zhihai Xu401202b2012-12-03 11:36:21 -0800315 mQuietEnableExternal = false;
316 mEnableExternal = false;
fredc0f420372012-04-12 00:02:00 -0700317 mAddress = null;
318 mName = null;
Zhihai Xudd9d17d2013-01-08 17:05:58 -0800319 mErrorRecoveryRetryCounter = 0;
fredc0f420372012-04-12 00:02:00 -0700320 mContentResolver = context.getContentResolver();
Wei Wange4a744b2015-06-11 17:50:29 -0700321 // Observe BLE scan only mode settings change.
322 registerForBleScanModeChange();
fredcd6883532012-04-25 17:46:13 -0700323 mCallbacks = new RemoteCallbackList<IBluetoothManagerCallback>();
324 mStateChangeCallbacks = new RemoteCallbackList<IBluetoothStateChangeCallback>();
Miao Chou658bf2f2015-06-26 17:14:35 -0700325 IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_LOCAL_NAME_CHANGED);
Matthew Xie6fde3092012-07-11 17:10:07 -0700326 registerForAirplaneMode(filter);
Dianne Hackbornd83a0962014-05-02 16:28:33 -0700327 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
Matthew Xie6fde3092012-07-11 17:10:07 -0700328 mContext.registerReceiver(mReceiver, filter);
fredc0f420372012-04-12 00:02:00 -0700329 loadStoredNameAndAddress();
Zhihai Xu401202b2012-12-03 11:36:21 -0800330 if (isBluetoothPersistedStateOn()) {
331 mEnableExternal = true;
fredc0f420372012-04-12 00:02:00 -0700332 }
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200333
Marie Janssen59804562016-12-28 14:13:21 -0800334 int systemUiUid = -1;
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200335 try {
Marie Janssen59804562016-12-28 14:13:21 -0800336 systemUiUid = mContext.getPackageManager().getPackageUidAsUser("com.android.systemui",
Jeff Sharkeyc5967e92016-01-07 18:50:29 -0700337 PackageManager.MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM);
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200338 } catch (PackageManager.NameNotFoundException e) {
Joe LaPennaacddf2b2015-09-04 12:52:42 -0700339 // Some platforms, such as wearables do not have a system ui.
Jeff Sharkey67609c72016-03-05 14:29:13 -0700340 Slog.w(TAG, "Unable to resolve SystemUI's UID.", e);
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200341 }
Marie Janssen59804562016-12-28 14:13:21 -0800342 mSystemUiUid = systemUiUid;
fredc0f420372012-04-12 00:02:00 -0700343 }
344
fredc649fe492012-04-19 01:07:18 -0700345 /**
346 * Returns true if airplane mode is currently on
347 */
348 private final boolean isAirplaneModeOn() {
Christopher Tatec09cdce2012-09-10 16:50:14 -0700349 return Settings.Global.getInt(mContext.getContentResolver(),
350 Settings.Global.AIRPLANE_MODE_ON, 0) == 1;
fredc649fe492012-04-19 01:07:18 -0700351 }
352
353 /**
354 * Returns true if the Bluetooth saved state is "on"
355 */
356 private final boolean isBluetoothPersistedStateOn() {
Jeff Brownbf6f6f92012-09-25 15:03:20 -0700357 return Settings.Global.getInt(mContentResolver,
Andre Eisenbach8c184312016-09-06 18:03:10 -0700358 Settings.Global.BLUETOOTH_ON, BLUETOOTH_ON_BLUETOOTH) != BLUETOOTH_OFF;
Zhihai Xu401202b2012-12-03 11:36:21 -0800359 }
360
361 /**
362 * Returns true if the Bluetooth saved state is BLUETOOTH_ON_BLUETOOTH
363 */
364 private final boolean isBluetoothPersistedStateOnBluetooth() {
365 return Settings.Global.getInt(mContentResolver,
Andre Eisenbach8c184312016-09-06 18:03:10 -0700366 Settings.Global.BLUETOOTH_ON, BLUETOOTH_ON_BLUETOOTH) == BLUETOOTH_ON_BLUETOOTH;
fredc649fe492012-04-19 01:07:18 -0700367 }
368
369 /**
370 * Save the Bluetooth on/off state
fredc649fe492012-04-19 01:07:18 -0700371 */
Zhihai Xu401202b2012-12-03 11:36:21 -0800372 private void persistBluetoothSetting(int value) {
Marie Janssened50bbc2016-12-15 13:51:30 -0800373 if (DBG) Slog.d(TAG, "Persisting Bluetooth Setting: " + value);
374 // waive WRITE_SECURE_SETTINGS permission check
375 long callingIdentity = Binder.clearCallingIdentity();
Jeff Brownbf6f6f92012-09-25 15:03:20 -0700376 Settings.Global.putInt(mContext.getContentResolver(),
377 Settings.Global.BLUETOOTH_ON,
Zhihai Xu401202b2012-12-03 11:36:21 -0800378 value);
Marie Janssened50bbc2016-12-15 13:51:30 -0800379 Binder.restoreCallingIdentity(callingIdentity);
fredc649fe492012-04-19 01:07:18 -0700380 }
381
382 /**
383 * Returns true if the Bluetooth Adapter's name and address is
384 * locally cached
385 * @return
386 */
fredc0f420372012-04-12 00:02:00 -0700387 private boolean isNameAndAddressSet() {
388 return mName !=null && mAddress!= null && mName.length()>0 && mAddress.length()>0;
389 }
390
fredc649fe492012-04-19 01:07:18 -0700391 /**
392 * Retrieve the Bluetooth Adapter's name and address and save it in
393 * in the local cache
394 */
fredc0f420372012-04-12 00:02:00 -0700395 private void loadStoredNameAndAddress() {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700396 if (DBG) Slog.d(TAG, "Loading stored name and address");
Zhihai Xud31c3222012-10-31 16:08:57 -0700397 if (mContext.getResources().getBoolean
398 (com.android.internal.R.bool.config_bluetooth_address_validation) &&
399 Settings.Secure.getInt(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDR_VALID, 0) == 0) {
400 // if the valid flag is not set, don't load the address and name
Jeff Sharkey67609c72016-03-05 14:29:13 -0700401 if (DBG) Slog.d(TAG, "invalid bluetooth name and address stored");
Zhihai Xud31c3222012-10-31 16:08:57 -0700402 return;
403 }
fredc0f420372012-04-12 00:02:00 -0700404 mName = Settings.Secure.getString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_NAME);
405 mAddress = Settings.Secure.getString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDRESS);
Jeff Sharkey67609c72016-03-05 14:29:13 -0700406 if (DBG) Slog.d(TAG, "Stored bluetooth Name=" + mName + ",Address=" + mAddress);
fredc0f420372012-04-12 00:02:00 -0700407 }
408
fredc649fe492012-04-19 01:07:18 -0700409 /**
410 * Save the Bluetooth name and address in the persistent store.
411 * Only non-null values will be saved.
412 * @param name
413 * @param address
414 */
fredc0f420372012-04-12 00:02:00 -0700415 private void storeNameAndAddress(String name, String address) {
416 if (name != null) {
417 Settings.Secure.putString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_NAME, name);
fredc0f420372012-04-12 00:02:00 -0700418 mName = name;
Jeff Sharkey67609c72016-03-05 14:29:13 -0700419 if (DBG) Slog.d(TAG,"Stored Bluetooth name: " +
fredc649fe492012-04-19 01:07:18 -0700420 Settings.Secure.getString(mContentResolver,SECURE_SETTINGS_BLUETOOTH_NAME));
fredc0f420372012-04-12 00:02:00 -0700421 }
422
423 if (address != null) {
424 Settings.Secure.putString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDRESS, address);
fredc0f420372012-04-12 00:02:00 -0700425 mAddress=address;
Jeff Sharkey67609c72016-03-05 14:29:13 -0700426 if (DBG) Slog.d(TAG,"Stored Bluetoothaddress: " +
fredc649fe492012-04-19 01:07:18 -0700427 Settings.Secure.getString(mContentResolver,SECURE_SETTINGS_BLUETOOTH_ADDRESS));
fredc0f420372012-04-12 00:02:00 -0700428 }
Zhihai Xud31c3222012-10-31 16:08:57 -0700429
430 if ((name != null) && (address != null)) {
431 Settings.Secure.putInt(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDR_VALID, 1);
432 }
fredc0f420372012-04-12 00:02:00 -0700433 }
434
435 public IBluetooth registerAdapter(IBluetoothManagerCallback callback){
Natalie Silvanovich55db6462014-05-01 16:12:23 -0700436 if (callback == null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700437 Slog.w(TAG, "Callback is null in registerAdapter");
Natalie Silvanovich55db6462014-05-01 16:12:23 -0700438 return null;
439 }
fredc0f420372012-04-12 00:02:00 -0700440 Message msg = mHandler.obtainMessage(MESSAGE_REGISTER_ADAPTER);
441 msg.obj = callback;
442 mHandler.sendMessage(msg);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700443
444 return mBluetooth;
fredc0f420372012-04-12 00:02:00 -0700445 }
446
447 public void unregisterAdapter(IBluetoothManagerCallback callback) {
Natalie Silvanovich55db6462014-05-01 16:12:23 -0700448 if (callback == null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700449 Slog.w(TAG, "Callback is null in unregisterAdapter");
Natalie Silvanovich55db6462014-05-01 16:12:23 -0700450 return;
451 }
fredc0f420372012-04-12 00:02:00 -0700452 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
453 "Need BLUETOOTH permission");
454 Message msg = mHandler.obtainMessage(MESSAGE_UNREGISTER_ADAPTER);
455 msg.obj = callback;
456 mHandler.sendMessage(msg);
457 }
458
459 public void registerStateChangeCallback(IBluetoothStateChangeCallback callback) {
460 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
461 "Need BLUETOOTH permission");
Marie Janssencb21ad72016-12-13 10:51:02 -0800462 if (callback == null) {
463 Slog.w(TAG, "registerStateChangeCallback: Callback is null!");
464 return;
465 }
fredc0f420372012-04-12 00:02:00 -0700466 Message msg = mHandler.obtainMessage(MESSAGE_REGISTER_STATE_CHANGE_CALLBACK);
467 msg.obj = callback;
468 mHandler.sendMessage(msg);
469 }
470
471 public void unregisterStateChangeCallback(IBluetoothStateChangeCallback callback) {
472 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
473 "Need BLUETOOTH permission");
Marie Janssencb21ad72016-12-13 10:51:02 -0800474 if (callback == null) {
475 Slog.w(TAG, "unregisterStateChangeCallback: Callback is null!");
476 return;
477 }
fredc0f420372012-04-12 00:02:00 -0700478 Message msg = mHandler.obtainMessage(MESSAGE_UNREGISTER_STATE_CHANGE_CALLBACK);
479 msg.obj = callback;
480 mHandler.sendMessage(msg);
481 }
482
483 public boolean isEnabled() {
Zhihai Xu6eb76522012-11-29 15:41:04 -0800484 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
485 (!checkIfCallerIsForegroundUser())) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700486 Slog.w(TAG,"isEnabled(): not allowed for non-active and non system user");
Zhihai Xu40874a02012-10-08 17:57:03 -0700487 return false;
488 }
489
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700490 try {
491 mBluetoothLock.readLock().lock();
492 if (mBluetooth != null) return mBluetooth.isEnabled();
493 } catch (RemoteException e) {
494 Slog.e(TAG, "isEnabled()", e);
495 } finally {
496 mBluetoothLock.readLock().unlock();
fredc0f420372012-04-12 00:02:00 -0700497 }
498 return false;
499 }
500
Christine Hallstrom995c90a2016-05-25 15:49:08 -0700501 public int getState() {
502 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
503 (!checkIfCallerIsForegroundUser())) {
Marie Janssencb21ad72016-12-13 10:51:02 -0800504 Slog.w(TAG, "getState(): report OFF for non-active and non system user");
Christine Hallstrom995c90a2016-05-25 15:49:08 -0700505 return BluetoothAdapter.STATE_OFF;
506 }
507
508 try {
509 mBluetoothLock.readLock().lock();
510 if (mBluetooth != null) return mBluetooth.getState();
511 } catch (RemoteException e) {
512 Slog.e(TAG, "getState()", e);
513 } finally {
514 mBluetoothLock.readLock().unlock();
515 }
516 return BluetoothAdapter.STATE_OFF;
517 }
518
Nitin Arorad055adb2015-03-02 15:03:51 -0800519 class ClientDeathRecipient implements IBinder.DeathRecipient {
Marie Janssen59804562016-12-28 14:13:21 -0800520 private String mPackageName;
521
522 public ClientDeathRecipient(String packageName) {
523 mPackageName = packageName;
524 }
525
Nitin Arorad055adb2015-03-02 15:03:51 -0800526 public void binderDied() {
Marie Janssen59804562016-12-28 14:13:21 -0800527 if (DBG) Slog.d(TAG, "Binder is dead - unregister " + mPackageName);
Marie Janssen2977c3e2016-11-09 12:01:24 -0800528 if (isBleAppPresent()) {
529 // Nothing to do, another app is here.
530 return;
531 }
532 if (DBG) Slog.d(TAG, "Disabling LE only mode after application crash");
533 try {
534 mBluetoothLock.readLock().lock();
535 if (mBluetooth != null &&
536 mBluetooth.getState() == BluetoothAdapter.STATE_BLE_ON) {
537 mEnable = false;
538 mBluetooth.onBrEdrDown();
Nitin Arorad055adb2015-03-02 15:03:51 -0800539 }
Marie Janssen2977c3e2016-11-09 12:01:24 -0800540 } catch (RemoteException e) {
541 Slog.e(TAG,"Unable to call onBrEdrDown", e);
542 } finally {
543 mBluetoothLock.readLock().unlock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800544 }
545 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800546
Marie Janssen59804562016-12-28 14:13:21 -0800547 public String getPackageName() {
548 return mPackageName;
549 }
550 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800551
Wei Wang67d84162015-04-26 17:04:29 -0700552 @Override
553 public boolean isBleScanAlwaysAvailable() {
Marie Janssen6a383a72016-10-25 10:47:51 -0700554 if (isAirplaneModeOn() && !mEnable) {
555 return false;
556 }
Wei Wang67d84162015-04-26 17:04:29 -0700557 try {
558 return (Settings.Global.getInt(mContentResolver,
559 Settings.Global.BLE_SCAN_ALWAYS_AVAILABLE)) != 0;
560 } catch (SettingNotFoundException e) {
561 }
562 return false;
563 }
564
Wei Wange4a744b2015-06-11 17:50:29 -0700565 // Monitor change of BLE scan only mode settings.
566 private void registerForBleScanModeChange() {
567 ContentObserver contentObserver = new ContentObserver(null) {
568 @Override
569 public void onChange(boolean selfChange) {
Marie Janssen2977c3e2016-11-09 12:01:24 -0800570 if (isBleScanAlwaysAvailable()) {
571 // Nothing to do
572 return;
573 }
574 // BLE scan is not available.
575 disableBleScanMode();
576 clearBleApps();
577 try {
578 mBluetoothLock.readLock().lock();
579 if (mBluetooth != null) mBluetooth.onBrEdrDown();
580 } catch (RemoteException e) {
581 Slog.e(TAG, "error when disabling bluetooth", e);
582 } finally {
583 mBluetoothLock.readLock().unlock();
Wei Wange4a744b2015-06-11 17:50:29 -0700584 }
585 }
586 };
587
588 mContentResolver.registerContentObserver(
589 Settings.Global.getUriFor(Settings.Global.BLE_SCAN_ALWAYS_AVAILABLE),
590 false, contentObserver);
591 }
592
593 // Disable ble scan only mode.
594 private void disableBleScanMode() {
595 try {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700596 mBluetoothLock.writeLock().lock();
Wei Wange4a744b2015-06-11 17:50:29 -0700597 if (mBluetooth != null && (mBluetooth.getState() != BluetoothAdapter.STATE_ON)) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700598 if (DBG) Slog.d(TAG, "Reseting the mEnable flag for clean disable");
Wei Wange4a744b2015-06-11 17:50:29 -0700599 mEnable = false;
600 }
601 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700602 Slog.e(TAG, "getState()", e);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700603 } finally {
604 mBluetoothLock.writeLock().unlock();
Wei Wange4a744b2015-06-11 17:50:29 -0700605 }
606 }
607
Marie Janssen59804562016-12-28 14:13:21 -0800608 public int updateBleAppCount(IBinder token, boolean enable, String packageName) {
609 ClientDeathRecipient r = mBleApps.get(token);
610 if (r == null && enable) {
611 ClientDeathRecipient deathRec = new ClientDeathRecipient(packageName);
612 try {
613 token.linkToDeath(deathRec, 0);
614 } catch (RemoteException ex) {
615 throw new IllegalArgumentException("BLE app (" + packageName + ") already dead!");
Nitin Arorad055adb2015-03-02 15:03:51 -0800616 }
Marie Janssen59804562016-12-28 14:13:21 -0800617 mBleApps.put(token, deathRec);
618 if (DBG) Slog.d(TAG, "Registered for death of " + packageName);
619 } else if (!enable && r != null) {
620 // Unregister death recipient as the app goes away.
621 token.unlinkToDeath(r, 0);
622 mBleApps.remove(token);
623 if (DBG) Slog.d(TAG, "Unregistered for death of " + packageName);
Nitin Arorad055adb2015-03-02 15:03:51 -0800624 }
Marie Janssen2977c3e2016-11-09 12:01:24 -0800625 int appCount = mBleApps.size();
626 if (DBG) Slog.d(TAG, appCount + " registered Ble Apps");
627 if (appCount == 0 && mEnable) {
Wei Wange4a744b2015-06-11 17:50:29 -0700628 disableBleScanMode();
Nitin Arorad055adb2015-03-02 15:03:51 -0800629 }
Marie Janssen2977c3e2016-11-09 12:01:24 -0800630 return appCount;
Nitin Arorad055adb2015-03-02 15:03:51 -0800631 }
632
Wei Wange4a744b2015-06-11 17:50:29 -0700633 // Clear all apps using BLE scan only mode.
634 private void clearBleApps() {
Marie Janssen2977c3e2016-11-09 12:01:24 -0800635 mBleApps.clear();
Wei Wange4a744b2015-06-11 17:50:29 -0700636 }
637
Marie Janssen59804562016-12-28 14:13:21 -0800638 /** @hide */
Nitin Arorad055adb2015-03-02 15:03:51 -0800639 public boolean isBleAppPresent() {
Marie Janssen2977c3e2016-11-09 12:01:24 -0800640 if (DBG) Slog.d(TAG, "isBleAppPresent() count: " + mBleApps.size());
641 return mBleApps.size() > 0;
Nitin Arorad055adb2015-03-02 15:03:51 -0800642 }
643
644 /**
Marie Janssened50bbc2016-12-15 13:51:30 -0800645 * Action taken when GattService is turned on
Nitin Arorad055adb2015-03-02 15:03:51 -0800646 */
647 private void onBluetoothGattServiceUp() {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700648 if (DBG) Slog.d(TAG,"BluetoothGatt Service is Up");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700649 try {
650 mBluetoothLock.readLock().lock();
Marie Janssened50bbc2016-12-15 13:51:30 -0800651 if (mBluetooth == null) {
652 if (DBG) Slog.w(TAG, "onBluetoothServiceUp: mBluetooth is null!");
653 return;
654 }
655 int st = mBluetooth.getState();
656 if (st != BluetoothAdapter.STATE_BLE_ON) {
657 if (DBG) Slog.v(TAG, "onBluetoothServiceUp: state isn't BLE_ON: " +
658 BluetoothAdapter.nameForState(st));
659 return;
660 }
661 if (isBluetoothPersistedStateOnBluetooth() || !isBleAppPresent()) {
662 // This triggers transition to STATE_ON
Nitin Arorad055adb2015-03-02 15:03:51 -0800663 mBluetooth.onLeServiceUp();
Nitin Arorad055adb2015-03-02 15:03:51 -0800664 persistBluetoothSetting(BLUETOOTH_ON_BLUETOOTH);
Nitin Arorad055adb2015-03-02 15:03:51 -0800665 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700666 } catch (RemoteException e) {
667 Slog.e(TAG,"Unable to call onServiceUp", e);
668 } finally {
669 mBluetoothLock.readLock().unlock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800670 }
671 }
672
673 /**
674 * Inform BluetoothAdapter instances that BREDR part is down
675 * and turn off all service and stack if no LE app needs it
676 */
677 private void sendBrEdrDownCallback() {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700678 if (DBG) Slog.d(TAG,"Calling sendBrEdrDownCallback callbacks");
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700679
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700680 if (mBluetooth == null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700681 Slog.w(TAG, "Bluetooth handle is null");
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700682 return;
683 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800684
685 if (isBleAppPresent() == false) {
686 try {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700687 mBluetoothLock.readLock().lock();
688 if (mBluetooth != null) mBluetooth.onBrEdrDown();
689 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700690 Slog.e(TAG, "Call to onBrEdrDown() failed.", e);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700691 } finally {
692 mBluetoothLock.readLock().unlock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800693 }
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700694 } else {
695 // Need to stay at BLE ON. Disconnect all Gatt connections
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700696 try {
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700697 mBluetoothGatt.unregAll();
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700698 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700699 Slog.e(TAG, "Unable to disconnect all apps.", e);
Nitin Arorad055adb2015-03-02 15:03:51 -0800700 }
701 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800702 }
703
Marie Janssen59804562016-12-28 14:13:21 -0800704 public boolean enableNoAutoConnect(String packageName)
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700705 {
Lenka Trochtova13a05192016-12-02 12:19:39 +0100706 if (isBluetoothDisallowed()) {
707 if (DBG) {
708 Slog.d(TAG, "enableNoAutoConnect(): not enabling - bluetooth disallowed");
709 }
710 return false;
711 }
712
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700713 mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
714 "Need BLUETOOTH ADMIN permission");
Zhihai Xu40874a02012-10-08 17:57:03 -0700715
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700716 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700717 Slog.d(TAG,"enableNoAutoConnect(): mBluetooth =" + mBluetooth +
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700718 " mBinding = " + mBinding);
719 }
Martijn Coenen8385c5a2012-11-29 10:14:16 -0800720 int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
721
722 if (callingAppId != Process.NFC_UID) {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700723 throw new SecurityException("no permission to enable Bluetooth quietly");
724 }
Martijn Coenen8385c5a2012-11-29 10:14:16 -0800725
Zhihai Xu401202b2012-12-03 11:36:21 -0800726 synchronized(mReceiver) {
727 mQuietEnableExternal = true;
728 mEnableExternal = true;
Marie Janssen59804562016-12-28 14:13:21 -0800729 sendEnableMsg(true, packageName);
Zhihai Xu401202b2012-12-03 11:36:21 -0800730 }
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700731 return true;
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700732 }
Ajay Panicker4bb48302016-03-31 14:14:27 -0700733
Svetoslav Ganovc2ac5bd2016-06-29 17:31:44 -0700734 public boolean enable(String packageName) throws RemoteException {
Lenka Trochtova13a05192016-12-02 12:19:39 +0100735 if (isBluetoothDisallowed()) {
736 if (DBG) {
737 Slog.d(TAG,"enable(): not enabling - bluetooth disallowed");
738 }
739 return false;
740 }
741
Svetoslav Ganovc2ac5bd2016-06-29 17:31:44 -0700742 final int callingUid = Binder.getCallingUid();
743 final boolean callerSystem = UserHandle.getAppId(callingUid) == Process.SYSTEM_UID;
744
745 if (!callerSystem) {
746 if (!checkIfCallerIsForegroundUser()) {
747 Slog.w(TAG, "enable(): not allowed for non-active and non system user");
748 return false;
749 }
750
751 mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
752 "Need BLUETOOTH ADMIN permission");
753
Ivan Podogovafababd2016-12-05 16:46:52 +0000754 if (!isEnabled() && mPermissionReviewRequired) {
755 startConsentUi(packageName, callingUid, BluetoothAdapter.ACTION_REQUEST_ENABLE);
Svetoslav Ganovc2ac5bd2016-06-29 17:31:44 -0700756 return false;
757 }
fredcf2458862012-04-16 15:18:27 -0700758 }
759
Zhihai Xu401202b2012-12-03 11:36:21 -0800760 if (DBG) {
Marie Janssen59804562016-12-28 14:13:21 -0800761 Slog.d(TAG,"enable(" + packageName + "): mBluetooth =" + mBluetooth +
Marie Janssencb21ad72016-12-13 10:51:02 -0800762 " mBinding = " + mBinding + " mState = " +
763 BluetoothAdapter.nameForState(mState));
Sanket Agarwal090bf552016-04-21 14:10:55 -0700764 }
Zhihai Xu401202b2012-12-03 11:36:21 -0800765
766 synchronized(mReceiver) {
767 mQuietEnableExternal = false;
768 mEnableExternal = true;
769 // waive WRITE_SECURE_SETTINGS permission check
Marie Janssen59804562016-12-28 14:13:21 -0800770 sendEnableMsg(false, packageName);
Zhihai Xu401202b2012-12-03 11:36:21 -0800771 }
Jeff Sharkey67609c72016-03-05 14:29:13 -0700772 if (DBG) Slog.d(TAG, "enable returning");
Zhihai Xu401202b2012-12-03 11:36:21 -0800773 return true;
fredc0f420372012-04-12 00:02:00 -0700774 }
775
Svetoslav Ganovc2ac5bd2016-06-29 17:31:44 -0700776 public boolean disable(String packageName, boolean persist) throws RemoteException {
777 final int callingUid = Binder.getCallingUid();
778 final boolean callerSystem = UserHandle.getAppId(callingUid) == Process.SYSTEM_UID;
Zhihai Xu40874a02012-10-08 17:57:03 -0700779
Svetoslav Ganovc2ac5bd2016-06-29 17:31:44 -0700780 if (!callerSystem) {
781 if (!checkIfCallerIsForegroundUser()) {
782 Slog.w(TAG, "disable(): not allowed for non-active and non system user");
783 return false;
784 }
785
786 mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
787 "Need BLUETOOTH ADMIN permission");
788
Ivan Podogovafababd2016-12-05 16:46:52 +0000789 if (isEnabled() && mPermissionReviewRequired) {
790 startConsentUi(packageName, callingUid, BluetoothAdapter.ACTION_REQUEST_DISABLE);
Svetoslav Ganovc2ac5bd2016-06-29 17:31:44 -0700791 return false;
792 }
Zhihai Xu40874a02012-10-08 17:57:03 -0700793 }
794
fredcf2458862012-04-16 15:18:27 -0700795 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700796 Slog.d(TAG,"disable(): mBluetooth = " + mBluetooth +
Matthew Xiecdce0b92012-07-12 19:06:15 -0700797 " mBinding = " + mBinding);
798 }
fredcf2458862012-04-16 15:18:27 -0700799
Zhihai Xu401202b2012-12-03 11:36:21 -0800800 synchronized(mReceiver) {
801 if (persist) {
Zhihai Xu401202b2012-12-03 11:36:21 -0800802 persistBluetoothSetting(BLUETOOTH_OFF);
Zhihai Xu401202b2012-12-03 11:36:21 -0800803 }
804 mEnableExternal = false;
Marie Janssen59804562016-12-28 14:13:21 -0800805 sendDisableMsg(packageName);
Zhihai Xu401202b2012-12-03 11:36:21 -0800806 }
fredc0f420372012-04-12 00:02:00 -0700807 return true;
808 }
809
Ivan Podogovafababd2016-12-05 16:46:52 +0000810 private void startConsentUi(String packageName, int callingUid, String intentAction)
811 throws RemoteException {
Svetoslav Ganovc2ac5bd2016-06-29 17:31:44 -0700812 try {
813 // Validate the package only if we are going to use it
814 ApplicationInfo applicationInfo = mContext.getPackageManager()
815 .getApplicationInfoAsUser(packageName,
816 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
817 UserHandle.getUserId(callingUid));
818 if (applicationInfo.uid != callingUid) {
819 throw new SecurityException("Package " + callingUid
820 + " not in uid " + callingUid);
821 }
822
Ivan Podogovafababd2016-12-05 16:46:52 +0000823 // Permission review mode, trigger a user prompt
824 Intent intent = new Intent(intentAction);
825 mContext.startActivity(intent);
Svetoslav Ganovc2ac5bd2016-06-29 17:31:44 -0700826 } catch (PackageManager.NameNotFoundException e) {
827 throw new RemoteException(e.getMessage());
828 }
Svetoslav Ganovc2ac5bd2016-06-29 17:31:44 -0700829 }
830
fredc649fe492012-04-19 01:07:18 -0700831 public void unbindAndFinish() {
fredcf2458862012-04-16 15:18:27 -0700832 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700833 Slog.d(TAG,"unbindAndFinish(): " + mBluetooth +
Marie Janssencb21ad72016-12-13 10:51:02 -0800834 " mBinding = " + mBinding + " mUnbinding = " + mUnbinding);
fredcf2458862012-04-16 15:18:27 -0700835 }
836
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700837 try {
838 mBluetoothLock.writeLock().lock();
fredc0f420372012-04-12 00:02:00 -0700839 if (mUnbinding) return;
840 mUnbinding = true;
Pavlin Radoslavove47ec142016-06-01 22:25:18 -0700841 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
Pavlin Radoslavov74f60c02016-09-21 17:28:11 -0700842 mHandler.removeMessages(MESSAGE_BIND_PROFILE_SERVICE);
Zhihai Xu40874a02012-10-08 17:57:03 -0700843 if (mBluetooth != null) {
Andre Eisenbach305fdab2015-11-11 21:43:26 -0800844 //Unregister callback object
845 try {
846 mBluetooth.unregisterCallback(mBluetoothCallback);
847 } catch (RemoteException re) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700848 Slog.e(TAG, "Unable to unregister BluetoothCallback",re);
fredcbf072a72012-05-09 16:52:50 -0700849 }
Marie Janssen9db28eb2016-01-12 16:05:15 -0800850 mBluetoothBinder = null;
fredcd6883532012-04-25 17:46:13 -0700851 mBluetooth = null;
fredc0f420372012-04-12 00:02:00 -0700852 mContext.unbindService(mConnection);
fredcd6883532012-04-25 17:46:13 -0700853 mUnbinding = false;
Zhihai Xu40874a02012-10-08 17:57:03 -0700854 mBinding = false;
fredcf2458862012-04-16 15:18:27 -0700855 } else {
Marie Janssencb21ad72016-12-13 10:51:02 -0800856 mUnbinding = false;
fredc0f420372012-04-12 00:02:00 -0700857 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800858 mBluetoothGatt = null;
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700859 } finally {
860 mBluetoothLock.writeLock().unlock();
fredc0f420372012-04-12 00:02:00 -0700861 }
862 }
863
Matthew Xieddf7e472013-03-01 18:41:02 -0800864 public IBluetoothGatt getBluetoothGatt() {
865 // sync protection
866 return mBluetoothGatt;
867 }
868
Benjamin Franze8b98922014-11-12 15:57:54 +0000869 @Override
870 public boolean bindBluetoothProfileService(int bluetoothProfile,
871 IBluetoothProfileServiceConnection proxy) {
872 if (!mEnable) {
873 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700874 Slog.d(TAG, "Trying to bind to profile: " + bluetoothProfile +
Benjamin Franze8b98922014-11-12 15:57:54 +0000875 ", while Bluetooth was disabled");
876 }
877 return false;
878 }
879 synchronized (mProfileServices) {
880 ProfileServiceConnections psc = mProfileServices.get(new Integer(bluetoothProfile));
881 if (psc == null) {
882 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700883 Slog.d(TAG, "Creating new ProfileServiceConnections object for"
Benjamin Franze8b98922014-11-12 15:57:54 +0000884 + " profile: " + bluetoothProfile);
885 }
Benjamin Franz5b614592014-12-09 18:58:45 +0000886
887 if (bluetoothProfile != BluetoothProfile.HEADSET) return false;
888
889 Intent intent = new Intent(IBluetoothHeadset.class.getName());
Benjamin Franze8b98922014-11-12 15:57:54 +0000890 psc = new ProfileServiceConnections(intent);
Benjamin Franz5b614592014-12-09 18:58:45 +0000891 if (!psc.bindService()) return false;
892
Benjamin Franze8b98922014-11-12 15:57:54 +0000893 mProfileServices.put(new Integer(bluetoothProfile), psc);
Benjamin Franze8b98922014-11-12 15:57:54 +0000894 }
895 }
896
897 // Introducing a delay to give the client app time to prepare
898 Message addProxyMsg = mHandler.obtainMessage(MESSAGE_ADD_PROXY_DELAYED);
899 addProxyMsg.arg1 = bluetoothProfile;
900 addProxyMsg.obj = proxy;
901 mHandler.sendMessageDelayed(addProxyMsg, ADD_PROXY_DELAY_MS);
902 return true;
903 }
904
905 @Override
906 public void unbindBluetoothProfileService(int bluetoothProfile,
907 IBluetoothProfileServiceConnection proxy) {
908 synchronized (mProfileServices) {
909 ProfileServiceConnections psc = mProfileServices.get(new Integer(bluetoothProfile));
910 if (psc == null) {
911 return;
912 }
913 psc.removeProxy(proxy);
914 }
915 }
916
917 private void unbindAllBluetoothProfileServices() {
918 synchronized (mProfileServices) {
919 for (Integer i : mProfileServices.keySet()) {
920 ProfileServiceConnections psc = mProfileServices.get(i);
Benjamin Franz5b614592014-12-09 18:58:45 +0000921 try {
922 mContext.unbindService(psc);
923 } catch (IllegalArgumentException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700924 Slog.e(TAG, "Unable to unbind service with intent: " + psc.mIntent, e);
Benjamin Franz5b614592014-12-09 18:58:45 +0000925 }
Benjamin Franze8b98922014-11-12 15:57:54 +0000926 psc.removeAllProxies();
927 }
928 mProfileServices.clear();
929 }
930 }
931
932 /**
Miao Chou658bf2f2015-06-26 17:14:35 -0700933 * Send enable message and set adapter name and address. Called when the boot phase becomes
934 * PHASE_SYSTEM_SERVICES_READY.
935 */
936 public void handleOnBootPhase() {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700937 if (DBG) Slog.d(TAG, "Bluetooth boot completed");
Lenka Trochtova13a05192016-12-02 12:19:39 +0100938 UserManagerInternal userManagerInternal =
939 LocalServices.getService(UserManagerInternal.class);
940 userManagerInternal.addUserRestrictionsListener(mUserRestrictionsListener);
941 if (isBluetoothDisallowed()) {
942 return;
943 }
Miao Chou658bf2f2015-06-26 17:14:35 -0700944 if (mEnableExternal && isBluetoothPersistedStateOnBluetooth()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700945 if (DBG) Slog.d(TAG, "Auto-enabling Bluetooth.");
Marie Janssen59804562016-12-28 14:13:21 -0800946 sendEnableMsg(mQuietEnableExternal, "system boot");
Ajay Panickerbf796d82016-03-11 13:47:20 -0800947 } else if (!isNameAndAddressSet()) {
948 if (DBG) Slog.d(TAG, "Getting adapter name and address");
Ajay Panicker4bb48302016-03-31 14:14:27 -0700949 Message getMsg = mHandler.obtainMessage(MESSAGE_GET_NAME_AND_ADDRESS);
950 mHandler.sendMessage(getMsg);
Miao Chou658bf2f2015-06-26 17:14:35 -0700951 }
Miao Chou658bf2f2015-06-26 17:14:35 -0700952 }
953
954 /**
955 * Called when switching to a different foreground user.
956 */
957 public void handleOnSwitchUser(int userHandle) {
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -0700958 if (DBG) Slog.d(TAG, "User " + userHandle + " switched");
959 mHandler.obtainMessage(MESSAGE_USER_SWITCHED, userHandle, 0).sendToTarget();
960 }
961
962 /**
963 * Called when user is unlocked.
964 */
965 public void handleOnUnlockUser(int userHandle) {
966 if (DBG) Slog.d(TAG, "User " + userHandle + " unlocked");
967 mHandler.obtainMessage(MESSAGE_USER_UNLOCKED, userHandle, 0).sendToTarget();
Miao Chou658bf2f2015-06-26 17:14:35 -0700968 }
969
970 /**
Benjamin Franze8b98922014-11-12 15:57:54 +0000971 * This class manages the clients connected to a given ProfileService
972 * and maintains the connection with that service.
973 */
974 final private class ProfileServiceConnections implements ServiceConnection,
975 IBinder.DeathRecipient {
976 final RemoteCallbackList<IBluetoothProfileServiceConnection> mProxies =
977 new RemoteCallbackList <IBluetoothProfileServiceConnection>();
978 IBinder mService;
979 ComponentName mClassName;
980 Intent mIntent;
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700981 boolean mInvokingProxyCallbacks = false;
Benjamin Franze8b98922014-11-12 15:57:54 +0000982
983 ProfileServiceConnections(Intent intent) {
984 mService = null;
985 mClassName = null;
986 mIntent = intent;
987 }
988
Benjamin Franz5b614592014-12-09 18:58:45 +0000989 private boolean bindService() {
990 if (mIntent != null && mService == null &&
991 doBind(mIntent, this, 0, UserHandle.CURRENT_OR_SELF)) {
Benjamin Franze8b98922014-11-12 15:57:54 +0000992 Message msg = mHandler.obtainMessage(MESSAGE_BIND_PROFILE_SERVICE);
993 msg.obj = this;
994 mHandler.sendMessageDelayed(msg, TIMEOUT_BIND_MS);
Benjamin Franz5b614592014-12-09 18:58:45 +0000995 return true;
Benjamin Franze8b98922014-11-12 15:57:54 +0000996 }
Jeff Sharkey67609c72016-03-05 14:29:13 -0700997 Slog.w(TAG, "Unable to bind with intent: " + mIntent);
Benjamin Franz5b614592014-12-09 18:58:45 +0000998 return false;
Benjamin Franze8b98922014-11-12 15:57:54 +0000999 }
1000
1001 private void addProxy(IBluetoothProfileServiceConnection proxy) {
1002 mProxies.register(proxy);
1003 if (mService != null) {
1004 try{
1005 proxy.onServiceConnected(mClassName, mService);
1006 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001007 Slog.e(TAG, "Unable to connect to proxy", e);
Benjamin Franze8b98922014-11-12 15:57:54 +00001008 }
1009 } else {
1010 if (!mHandler.hasMessages(MESSAGE_BIND_PROFILE_SERVICE, this)) {
1011 Message msg = mHandler.obtainMessage(MESSAGE_BIND_PROFILE_SERVICE);
1012 msg.obj = this;
1013 mHandler.sendMessage(msg);
1014 }
1015 }
1016 }
1017
1018 private void removeProxy(IBluetoothProfileServiceConnection proxy) {
1019 if (proxy != null) {
1020 if (mProxies.unregister(proxy)) {
1021 try {
1022 proxy.onServiceDisconnected(mClassName);
1023 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001024 Slog.e(TAG, "Unable to disconnect proxy", e);
Benjamin Franze8b98922014-11-12 15:57:54 +00001025 }
1026 }
1027 } else {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001028 Slog.w(TAG, "Trying to remove a null proxy");
Benjamin Franze8b98922014-11-12 15:57:54 +00001029 }
1030 }
1031
1032 private void removeAllProxies() {
1033 onServiceDisconnected(mClassName);
1034 mProxies.kill();
1035 }
1036
1037 @Override
1038 public void onServiceConnected(ComponentName className, IBinder service) {
1039 // remove timeout message
1040 mHandler.removeMessages(MESSAGE_BIND_PROFILE_SERVICE, this);
1041 mService = service;
1042 mClassName = className;
1043 try {
1044 mService.linkToDeath(this, 0);
1045 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001046 Slog.e(TAG, "Unable to linkToDeath", e);
Benjamin Franze8b98922014-11-12 15:57:54 +00001047 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001048
1049 if (mInvokingProxyCallbacks) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001050 Slog.e(TAG, "Proxy callbacks already in progress.");
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001051 return;
Benjamin Franze8b98922014-11-12 15:57:54 +00001052 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001053 mInvokingProxyCallbacks = true;
1054
1055 final int n = mProxies.beginBroadcast();
1056 try {
1057 for (int i = 0; i < n; i++) {
1058 try {
1059 mProxies.getBroadcastItem(i).onServiceConnected(className, service);
1060 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001061 Slog.e(TAG, "Unable to connect to proxy", e);
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001062 }
1063 }
1064 } finally {
1065 mProxies.finishBroadcast();
1066 mInvokingProxyCallbacks = false;
1067 }
Benjamin Franze8b98922014-11-12 15:57:54 +00001068 }
1069
1070 @Override
1071 public void onServiceDisconnected(ComponentName className) {
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001072 if (mService == null) return;
Benjamin Franze8b98922014-11-12 15:57:54 +00001073 mService.unlinkToDeath(this, 0);
1074 mService = null;
1075 mClassName = null;
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001076
1077 if (mInvokingProxyCallbacks) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001078 Slog.e(TAG, "Proxy callbacks already in progress.");
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001079 return;
Benjamin Franze8b98922014-11-12 15:57:54 +00001080 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001081 mInvokingProxyCallbacks = true;
1082
1083 final int n = mProxies.beginBroadcast();
1084 try {
1085 for (int i = 0; i < n; i++) {
1086 try {
1087 mProxies.getBroadcastItem(i).onServiceDisconnected(className);
1088 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001089 Slog.e(TAG, "Unable to disconnect from proxy", e);
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001090 }
1091 }
1092 } finally {
1093 mProxies.finishBroadcast();
1094 mInvokingProxyCallbacks = false;
1095 }
Benjamin Franze8b98922014-11-12 15:57:54 +00001096 }
1097
1098 @Override
1099 public void binderDied() {
1100 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001101 Slog.w(TAG, "Profile service for profile: " + mClassName
Benjamin Franze8b98922014-11-12 15:57:54 +00001102 + " died.");
1103 }
1104 onServiceDisconnected(mClassName);
1105 // Trigger rebind
1106 Message msg = mHandler.obtainMessage(MESSAGE_BIND_PROFILE_SERVICE);
1107 msg.obj = this;
1108 mHandler.sendMessageDelayed(msg, TIMEOUT_BIND_MS);
1109 }
1110 }
1111
fredcbf072a72012-05-09 16:52:50 -07001112 private void sendBluetoothStateCallback(boolean isUp) {
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001113 try {
1114 int n = mStateChangeCallbacks.beginBroadcast();
Jeff Sharkey67609c72016-03-05 14:29:13 -07001115 if (DBG) Slog.d(TAG,"Broadcasting onBluetoothStateChange("+isUp+") to " + n + " receivers.");
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001116 for (int i=0; i <n;i++) {
1117 try {
1118 mStateChangeCallbacks.getBroadcastItem(i).onBluetoothStateChange(isUp);
1119 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001120 Slog.e(TAG, "Unable to call onBluetoothStateChange() on callback #" + i , e);
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001121 }
fredcbf072a72012-05-09 16:52:50 -07001122 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001123 } finally {
1124 mStateChangeCallbacks.finishBroadcast();
fredcbf072a72012-05-09 16:52:50 -07001125 }
fredcbf072a72012-05-09 16:52:50 -07001126 }
1127
1128 /**
Zhihai Xu40874a02012-10-08 17:57:03 -07001129 * Inform BluetoothAdapter instances that Adapter service is up
1130 */
1131 private void sendBluetoothServiceUpCallback() {
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001132 try {
1133 int n = mCallbacks.beginBroadcast();
Jeff Sharkey67609c72016-03-05 14:29:13 -07001134 Slog.d(TAG,"Broadcasting onBluetoothServiceUp() to " + n + " receivers.");
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001135 for (int i=0; i <n;i++) {
1136 try {
1137 mCallbacks.getBroadcastItem(i).onBluetoothServiceUp(mBluetooth);
1138 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001139 Slog.e(TAG, "Unable to call onBluetoothServiceUp() on callback #" + i, e);
Zhihai Xu40874a02012-10-08 17:57:03 -07001140 }
1141 }
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001142 } finally {
1143 mCallbacks.finishBroadcast();
Zhihai Xu40874a02012-10-08 17:57:03 -07001144 }
1145 }
1146 /**
fredcbf072a72012-05-09 16:52:50 -07001147 * Inform BluetoothAdapter instances that Adapter service is down
1148 */
1149 private void sendBluetoothServiceDownCallback() {
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001150 try {
1151 int n = mCallbacks.beginBroadcast();
Jeff Sharkey67609c72016-03-05 14:29:13 -07001152 Slog.d(TAG,"Broadcasting onBluetoothServiceDown() to " + n + " receivers.");
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001153 for (int i=0; i <n;i++) {
1154 try {
1155 mCallbacks.getBroadcastItem(i).onBluetoothServiceDown();
1156 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001157 Slog.e(TAG, "Unable to call onBluetoothServiceDown() on callback #" + i, e);
fredcd6883532012-04-25 17:46:13 -07001158 }
1159 }
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001160 } finally {
1161 mCallbacks.finishBroadcast();
fredcd6883532012-04-25 17:46:13 -07001162 }
1163 }
Svet Ganov408abf72015-05-12 19:13:36 -07001164
fredc0f420372012-04-12 00:02:00 -07001165 public String getAddress() {
Matthew Xieaf5ddbf2012-12-04 10:47:43 -08001166 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
Svet Ganov408abf72015-05-12 19:13:36 -07001167 "Need BLUETOOTH permission");
Zhihai Xu40874a02012-10-08 17:57:03 -07001168
Zhihai Xu6eb76522012-11-29 15:41:04 -08001169 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
Svet Ganov408abf72015-05-12 19:13:36 -07001170 (!checkIfCallerIsForegroundUser())) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001171 Slog.w(TAG,"getAddress(): not allowed for non-active and non system user");
Zhihai Xu6eb76522012-11-29 15:41:04 -08001172 return null;
Zhihai Xu40874a02012-10-08 17:57:03 -07001173 }
1174
Svet Ganov408abf72015-05-12 19:13:36 -07001175 if (mContext.checkCallingOrSelfPermission(Manifest.permission.LOCAL_MAC_ADDRESS)
1176 != PackageManager.PERMISSION_GRANTED) {
1177 return BluetoothAdapter.DEFAULT_MAC_ADDRESS;
1178 }
1179
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001180 try {
1181 mBluetoothLock.readLock().lock();
1182 if (mBluetooth != null) return mBluetooth.getAddress();
1183 } catch (RemoteException e) {
1184 Slog.e(TAG, "getAddress(): Unable to retrieve address remotely. Returning cached address", e);
1185 } finally {
1186 mBluetoothLock.readLock().unlock();
fredc116d1d462012-04-20 14:47:08 -07001187 }
Ajay Panickerbf796d82016-03-11 13:47:20 -08001188
Matthew Xiecdce0b92012-07-12 19:06:15 -07001189 // mAddress is accessed from outside.
1190 // It is alright without a lock. Here, bluetooth is off, no other thread is
1191 // changing mAddress
fredc0f420372012-04-12 00:02:00 -07001192 return mAddress;
1193 }
fredc649fe492012-04-19 01:07:18 -07001194
fredc0f420372012-04-12 00:02:00 -07001195 public String getName() {
Matthew Xieaf5ddbf2012-12-04 10:47:43 -08001196 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
1197 "Need BLUETOOTH permission");
Zhihai Xu40874a02012-10-08 17:57:03 -07001198
Zhihai Xu6eb76522012-11-29 15:41:04 -08001199 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
1200 (!checkIfCallerIsForegroundUser())) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001201 Slog.w(TAG,"getName(): not allowed for non-active and non system user");
Zhihai Xu6eb76522012-11-29 15:41:04 -08001202 return null;
Zhihai Xu40874a02012-10-08 17:57:03 -07001203 }
1204
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001205 try {
1206 mBluetoothLock.readLock().lock();
1207 if (mBluetooth != null) return mBluetooth.getName();
1208 } catch (RemoteException e) {
1209 Slog.e(TAG, "getName(): Unable to retrieve name remotely. Returning cached name", e);
1210 } finally {
1211 mBluetoothLock.readLock().unlock();
fredc116d1d462012-04-20 14:47:08 -07001212 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001213
Matthew Xiecdce0b92012-07-12 19:06:15 -07001214 // mName is accessed from outside.
1215 // It alright without a lock. Here, bluetooth is off, no other thread is
1216 // changing mName
fredc0f420372012-04-12 00:02:00 -07001217 return mName;
1218 }
1219
fredc0f420372012-04-12 00:02:00 -07001220 private class BluetoothServiceConnection implements ServiceConnection {
Marie Janssencb21ad72016-12-13 10:51:02 -08001221 public void onServiceConnected(ComponentName componentName, IBinder service) {
1222 String name = componentName.getClassName();
1223 if (DBG) Slog.d(TAG, "BluetoothServiceConnection: " + name);
fredc0f420372012-04-12 00:02:00 -07001224 Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_SERVICE_CONNECTED);
Marie Janssencb21ad72016-12-13 10:51:02 -08001225 if (name.equals("com.android.bluetooth.btservice.AdapterService")) {
Matthew Xieddf7e472013-03-01 18:41:02 -08001226 msg.arg1 = SERVICE_IBLUETOOTH;
Marie Janssencb21ad72016-12-13 10:51:02 -08001227 } else if (name.equals("com.android.bluetooth.gatt.GattService")) {
Matthew Xieddf7e472013-03-01 18:41:02 -08001228 msg.arg1 = SERVICE_IBLUETOOTHGATT;
1229 } else {
Marie Janssencb21ad72016-12-13 10:51:02 -08001230 Slog.e(TAG, "Unknown service connected: " + name);
Matthew Xieddf7e472013-03-01 18:41:02 -08001231 return;
1232 }
fredc0f420372012-04-12 00:02:00 -07001233 msg.obj = service;
1234 mHandler.sendMessage(msg);
1235 }
1236
Marie Janssencb21ad72016-12-13 10:51:02 -08001237 public void onServiceDisconnected(ComponentName componentName) {
1238 // Called if we unexpectedly disconnect.
1239 String name = componentName.getClassName();
1240 if (DBG) Slog.d(TAG, "BluetoothServiceConnection, disconnected: " + name);
fredc0f420372012-04-12 00:02:00 -07001241 Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED);
Marie Janssencb21ad72016-12-13 10:51:02 -08001242 if (name.equals("com.android.bluetooth.btservice.AdapterService")) {
Matthew Xieddf7e472013-03-01 18:41:02 -08001243 msg.arg1 = SERVICE_IBLUETOOTH;
Marie Janssencb21ad72016-12-13 10:51:02 -08001244 } else if (name.equals("com.android.bluetooth.gatt.GattService")) {
Matthew Xieddf7e472013-03-01 18:41:02 -08001245 msg.arg1 = SERVICE_IBLUETOOTHGATT;
1246 } else {
Marie Janssencb21ad72016-12-13 10:51:02 -08001247 Slog.e(TAG, "Unknown service disconnected: " + name);
Matthew Xieddf7e472013-03-01 18:41:02 -08001248 return;
1249 }
fredc0f420372012-04-12 00:02:00 -07001250 mHandler.sendMessage(msg);
1251 }
1252 }
1253
1254 private BluetoothServiceConnection mConnection = new BluetoothServiceConnection();
1255
Zhihai Xu40874a02012-10-08 17:57:03 -07001256 private class BluetoothHandler extends Handler {
Ajay Panicker4bb48302016-03-31 14:14:27 -07001257 boolean mGetNameAddressOnly = false;
1258
Zhihai Xu40874a02012-10-08 17:57:03 -07001259 public BluetoothHandler(Looper looper) {
1260 super(looper);
1261 }
1262
fredc0f420372012-04-12 00:02:00 -07001263 @Override
1264 public void handleMessage(Message msg) {
fredc0f420372012-04-12 00:02:00 -07001265 switch (msg.what) {
Ajay Panicker4bb48302016-03-31 14:14:27 -07001266 case MESSAGE_GET_NAME_AND_ADDRESS:
1267 if (DBG) Slog.d(TAG, "MESSAGE_GET_NAME_AND_ADDRESS");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001268 try {
1269 mBluetoothLock.writeLock().lock();
Ajay Panicker4bb48302016-03-31 14:14:27 -07001270 if ((mBluetooth == null) && (!mBinding)) {
1271 if (DBG) Slog.d(TAG, "Binding to service to get name and address");
1272 mGetNameAddressOnly = true;
1273 Message timeoutMsg = mHandler.obtainMessage(MESSAGE_TIMEOUT_BIND);
1274 mHandler.sendMessageDelayed(timeoutMsg, TIMEOUT_BIND_MS);
1275 Intent i = new Intent(IBluetooth.class.getName());
1276 if (!doBind(i, mConnection,
1277 Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT,
1278 UserHandle.CURRENT)) {
1279 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
1280 } else {
1281 mBinding = true;
1282 }
1283 } else if (mBluetooth != null) {
1284 try {
1285 storeNameAndAddress(mBluetooth.getName(),
1286 mBluetooth.getAddress());
1287 } catch (RemoteException re) {
1288 Slog.e(TAG, "Unable to grab names", re);
1289 }
1290 if (mGetNameAddressOnly && !mEnable) {
1291 unbindAndFinish();
1292 }
1293 mGetNameAddressOnly = false;
1294 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001295 } finally {
1296 mBluetoothLock.writeLock().unlock();
Ajay Panicker4bb48302016-03-31 14:14:27 -07001297 }
1298 break;
1299
Matthew Xiecdce0b92012-07-12 19:06:15 -07001300 case MESSAGE_ENABLE:
fredcf2458862012-04-16 15:18:27 -07001301 if (DBG) {
Marie Janssencb21ad72016-12-13 10:51:02 -08001302 Slog.d(TAG, "MESSAGE_ENABLE(" + msg.arg1 + "): mBluetooth = " + mBluetooth);
fredc649fe492012-04-19 01:07:18 -07001303 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001304 mHandler.removeMessages(MESSAGE_RESTART_BLUETOOTH_SERVICE);
1305 mEnable = true;
Calvin Ona0b91d72016-06-15 17:58:23 -07001306
1307 // Use service interface to get the exact state
1308 try {
1309 mBluetoothLock.readLock().lock();
1310 if (mBluetooth != null) {
1311 int state = mBluetooth.getState();
1312 if (state == BluetoothAdapter.STATE_BLE_ON) {
Marie Janssene0bfa2e2016-12-20 11:21:12 -08001313 Slog.w(TAG, "BT Enable in BLE_ON State, going to ON");
Calvin Ona0b91d72016-06-15 17:58:23 -07001314 mBluetooth.onLeServiceUp();
Marie Janssene0bfa2e2016-12-20 11:21:12 -08001315 persistBluetoothSetting(BLUETOOTH_ON_BLUETOOTH);
Calvin Ona0b91d72016-06-15 17:58:23 -07001316 break;
1317 }
1318 }
1319 } catch (RemoteException e) {
1320 Slog.e(TAG, "", e);
1321 } finally {
1322 mBluetoothLock.readLock().unlock();
1323 }
1324
1325 mQuietEnable = (msg.arg1 == 1);
Pavlin Radoslavove47ec142016-06-01 22:25:18 -07001326 if (mBluetooth == null) {
Calvin Ona0b91d72016-06-15 17:58:23 -07001327 handleEnable(mQuietEnable);
Pavlin Radoslavove47ec142016-06-01 22:25:18 -07001328 } else {
1329 //
1330 // We need to wait until transitioned to STATE_OFF and
1331 // the previous Bluetooth process has exited. The
1332 // waiting period has three components:
1333 // (a) Wait until the local state is STATE_OFF. This
1334 // is accomplished by "waitForOnOff(false, true)".
1335 // (b) Wait until the STATE_OFF state is updated to
1336 // all components.
1337 // (c) Wait until the Bluetooth process exits, and
1338 // ActivityManager detects it.
1339 // The waiting for (b) and (c) is accomplished by
1340 // delaying the MESSAGE_RESTART_BLUETOOTH_SERVICE
1341 // message. On slower devices, that delay needs to be
1342 // on the order of (2 * SERVICE_RESTART_TIME_MS).
1343 //
1344 waitForOnOff(false, true);
Pavlin Radoslavove47ec142016-06-01 22:25:18 -07001345 Message restartMsg = mHandler.obtainMessage(
1346 MESSAGE_RESTART_BLUETOOTH_SERVICE);
1347 mHandler.sendMessageDelayed(restartMsg,
1348 2 * SERVICE_RESTART_TIME_MS);
1349 }
fredc649fe492012-04-19 01:07:18 -07001350 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001351
fredc0f420372012-04-12 00:02:00 -07001352 case MESSAGE_DISABLE:
Marie Janssencb21ad72016-12-13 10:51:02 -08001353 if (DBG) Slog.d(TAG, "MESSAGE_DISABLE: mBluetooth = " + mBluetooth);
Zhihai Xu40874a02012-10-08 17:57:03 -07001354 mHandler.removeMessages(MESSAGE_RESTART_BLUETOOTH_SERVICE);
1355 if (mEnable && mBluetooth != null) {
1356 waitForOnOff(true, false);
1357 mEnable = false;
Zhihai Xu401202b2012-12-03 11:36:21 -08001358 handleDisable();
Zhihai Xu40874a02012-10-08 17:57:03 -07001359 waitForOnOff(false, false);
1360 } else {
1361 mEnable = false;
Zhihai Xu401202b2012-12-03 11:36:21 -08001362 handleDisable();
Zhihai Xu40874a02012-10-08 17:57:03 -07001363 }
fredc0f420372012-04-12 00:02:00 -07001364 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001365
fredc0f420372012-04-12 00:02:00 -07001366 case MESSAGE_REGISTER_ADAPTER:
1367 {
1368 IBluetoothManagerCallback callback = (IBluetoothManagerCallback) msg.obj;
Marie Janssencb21ad72016-12-13 10:51:02 -08001369 mCallbacks.register(callback);
fredc0f420372012-04-12 00:02:00 -07001370 break;
Marie Janssencb21ad72016-12-13 10:51:02 -08001371 }
fredc0f420372012-04-12 00:02:00 -07001372 case MESSAGE_UNREGISTER_ADAPTER:
1373 {
1374 IBluetoothManagerCallback callback = (IBluetoothManagerCallback) msg.obj;
Marie Janssencb21ad72016-12-13 10:51:02 -08001375 mCallbacks.unregister(callback);
fredc0f420372012-04-12 00:02:00 -07001376 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001377 }
fredc0f420372012-04-12 00:02:00 -07001378 case MESSAGE_REGISTER_STATE_CHANGE_CALLBACK:
1379 {
1380 IBluetoothStateChangeCallback callback = (IBluetoothStateChangeCallback) msg.obj;
Marie Janssencb21ad72016-12-13 10:51:02 -08001381 mStateChangeCallbacks.register(callback);
fredc0f420372012-04-12 00:02:00 -07001382 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001383 }
fredc0f420372012-04-12 00:02:00 -07001384 case MESSAGE_UNREGISTER_STATE_CHANGE_CALLBACK:
1385 {
1386 IBluetoothStateChangeCallback callback = (IBluetoothStateChangeCallback) msg.obj;
Marie Janssencb21ad72016-12-13 10:51:02 -08001387 mStateChangeCallbacks.unregister(callback);
fredc0f420372012-04-12 00:02:00 -07001388 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001389 }
Benjamin Franze8b98922014-11-12 15:57:54 +00001390 case MESSAGE_ADD_PROXY_DELAYED:
1391 {
1392 ProfileServiceConnections psc = mProfileServices.get(
1393 new Integer(msg.arg1));
1394 if (psc == null) {
1395 break;
1396 }
1397 IBluetoothProfileServiceConnection proxy =
1398 (IBluetoothProfileServiceConnection) msg.obj;
1399 psc.addProxy(proxy);
1400 break;
1401 }
1402 case MESSAGE_BIND_PROFILE_SERVICE:
1403 {
1404 ProfileServiceConnections psc = (ProfileServiceConnections) msg.obj;
1405 removeMessages(MESSAGE_BIND_PROFILE_SERVICE, msg.obj);
1406 if (psc == null) {
1407 break;
1408 }
1409 psc.bindService();
1410 break;
1411 }
fredc0f420372012-04-12 00:02:00 -07001412 case MESSAGE_BLUETOOTH_SERVICE_CONNECTED:
1413 {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001414 if (DBG) Slog.d(TAG,"MESSAGE_BLUETOOTH_SERVICE_CONNECTED: " + msg.arg1);
fredc0f420372012-04-12 00:02:00 -07001415
1416 IBinder service = (IBinder) msg.obj;
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001417 try {
1418 mBluetoothLock.writeLock().lock();
Matthew Xieddf7e472013-03-01 18:41:02 -08001419 if (msg.arg1 == SERVICE_IBLUETOOTHGATT) {
1420 mBluetoothGatt = IBluetoothGatt.Stub.asInterface(service);
Nitin Arorad055adb2015-03-02 15:03:51 -08001421 onBluetoothGattServiceUp();
Matthew Xieddf7e472013-03-01 18:41:02 -08001422 break;
1423 } // else must be SERVICE_IBLUETOOTH
1424
1425 //Remove timeout
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001426 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
Matthew Xieddf7e472013-03-01 18:41:02 -08001427
fredc0f420372012-04-12 00:02:00 -07001428 mBinding = false;
Marie Janssen9db28eb2016-01-12 16:05:15 -08001429 mBluetoothBinder = service;
fredc0f420372012-04-12 00:02:00 -07001430 mBluetooth = IBluetooth.Stub.asInterface(service);
fredc0f420372012-04-12 00:02:00 -07001431
Ajay Panicker4bb48302016-03-31 14:14:27 -07001432 if (!isNameAndAddressSet()) {
1433 Message getMsg = mHandler.obtainMessage(MESSAGE_GET_NAME_AND_ADDRESS);
1434 mHandler.sendMessage(getMsg);
1435 if (mGetNameAddressOnly) return;
1436 }
1437
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001438 try {
1439 boolean enableHciSnoopLog = (Settings.Secure.getInt(mContentResolver,
1440 Settings.Secure.BLUETOOTH_HCI_LOG, 0) == 1);
1441 if (!mBluetooth.configHciSnoopLog(enableHciSnoopLog)) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001442 Slog.e(TAG,"IBluetooth.configHciSnoopLog return false");
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001443 }
1444 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001445 Slog.e(TAG,"Unable to call configHciSnoopLog", e);
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001446 }
1447
Matthew Xiecdce0b92012-07-12 19:06:15 -07001448 //Register callback object
fredcbf072a72012-05-09 16:52:50 -07001449 try {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001450 mBluetooth.registerCallback(mBluetoothCallback);
1451 } catch (RemoteException re) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001452 Slog.e(TAG, "Unable to register BluetoothCallback",re);
fredcbf072a72012-05-09 16:52:50 -07001453 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001454 //Inform BluetoothAdapter instances that service is up
Zhihai Xu40874a02012-10-08 17:57:03 -07001455 sendBluetoothServiceUpCallback();
1456
Matthew Xiecdce0b92012-07-12 19:06:15 -07001457 //Do enable request
1458 try {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001459 if (mQuietEnable == false) {
Marie Janssencb21ad72016-12-13 10:51:02 -08001460 if (!mBluetooth.enable()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001461 Slog.e(TAG,"IBluetooth.enable() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001462 }
Marie Janssencb21ad72016-12-13 10:51:02 -08001463 } else {
1464 if (!mBluetooth.enableNoAutoConnect()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001465 Slog.e(TAG,"IBluetooth.enableNoAutoConnect() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001466 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001467 }
1468 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001469 Slog.e(TAG,"Unable to call enable()",e);
Matthew Xiecdce0b92012-07-12 19:06:15 -07001470 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001471 } finally {
1472 mBluetoothLock.writeLock().unlock();
Freda8c6df02012-07-11 10:25:23 -07001473 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001474
1475 if (!mEnable) {
1476 waitForOnOff(true, false);
Zhihai Xu401202b2012-12-03 11:36:21 -08001477 handleDisable();
Zhihai Xu40874a02012-10-08 17:57:03 -07001478 waitForOnOff(false, false);
1479 }
fredc649fe492012-04-19 01:07:18 -07001480 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001481 }
fredcbf072a72012-05-09 16:52:50 -07001482 case MESSAGE_BLUETOOTH_STATE_CHANGE:
fredc0f420372012-04-12 00:02:00 -07001483 {
fredcbf072a72012-05-09 16:52:50 -07001484 int prevState = msg.arg1;
1485 int newState = msg.arg2;
Marie Janssencb21ad72016-12-13 10:51:02 -08001486 if (DBG) {
1487 Slog.d(TAG, "MESSAGE_BLUETOOTH_STATE_CHANGE: " + BluetoothAdapter.nameForState(prevState) + " > " +
1488 BluetoothAdapter.nameForState(newState));
1489 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001490 mState = newState;
1491 bluetoothStateChangeHandler(prevState, newState);
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001492 // handle error state transition case from TURNING_ON to OFF
1493 // unbind and rebind bluetooth service and enable bluetooth
Nitin Arorad055adb2015-03-02 15:03:51 -08001494 if ((prevState == BluetoothAdapter.STATE_BLE_TURNING_ON) &&
Calvin Ona0b91d72016-06-15 17:58:23 -07001495 (newState == BluetoothAdapter.STATE_OFF) &&
1496 (mBluetooth != null) && mEnable) {
Marie Janssen2977c3e2016-11-09 12:01:24 -08001497 recoverBluetoothServiceFromError(false);
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001498 }
Nitin Arorad055adb2015-03-02 15:03:51 -08001499 if ((prevState == BluetoothAdapter.STATE_TURNING_ON) &&
Calvin Ona0b91d72016-06-15 17:58:23 -07001500 (newState == BluetoothAdapter.STATE_BLE_ON) &&
1501 (mBluetooth != null) && mEnable) {
Marie Janssen2977c3e2016-11-09 12:01:24 -08001502 recoverBluetoothServiceFromError(true);
Nitin Arorad055adb2015-03-02 15:03:51 -08001503 }
Calvin Ona0b91d72016-06-15 17:58:23 -07001504 // If we tried to enable BT while BT was in the process of shutting down,
1505 // wait for the BT process to fully tear down and then force a restart
1506 // here. This is a bit of a hack (b/29363429).
1507 if ((prevState == BluetoothAdapter.STATE_BLE_TURNING_OFF) &&
1508 (newState == BluetoothAdapter.STATE_OFF)) {
1509 if (mEnable) {
1510 Slog.d(TAG, "Entering STATE_OFF but mEnabled is true; restarting.");
1511 waitForOnOff(false, true);
1512 Message restartMsg = mHandler.obtainMessage(
1513 MESSAGE_RESTART_BLUETOOTH_SERVICE);
1514 mHandler.sendMessageDelayed(restartMsg, 2 * SERVICE_RESTART_TIME_MS);
1515 }
1516 }
Nitin Arorad055adb2015-03-02 15:03:51 -08001517 if (newState == BluetoothAdapter.STATE_ON ||
Calvin Ona0b91d72016-06-15 17:58:23 -07001518 newState == BluetoothAdapter.STATE_BLE_ON) {
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001519 // bluetooth is working, reset the counter
1520 if (mErrorRecoveryRetryCounter != 0) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001521 Slog.w(TAG, "bluetooth is recovered from error");
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001522 mErrorRecoveryRetryCounter = 0;
1523 }
1524 }
fredc649fe492012-04-19 01:07:18 -07001525 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001526 }
fredc0f420372012-04-12 00:02:00 -07001527 case MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED:
1528 {
Marie Janssencb21ad72016-12-13 10:51:02 -08001529 Slog.e(TAG, "MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED(" + msg.arg1 + ")");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001530 try {
1531 mBluetoothLock.writeLock().lock();
Matthew Xieddf7e472013-03-01 18:41:02 -08001532 if (msg.arg1 == SERVICE_IBLUETOOTH) {
1533 // if service is unbinded already, do nothing and return
1534 if (mBluetooth == null) break;
1535 mBluetooth = null;
1536 } else if (msg.arg1 == SERVICE_IBLUETOOTHGATT) {
1537 mBluetoothGatt = null;
1538 break;
1539 } else {
Marie Janssencb21ad72016-12-13 10:51:02 -08001540 Slog.e(TAG, "Unknown argument for service disconnect!");
Matthew Xieddf7e472013-03-01 18:41:02 -08001541 break;
1542 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001543 } finally {
1544 mBluetoothLock.writeLock().unlock();
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301545 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001546
1547 if (mEnable) {
1548 mEnable = false;
1549 // Send a Bluetooth Restart message
1550 Message restartMsg = mHandler.obtainMessage(
1551 MESSAGE_RESTART_BLUETOOTH_SERVICE);
1552 mHandler.sendMessageDelayed(restartMsg,
1553 SERVICE_RESTART_TIME_MS);
1554 }
1555
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001556 sendBluetoothServiceDownCallback();
Zhihai Xu40874a02012-10-08 17:57:03 -07001557
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001558 // Send BT state broadcast to update
1559 // the BT icon correctly
1560 if ((mState == BluetoothAdapter.STATE_TURNING_ON) ||
Calvin Ona0b91d72016-06-15 17:58:23 -07001561 (mState == BluetoothAdapter.STATE_ON)) {
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001562 bluetoothStateChangeHandler(BluetoothAdapter.STATE_ON,
1563 BluetoothAdapter.STATE_TURNING_OFF);
1564 mState = BluetoothAdapter.STATE_TURNING_OFF;
Zhihai Xu40874a02012-10-08 17:57:03 -07001565 }
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001566 if (mState == BluetoothAdapter.STATE_TURNING_OFF) {
1567 bluetoothStateChangeHandler(BluetoothAdapter.STATE_TURNING_OFF,
1568 BluetoothAdapter.STATE_OFF);
1569 }
1570
1571 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
1572 mState = BluetoothAdapter.STATE_OFF;
fredc649fe492012-04-19 01:07:18 -07001573 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001574 }
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301575 case MESSAGE_RESTART_BLUETOOTH_SERVICE:
1576 {
Marie Janssencb21ad72016-12-13 10:51:02 -08001577 Slog.d(TAG, "MESSAGE_RESTART_BLUETOOTH_SERVICE");
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301578 /* Enable without persisting the setting as
1579 it doesnt change when IBluetooth
1580 service restarts */
Zhihai Xu40874a02012-10-08 17:57:03 -07001581 mEnable = true;
Zhihai Xu401202b2012-12-03 11:36:21 -08001582 handleEnable(mQuietEnable);
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301583 break;
1584 }
Marie Janssencb21ad72016-12-13 10:51:02 -08001585 case MESSAGE_TIMEOUT_BIND: {
1586 Slog.e(TAG, "MESSAGE_TIMEOUT_BIND");
1587 mBluetoothLock.writeLock().lock();
1588 mBinding = false;
1589 mBluetoothLock.writeLock().unlock();
1590 break;
1591 }
fredc0f420372012-04-12 00:02:00 -07001592 case MESSAGE_TIMEOUT_UNBIND:
1593 {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001594 Slog.e(TAG, "MESSAGE_TIMEOUT_UNBIND");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001595 mBluetoothLock.writeLock().lock();
1596 mUnbinding = false;
1597 mBluetoothLock.writeLock().unlock();
fredc649fe492012-04-19 01:07:18 -07001598 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001599 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001600
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001601 case MESSAGE_USER_SWITCHED: {
1602 if (DBG) Slog.d(TAG, "MESSAGE_USER_SWITCHED");
Zhihai Xu40874a02012-10-08 17:57:03 -07001603 mHandler.removeMessages(MESSAGE_USER_SWITCHED);
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001604
Zhihai Xu40874a02012-10-08 17:57:03 -07001605 /* disable and enable BT when detect a user switch */
1606 if (mEnable && mBluetooth != null) {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001607 try {
1608 mBluetoothLock.readLock().lock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001609 if (mBluetooth != null) {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001610 mBluetooth.unregisterCallback(mBluetoothCallback);
Zhihai Xu40874a02012-10-08 17:57:03 -07001611 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001612 } catch (RemoteException re) {
1613 Slog.e(TAG, "Unable to unregister", re);
1614 } finally {
1615 mBluetoothLock.readLock().unlock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001616 }
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001617
1618 if (mState == BluetoothAdapter.STATE_TURNING_OFF) {
1619 // MESSAGE_USER_SWITCHED happened right after MESSAGE_ENABLE
1620 bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_OFF);
1621 mState = BluetoothAdapter.STATE_OFF;
1622 }
1623 if (mState == BluetoothAdapter.STATE_OFF) {
1624 bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_TURNING_ON);
1625 mState = BluetoothAdapter.STATE_TURNING_ON;
1626 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001627
1628 waitForOnOff(true, false);
1629
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001630 if (mState == BluetoothAdapter.STATE_TURNING_ON) {
1631 bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_ON);
1632 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001633
Benjamin Franze8b98922014-11-12 15:57:54 +00001634 unbindAllBluetoothProfileServices();
Zhihai Xu40874a02012-10-08 17:57:03 -07001635 // disable
Zhihai Xu401202b2012-12-03 11:36:21 -08001636 handleDisable();
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001637 // Pbap service need receive STATE_TURNING_OFF intent to close
1638 bluetoothStateChangeHandler(BluetoothAdapter.STATE_ON,
1639 BluetoothAdapter.STATE_TURNING_OFF);
Zhihai Xu40874a02012-10-08 17:57:03 -07001640
Pavlin Radoslavov41401112016-06-27 15:25:18 -07001641 boolean didDisableTimeout = !waitForOnOff(false, true);
Zhihai Xu40874a02012-10-08 17:57:03 -07001642
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001643 bluetoothStateChangeHandler(BluetoothAdapter.STATE_TURNING_OFF,
Zhihai Xu40874a02012-10-08 17:57:03 -07001644 BluetoothAdapter.STATE_OFF);
Zhihai Xu40874a02012-10-08 17:57:03 -07001645 sendBluetoothServiceDownCallback();
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001646
Pavlin Radoslavove957a8a2016-05-24 15:28:41 -07001647 try {
1648 mBluetoothLock.writeLock().lock();
1649 if (mBluetooth != null) {
1650 mBluetooth = null;
1651 // Unbind
1652 mContext.unbindService(mConnection);
1653 }
1654 mBluetoothGatt = null;
1655 } finally {
1656 mBluetoothLock.writeLock().unlock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001657 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001658
Pavlin Radoslavov41401112016-06-27 15:25:18 -07001659 //
1660 // If disabling Bluetooth times out, wait for an
1661 // additional amount of time to ensure the process is
1662 // shut down completely before attempting to restart.
1663 //
1664 if (didDisableTimeout) {
1665 SystemClock.sleep(3000);
1666 } else {
1667 SystemClock.sleep(100);
1668 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001669
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001670 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
1671 mState = BluetoothAdapter.STATE_OFF;
Zhihai Xu40874a02012-10-08 17:57:03 -07001672 // enable
Zhihai Xu401202b2012-12-03 11:36:21 -08001673 handleEnable(mQuietEnable);
John Spurlock8a985d22014-02-25 09:40:05 -05001674 } else if (mBinding || mBluetooth != null) {
Zhihai Xu40874a02012-10-08 17:57:03 -07001675 Message userMsg = mHandler.obtainMessage(MESSAGE_USER_SWITCHED);
1676 userMsg.arg2 = 1 + msg.arg2;
Marie Janssencb21ad72016-12-13 10:51:02 -08001677 // if user is switched when service is binding retry after a delay
Zhihai Xu40874a02012-10-08 17:57:03 -07001678 mHandler.sendMessageDelayed(userMsg, USER_SWITCHED_TIME_MS);
1679 if (DBG) {
Marie Janssencb21ad72016-12-13 10:51:02 -08001680 Slog.d(TAG, "Retry MESSAGE_USER_SWITCHED " + userMsg.arg2);
Zhihai Xu40874a02012-10-08 17:57:03 -07001681 }
John Spurlock8a985d22014-02-25 09:40:05 -05001682 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001683 break;
1684 }
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001685 case MESSAGE_USER_UNLOCKED: {
1686 if (DBG) Slog.d(TAG, "MESSAGE_USER_UNLOCKED");
1687 mHandler.removeMessages(MESSAGE_USER_SWITCHED);
1688
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001689 if (mEnable && !mBinding && (mBluetooth == null)) {
1690 // We should be connected, but we gave up for some
1691 // reason; maybe the Bluetooth service wasn't encryption
1692 // aware, so try binding again.
1693 if (DBG) Slog.d(TAG, "Enabled but not bound; retrying after unlock");
1694 handleEnable(mQuietEnable);
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001695 }
1696 }
fredc0f420372012-04-12 00:02:00 -07001697 }
1698 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001699 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001700
Zhihai Xu401202b2012-12-03 11:36:21 -08001701 private void handleEnable(boolean quietMode) {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001702 mQuietEnable = quietMode;
1703
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001704 try {
1705 mBluetoothLock.writeLock().lock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001706 if ((mBluetooth == null) && (!mBinding)) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001707 //Start bind timeout and bind
1708 Message timeoutMsg=mHandler.obtainMessage(MESSAGE_TIMEOUT_BIND);
1709 mHandler.sendMessageDelayed(timeoutMsg,TIMEOUT_BIND_MS);
Matthew Xiecdce0b92012-07-12 19:06:15 -07001710 Intent i = new Intent(IBluetooth.class.getName());
Dianne Hackbornce09f5a2014-10-10 15:03:13 -07001711 if (!doBind(i, mConnection,Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT,
1712 UserHandle.CURRENT)) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001713 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
Zhihai Xu40874a02012-10-08 17:57:03 -07001714 } else {
1715 mBinding = true;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001716 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001717 } else if (mBluetooth != null) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001718 //Enable bluetooth
1719 try {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001720 if (!mQuietEnable) {
1721 if(!mBluetooth.enable()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001722 Slog.e(TAG,"IBluetooth.enable() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001723 }
1724 }
1725 else {
1726 if(!mBluetooth.enableNoAutoConnect()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001727 Slog.e(TAG,"IBluetooth.enableNoAutoConnect() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001728 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001729 }
1730 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001731 Slog.e(TAG,"Unable to call enable()",e);
Matthew Xiecdce0b92012-07-12 19:06:15 -07001732 }
1733 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001734 } finally {
1735 mBluetoothLock.writeLock().unlock();
Matthew Xiecdce0b92012-07-12 19:06:15 -07001736 }
1737 }
1738
Dianne Hackborn221ea892013-08-04 16:50:16 -07001739 boolean doBind(Intent intent, ServiceConnection conn, int flags, UserHandle user) {
1740 ComponentName comp = intent.resolveSystemService(mContext.getPackageManager(), 0);
1741 intent.setComponent(comp);
1742 if (comp == null || !mContext.bindServiceAsUser(intent, conn, flags, user)) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001743 Slog.e(TAG, "Fail to bind to: " + intent);
Dianne Hackborn221ea892013-08-04 16:50:16 -07001744 return false;
1745 }
1746 return true;
1747 }
1748
Zhihai Xu401202b2012-12-03 11:36:21 -08001749 private void handleDisable() {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001750 try {
1751 mBluetoothLock.readLock().lock();
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001752 if (mBluetooth != null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001753 if (DBG) Slog.d(TAG,"Sending off request.");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001754 if (!mBluetooth.disable()) {
1755 Slog.e(TAG,"IBluetooth.disable() returned false");
Matthew Xiecdce0b92012-07-12 19:06:15 -07001756 }
1757 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001758 } catch (RemoteException e) {
1759 Slog.e(TAG,"Unable to call disable()",e);
1760 } finally {
1761 mBluetoothLock.readLock().unlock();
Matthew Xiecdce0b92012-07-12 19:06:15 -07001762 }
1763 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001764
1765 private boolean checkIfCallerIsForegroundUser() {
1766 int foregroundUser;
1767 int callingUser = UserHandle.getCallingUserId();
Martijn Coenen8385c5a2012-11-29 10:14:16 -08001768 int callingUid = Binder.getCallingUid();
Zhihai Xu40874a02012-10-08 17:57:03 -07001769 long callingIdentity = Binder.clearCallingIdentity();
Benjamin Franze8b98922014-11-12 15:57:54 +00001770 UserManager um = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
1771 UserInfo ui = um.getProfileParent(callingUser);
1772 int parentUser = (ui != null) ? ui.id : UserHandle.USER_NULL;
Martijn Coenen8385c5a2012-11-29 10:14:16 -08001773 int callingAppId = UserHandle.getAppId(callingUid);
Zhihai Xu40874a02012-10-08 17:57:03 -07001774 boolean valid = false;
1775 try {
1776 foregroundUser = ActivityManager.getCurrentUser();
Martijn Coenen8385c5a2012-11-29 10:14:16 -08001777 valid = (callingUser == foregroundUser) ||
Benjamin Franze8b98922014-11-12 15:57:54 +00001778 parentUser == foregroundUser ||
Adrian Roosbd9a9a52014-08-18 15:31:57 +02001779 callingAppId == Process.NFC_UID ||
1780 callingAppId == mSystemUiUid;
Marie Janssencb21ad72016-12-13 10:51:02 -08001781 if (DBG && !valid) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001782 Slog.d(TAG, "checkIfCallerIsForegroundUser: valid=" + valid
Zhihai Xu40874a02012-10-08 17:57:03 -07001783 + " callingUser=" + callingUser
Benjamin Franze8b98922014-11-12 15:57:54 +00001784 + " parentUser=" + parentUser
Zhihai Xu40874a02012-10-08 17:57:03 -07001785 + " foregroundUser=" + foregroundUser);
1786 }
1787 } finally {
1788 Binder.restoreCallingIdentity(callingIdentity);
1789 }
1790 return valid;
1791 }
1792
Nitin Arorad055adb2015-03-02 15:03:51 -08001793 private void sendBleStateChanged(int prevState, int newState) {
Marie Janssencb21ad72016-12-13 10:51:02 -08001794 if (DBG) Slog.d(TAG,"Sending BLE State Change: " + BluetoothAdapter.nameForState(prevState) +
1795 " > " + BluetoothAdapter.nameForState(newState));
Nitin Arorad055adb2015-03-02 15:03:51 -08001796 // Send broadcast message to everyone else
1797 Intent intent = new Intent(BluetoothAdapter.ACTION_BLE_STATE_CHANGED);
1798 intent.putExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE, prevState);
1799 intent.putExtra(BluetoothAdapter.EXTRA_STATE, newState);
1800 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1801 mContext.sendBroadcastAsUser(intent, UserHandle.ALL, BLUETOOTH_PERM);
1802 }
1803
Zhihai Xu40874a02012-10-08 17:57:03 -07001804 private void bluetoothStateChangeHandler(int prevState, int newState) {
Nitin Arorad055adb2015-03-02 15:03:51 -08001805 boolean isStandardBroadcast = true;
Marie Janssencb21ad72016-12-13 10:51:02 -08001806 if (prevState == newState) { // No change. Nothing to do.
1807 return;
1808 }
1809 // Notify all proxy objects first of adapter state change
1810 if (newState == BluetoothAdapter.STATE_BLE_ON ||
1811 newState == BluetoothAdapter.STATE_OFF) {
1812 boolean intermediate_off = (prevState == BluetoothAdapter.STATE_TURNING_OFF
1813 && newState == BluetoothAdapter.STATE_BLE_ON);
Zhihai Xu40874a02012-10-08 17:57:03 -07001814
Marie Janssencb21ad72016-12-13 10:51:02 -08001815 if (newState == BluetoothAdapter.STATE_OFF) {
1816 // If Bluetooth is off, send service down event to proxy objects, and unbind
1817 if (DBG) Slog.d(TAG, "Bluetooth is complete send Service Down");
1818 sendBluetoothServiceDownCallback();
1819 unbindAndFinish();
Nitin Arorad055adb2015-03-02 15:03:51 -08001820 sendBleStateChanged(prevState, newState);
Marie Janssencb21ad72016-12-13 10:51:02 -08001821 // Don't broadcast as it has already been broadcast before
Nitin Arorad055adb2015-03-02 15:03:51 -08001822 isStandardBroadcast = false;
1823
Marie Janssencb21ad72016-12-13 10:51:02 -08001824 } else if (!intermediate_off) {
1825 // connect to GattService
1826 if (DBG) Slog.d(TAG, "Bluetooth is in LE only mode");
1827 if (mBluetoothGatt != null) {
1828 if (DBG) Slog.d(TAG, "Calling BluetoothGattServiceUp");
1829 onBluetoothGattServiceUp();
1830 } else {
1831 if (DBG) Slog.d(TAG, "Binding Bluetooth GATT service");
1832 if (mContext.getPackageManager().hasSystemFeature(
1833 PackageManager.FEATURE_BLUETOOTH_LE)) {
1834 Intent i = new Intent(IBluetoothGatt.class.getName());
1835 doBind(i, mConnection, Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT, UserHandle.CURRENT);
1836 }
Nitin Arorad055adb2015-03-02 15:03:51 -08001837 }
Marie Janssencb21ad72016-12-13 10:51:02 -08001838 sendBleStateChanged(prevState, newState);
1839 //Don't broadcase this as std intent
1840 isStandardBroadcast = false;
1841
1842 } else if (intermediate_off) {
1843 if (DBG) Slog.d(TAG, "Intermediate off, back to LE only mode");
1844 // For LE only mode, broadcast as is
1845 sendBleStateChanged(prevState, newState);
1846 sendBluetoothStateCallback(false); // BT is OFF for general users
1847 // Broadcast as STATE_OFF
1848 newState = BluetoothAdapter.STATE_OFF;
1849 sendBrEdrDownCallback();
Nitin Arorad055adb2015-03-02 15:03:51 -08001850 }
Marie Janssencb21ad72016-12-13 10:51:02 -08001851 } else if (newState == BluetoothAdapter.STATE_ON) {
1852 boolean isUp = (newState == BluetoothAdapter.STATE_ON);
1853 sendBluetoothStateCallback(isUp);
1854 sendBleStateChanged(prevState, newState);
1855
1856 } else if (newState == BluetoothAdapter.STATE_BLE_TURNING_ON ||
1857 newState == BluetoothAdapter.STATE_BLE_TURNING_OFF ) {
1858 sendBleStateChanged(prevState, newState);
1859 isStandardBroadcast = false;
1860
1861 } else if (newState == BluetoothAdapter.STATE_TURNING_ON ||
1862 newState == BluetoothAdapter.STATE_TURNING_OFF) {
1863 sendBleStateChanged(prevState, newState);
1864 }
1865
1866 if (isStandardBroadcast) {
1867 if (prevState == BluetoothAdapter.STATE_BLE_ON) {
1868 // Show prevState of BLE_ON as OFF to standard users
1869 prevState = BluetoothAdapter.STATE_OFF;
1870 }
1871 Intent intent = new Intent(BluetoothAdapter.ACTION_STATE_CHANGED);
1872 intent.putExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE, prevState);
1873 intent.putExtra(BluetoothAdapter.EXTRA_STATE, newState);
1874 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1875 mContext.sendBroadcastAsUser(intent, UserHandle.ALL, BLUETOOTH_PERM);
Zhihai Xu40874a02012-10-08 17:57:03 -07001876 }
1877 }
1878
1879 /**
1880 * if on is true, wait for state become ON
1881 * if off is true, wait for state become OFF
1882 * if both on and off are false, wait for state not ON
1883 */
1884 private boolean waitForOnOff(boolean on, boolean off) {
1885 int i = 0;
1886 while (i < 10) {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001887 try {
1888 mBluetoothLock.readLock().lock();
1889 if (mBluetooth == null) break;
1890 if (on) {
1891 if (mBluetooth.getState() == BluetoothAdapter.STATE_ON) return true;
1892 } else if (off) {
1893 if (mBluetooth.getState() == BluetoothAdapter.STATE_OFF) return true;
1894 } else {
1895 if (mBluetooth.getState() != BluetoothAdapter.STATE_ON) return true;
Zhihai Xu40874a02012-10-08 17:57:03 -07001896 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001897 } catch (RemoteException e) {
1898 Slog.e(TAG, "getState()", e);
1899 break;
1900 } finally {
1901 mBluetoothLock.readLock().unlock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001902 }
1903 if (on || off) {
1904 SystemClock.sleep(300);
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07001905 } else {
Zhihai Xu40874a02012-10-08 17:57:03 -07001906 SystemClock.sleep(50);
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07001907 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001908 i++;
1909 }
Jeff Sharkey67609c72016-03-05 14:29:13 -07001910 Slog.e(TAG,"waitForOnOff time out");
Zhihai Xu40874a02012-10-08 17:57:03 -07001911 return false;
1912 }
Zhihai Xu681ae7f2012-11-12 15:14:18 -08001913
Marie Janssen59804562016-12-28 14:13:21 -08001914 private void sendDisableMsg(String packageName) {
Zhihai Xu401202b2012-12-03 11:36:21 -08001915 mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_DISABLE));
Marie Janssen59804562016-12-28 14:13:21 -08001916 addActiveLog(packageName, false);
Zhihai Xu401202b2012-12-03 11:36:21 -08001917 }
1918
Marie Janssen59804562016-12-28 14:13:21 -08001919 private void sendEnableMsg(boolean quietMode, String packageName) {
Zhihai Xu401202b2012-12-03 11:36:21 -08001920 mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_ENABLE,
1921 quietMode ? 1 : 0, 0));
Marie Janssen59804562016-12-28 14:13:21 -08001922 addActiveLog(packageName, true);
1923 }
1924
1925 private void addActiveLog(String packageName, boolean enable) {
1926 synchronized (mActiveLogs) {
1927 if (mActiveLogs.size() > 10) {
1928 mActiveLogs.remove();
1929 }
1930 mActiveLogs.add(new ActiveLog(packageName, enable, System.currentTimeMillis()));
1931 }
Zhihai Xu401202b2012-12-03 11:36:21 -08001932 }
1933
Marie Janssen2977c3e2016-11-09 12:01:24 -08001934 private void recoverBluetoothServiceFromError(boolean clearBle) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001935 Slog.e(TAG,"recoverBluetoothServiceFromError");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001936 try {
1937 mBluetoothLock.readLock().lock();
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001938 if (mBluetooth != null) {
1939 //Unregister callback object
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001940 mBluetooth.unregisterCallback(mBluetoothCallback);
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001941 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001942 } catch (RemoteException re) {
1943 Slog.e(TAG, "Unable to unregister", re);
1944 } finally {
1945 mBluetoothLock.readLock().unlock();
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001946 }
1947
1948 SystemClock.sleep(500);
1949
1950 // disable
1951 handleDisable();
1952
1953 waitForOnOff(false, true);
1954
1955 sendBluetoothServiceDownCallback();
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001956
Pavlin Radoslavove957a8a2016-05-24 15:28:41 -07001957 try {
1958 mBluetoothLock.writeLock().lock();
1959 if (mBluetooth != null) {
1960 mBluetooth = null;
1961 // Unbind
1962 mContext.unbindService(mConnection);
1963 }
1964 mBluetoothGatt = null;
1965 } finally {
1966 mBluetoothLock.writeLock().unlock();
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001967 }
1968
1969 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
1970 mState = BluetoothAdapter.STATE_OFF;
1971
Marie Janssen2977c3e2016-11-09 12:01:24 -08001972 if (clearBle) {
1973 clearBleApps();
1974 }
1975
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001976 mEnable = false;
1977
1978 if (mErrorRecoveryRetryCounter++ < MAX_ERROR_RESTART_RETRIES) {
1979 // Send a Bluetooth Restart message to reenable bluetooth
1980 Message restartMsg = mHandler.obtainMessage(
1981 MESSAGE_RESTART_BLUETOOTH_SERVICE);
1982 mHandler.sendMessageDelayed(restartMsg, ERROR_RESTART_TIME_MS);
1983 } else {
1984 // todo: notify user to power down and power up phone to make bluetooth work.
1985 }
1986 }
Mike Lockwood726d4de2014-10-28 14:06:28 -07001987
Lenka Trochtova13a05192016-12-02 12:19:39 +01001988 private boolean isBluetoothDisallowed() {
1989 long callingIdentity = Binder.clearCallingIdentity();
1990 try {
1991 return mContext.getSystemService(UserManager.class)
1992 .hasUserRestriction(UserManager.DISALLOW_BLUETOOTH, UserHandle.SYSTEM);
1993 } finally {
1994 Binder.restoreCallingIdentity(callingIdentity);
1995 }
1996 }
1997
Mike Lockwood726d4de2014-10-28 14:06:28 -07001998 @Override
Pavlin Radoslavov6e8faff2016-02-23 11:54:37 -08001999 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2000 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DUMP, TAG);
2001 String errorMsg = null;
Marie Janssen59804562016-12-28 14:13:21 -08002002
2003 boolean protoOut = (args.length > 0) && args[0].startsWith("--proto");
2004
2005 if (!protoOut) {
2006 writer.println("Bluetooth Status");
2007 writer.println(" enabled: " + isEnabled());
2008 writer.println(" state: " + BluetoothAdapter.nameForState(mState));
2009 writer.println(" address: " + mAddress);
2010 writer.println(" name: " + mName);
2011 if (mEnable) {
2012 long onDuration = System.currentTimeMillis() - mActiveLogs.getLast().getTime();
2013 String onDurationString = String.format("%02d:%02d:%02d.%03d",
2014 (int)(onDuration / (1000 * 60 * 60)),
2015 (int)((onDuration / (1000 * 60)) % 60),
2016 (int)((onDuration / 1000) % 60),
2017 (int)(onDuration % 1000));
2018 writer.println(" time since enabled: " + onDurationString + "\n");
2019 }
2020
2021 writer.println("Enable log:");
2022 for (ActiveLog log : mActiveLogs) {
2023 writer.println(log);
2024 }
2025
2026 writer.println("\n" + mBleApps.size() + " BLE Apps registered:");
2027 for (ClientDeathRecipient app : mBleApps.values()) {
2028 writer.println(app.getPackageName());
2029 }
2030
2031 writer.flush();
2032 }
2033
Pavlin Radoslavov6e8faff2016-02-23 11:54:37 -08002034 if (mBluetoothBinder == null) {
2035 errorMsg = "Bluetooth Service not connected";
2036 } else {
2037 try {
2038 mBluetoothBinder.dump(fd, args);
2039 } catch (RemoteException re) {
Marie Janssen59804562016-12-28 14:13:21 -08002040 errorMsg = "RemoteException while dumping Bluetooth Service";
Pavlin Radoslavov6e8faff2016-02-23 11:54:37 -08002041 }
Mike Lockwood726d4de2014-10-28 14:06:28 -07002042 }
Pavlin Radoslavov6e8faff2016-02-23 11:54:37 -08002043 if (errorMsg != null) {
2044 // Silently return if we are extracting metrics in Protobuf format
Marie Janssen59804562016-12-28 14:13:21 -08002045 if (protoOut) return;
Pavlin Radoslavov6e8faff2016-02-23 11:54:37 -08002046 writer.println(errorMsg);
2047 }
Mike Lockwood726d4de2014-10-28 14:06:28 -07002048 }
fredc0f420372012-04-12 00:02:00 -07002049}