blob: 3b3ce073e0992402fef56d9647231c27c92b0d4d [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;
Lenka Trochtovac6f0e232017-01-17 10:35:49 +010052import android.os.ServiceManager;
Zhihai Xu40874a02012-10-08 17:57:03 -070053import android.os.SystemClock;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070054import android.os.UserHandle;
Benjamin Franze8b98922014-11-12 15:57:54 +000055import android.os.UserManager;
Lenka Trochtova13a05192016-12-02 12:19:39 +010056import android.os.UserManagerInternal;
57import android.os.UserManagerInternal.UserRestrictionsListener;
fredc0f420372012-04-12 00:02:00 -070058import android.provider.Settings;
Wei Wang67d84162015-04-26 17:04:29 -070059import android.provider.Settings.SettingNotFoundException;
Jeff Sharkey67609c72016-03-05 14:29:13 -070060import android.util.Slog;
Mike Lockwood726d4de2014-10-28 14:06:28 -070061
Lenka Trochtovac6f0e232017-01-17 10:35:49 +010062import com.android.server.pm.PackageManagerService;
63
Mike Lockwood726d4de2014-10-28 14:06:28 -070064import java.io.FileDescriptor;
65import java.io.PrintWriter;
Marie Janssen2977c3e2016-11-09 12:01:24 -080066import java.util.concurrent.ConcurrentHashMap;
Marie Janssen59804562016-12-28 14:13:21 -080067import java.util.concurrent.locks.ReentrantReadWriteLock;
Benjamin Franze8b98922014-11-12 15:57:54 +000068import java.util.HashMap;
Marie Janssen59804562016-12-28 14:13:21 -080069import java.util.LinkedList;
Benjamin Franze8b98922014-11-12 15:57:54 +000070import java.util.Map;
Miao Chou658bf2f2015-06-26 17:14:35 -070071
Marie Janssen59804562016-12-28 14:13:21 -080072
fredc0f420372012-04-12 00:02:00 -070073class BluetoothManagerService extends IBluetoothManager.Stub {
74 private static final String TAG = "BluetoothManagerService";
Pavlin Radoslavov41401112016-06-27 15:25:18 -070075 private static final boolean DBG = true;
fredc0f420372012-04-12 00:02:00 -070076
fredc0f420372012-04-12 00:02:00 -070077 private static final String BLUETOOTH_ADMIN_PERM = android.Manifest.permission.BLUETOOTH_ADMIN;
78 private static final String BLUETOOTH_PERM = android.Manifest.permission.BLUETOOTH;
fredc0f420372012-04-12 00:02:00 -070079 private static final String ACTION_SERVICE_STATE_CHANGED="com.android.bluetooth.btservice.action.STATE_CHANGED";
80 private static final String EXTRA_ACTION="action";
Zhihai Xud31c3222012-10-31 16:08:57 -070081 private static final String SECURE_SETTINGS_BLUETOOTH_ADDR_VALID="bluetooth_addr_valid";
fredc0f420372012-04-12 00:02:00 -070082 private static final String SECURE_SETTINGS_BLUETOOTH_ADDRESS="bluetooth_address";
83 private static final String SECURE_SETTINGS_BLUETOOTH_NAME="bluetooth_name";
fredc0f420372012-04-12 00:02:00 -070084 private static final int TIMEOUT_BIND_MS = 3000; //Maximum msec to wait for a bind
85 private static final int TIMEOUT_SAVE_MS = 500; //Maximum msec to wait for a save
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +053086 //Maximum msec to wait for service restart
87 private static final int SERVICE_RESTART_TIME_MS = 200;
Zhihai Xudd9d17d2013-01-08 17:05:58 -080088 //Maximum msec to wait for restart due to error
89 private static final int ERROR_RESTART_TIME_MS = 3000;
Zhihai Xu40874a02012-10-08 17:57:03 -070090 //Maximum msec to delay MESSAGE_USER_SWITCHED
91 private static final int USER_SWITCHED_TIME_MS = 200;
Benjamin Franze8b98922014-11-12 15:57:54 +000092 // Delay for the addProxy function in msec
93 private static final int ADD_PROXY_DELAY_MS = 100;
fredc0f420372012-04-12 00:02:00 -070094
95 private static final int MESSAGE_ENABLE = 1;
96 private static final int MESSAGE_DISABLE = 2;
fredc649fe492012-04-19 01:07:18 -070097 private static final int MESSAGE_REGISTER_ADAPTER = 20;
98 private static final int MESSAGE_UNREGISTER_ADAPTER = 21;
99 private static final int MESSAGE_REGISTER_STATE_CHANGE_CALLBACK = 30;
100 private static final int MESSAGE_UNREGISTER_STATE_CHANGE_CALLBACK = 31;
101 private static final int MESSAGE_BLUETOOTH_SERVICE_CONNECTED = 40;
102 private static final int MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED = 41;
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +0530103 private static final int MESSAGE_RESTART_BLUETOOTH_SERVICE = 42;
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -0700104 private static final int MESSAGE_BLUETOOTH_STATE_CHANGE = 60;
105 private static final int MESSAGE_TIMEOUT_BIND = 100;
106 private static final int MESSAGE_TIMEOUT_UNBIND = 101;
Ajay Panicker4bb48302016-03-31 14:14:27 -0700107 private static final int MESSAGE_GET_NAME_AND_ADDRESS = 200;
Zhihai Xu40874a02012-10-08 17:57:03 -0700108 private static final int MESSAGE_USER_SWITCHED = 300;
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -0700109 private static final int MESSAGE_USER_UNLOCKED = 301;
Benjamin Franze8b98922014-11-12 15:57:54 +0000110 private static final int MESSAGE_ADD_PROXY_DELAYED = 400;
111 private static final int MESSAGE_BIND_PROFILE_SERVICE = 401;
Marie Janssencb21ad72016-12-13 10:51:02 -0800112
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -0700113 private static final int MAX_SAVE_RETRIES = 3;
114 private static final int MAX_ERROR_RESTART_RETRIES = 6;
Zhihai Xudd9d17d2013-01-08 17:05:58 -0800115
Zhihai Xu401202b2012-12-03 11:36:21 -0800116 // Bluetooth persisted setting is off
117 private static final int BLUETOOTH_OFF=0;
118 // Bluetooth persisted setting is on
119 // and Airplane mode won't affect Bluetooth state at start up
120 private static final int BLUETOOTH_ON_BLUETOOTH=1;
121 // Bluetooth persisted setting is on
122 // but Airplane mode will affect Bluetooth state at start up
123 // and Airplane mode will have higher priority.
124 private static final int BLUETOOTH_ON_AIRPLANE=2;
fredc0f420372012-04-12 00:02:00 -0700125
Matthew Xieddf7e472013-03-01 18:41:02 -0800126 private static final int SERVICE_IBLUETOOTH = 1;
127 private static final int SERVICE_IBLUETOOTHGATT = 2;
128
fredc0f420372012-04-12 00:02:00 -0700129 private final Context mContext;
Matthew Xiecdce0b92012-07-12 19:06:15 -0700130
131 // Locks are not provided for mName and mAddress.
132 // They are accessed in handler or broadcast receiver, same thread context.
fredc0f420372012-04-12 00:02:00 -0700133 private String mAddress;
134 private String mName;
Matthew Xie6fde3092012-07-11 17:10:07 -0700135 private final ContentResolver mContentResolver;
136 private final RemoteCallbackList<IBluetoothManagerCallback> mCallbacks;
137 private final RemoteCallbackList<IBluetoothStateChangeCallback> mStateChangeCallbacks;
Marie Janssen9db28eb2016-01-12 16:05:15 -0800138 private IBinder mBluetoothBinder;
fredc649fe492012-04-19 01:07:18 -0700139 private IBluetooth mBluetooth;
Matthew Xieddf7e472013-03-01 18:41:02 -0800140 private IBluetoothGatt mBluetoothGatt;
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700141 private final ReentrantReadWriteLock mBluetoothLock =
142 new ReentrantReadWriteLock();
fredc649fe492012-04-19 01:07:18 -0700143 private boolean mBinding;
144 private boolean mUnbinding;
Marie Janssen59804562016-12-28 14:13:21 -0800145
Zhihai Xu401202b2012-12-03 11:36:21 -0800146 // used inside handler thread
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700147 private boolean mQuietEnable = false;
Marie Janssen59804562016-12-28 14:13:21 -0800148 private boolean mEnable;
149
150 /**
151 * Used for tracking apps that enabled / disabled Bluetooth.
152 */
153 private class ActiveLog {
154 private String mPackageName;
155 private boolean mEnable;
156 private long mTimestamp;
157
158 public ActiveLog(String packageName, boolean enable, long timestamp) {
159 mPackageName = packageName;
160 mEnable = enable;
161 mTimestamp = timestamp;
162 }
163
164 public long getTime() {
165 return mTimestamp;
166 }
167
168 public String toString() {
169 return android.text.format.DateFormat.format("MM-dd hh:mm:ss ", mTimestamp) +
170 (mEnable ? " Enabled " : " Disabled ") + " by " + mPackageName;
171 }
172
173 }
174
175 private LinkedList<ActiveLog> mActiveLogs;
176
177 // configuration from external IBinder call which is used to
Zhihai Xu401202b2012-12-03 11:36:21 -0800178 // synchronize with broadcast receiver.
179 private boolean mQuietEnableExternal;
Zhihai Xu401202b2012-12-03 11:36:21 -0800180 private boolean mEnableExternal;
Marie Janssen59804562016-12-28 14:13:21 -0800181
182 // Map of apps registered to keep BLE scanning on.
183 private Map<IBinder, ClientDeathRecipient> mBleApps = new ConcurrentHashMap<IBinder, ClientDeathRecipient>();
184
Zhihai Xu40874a02012-10-08 17:57:03 -0700185 private int mState;
Zhihai Xu40874a02012-10-08 17:57:03 -0700186 private final BluetoothHandler mHandler;
Zhihai Xudd9d17d2013-01-08 17:05:58 -0800187 private int mErrorRecoveryRetryCounter;
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200188 private final int mSystemUiUid;
fredc0f420372012-04-12 00:02:00 -0700189
Benjamin Franze8b98922014-11-12 15:57:54 +0000190 // Save a ProfileServiceConnections object for each of the bound
191 // bluetooth profile services
192 private final Map <Integer, ProfileServiceConnections> mProfileServices =
193 new HashMap <Integer, ProfileServiceConnections>();
194
Svetoslav Ganovc2ac5bd2016-06-29 17:31:44 -0700195 private final boolean mPermissionReviewRequired;
196
fredc649fe492012-04-19 01:07:18 -0700197 private void registerForAirplaneMode(IntentFilter filter) {
198 final ContentResolver resolver = mContext.getContentResolver();
Christopher Tatec09cdce2012-09-10 16:50:14 -0700199 final String airplaneModeRadios = Settings.Global.getString(resolver,
200 Settings.Global.AIRPLANE_MODE_RADIOS);
201 final String toggleableRadios = Settings.Global.getString(resolver,
202 Settings.Global.AIRPLANE_MODE_TOGGLEABLE_RADIOS);
fredc649fe492012-04-19 01:07:18 -0700203 boolean mIsAirplaneSensitive = airplaneModeRadios == null ? true :
Christopher Tatec09cdce2012-09-10 16:50:14 -0700204 airplaneModeRadios.contains(Settings.Global.RADIO_BLUETOOTH);
fredc649fe492012-04-19 01:07:18 -0700205 if (mIsAirplaneSensitive) {
206 filter.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED);
207 }
208 }
209
Marie Janssen59804562016-12-28 14:13:21 -0800210 private final IBluetoothCallback mBluetoothCallback = new IBluetoothCallback.Stub() {
fredcbf072a72012-05-09 16:52:50 -0700211 @Override
212 public void onBluetoothStateChange(int prevState, int newState) throws RemoteException {
213 Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_STATE_CHANGE,prevState,newState);
214 mHandler.sendMessage(msg);
215 }
216 };
217
Lenka Trochtova13a05192016-12-02 12:19:39 +0100218 private final UserRestrictionsListener mUserRestrictionsListener =
219 new UserRestrictionsListener() {
220 @Override
221 public void onUserRestrictionsChanged(int userId, Bundle newRestrictions,
222 Bundle prevRestrictions) {
Lenka Trochtovac6f0e232017-01-17 10:35:49 +0100223 if (!newRestrictions.containsKey(UserManager.DISALLOW_BLUETOOTH)
224 && !prevRestrictions.containsKey(UserManager.DISALLOW_BLUETOOTH)) {
225 // The relevant restriction has not changed - do nothing.
226 return;
227 }
Lenka Trochtova13a05192016-12-02 12:19:39 +0100228 final boolean bluetoothDisallowed =
229 newRestrictions.getBoolean(UserManager.DISALLOW_BLUETOOTH);
230 if ((mEnable || mEnableExternal) && bluetoothDisallowed) {
Svetoslav Ganovc2ac5bd2016-06-29 17:31:44 -0700231 try {
232 disable("android.os.UserManagerInternal", true);
233 } catch (RemoteException e) {
234 // Shouldn't happen: startConsentUiIfNeeded not called
235 // when from system.
236 }
Lenka Trochtova13a05192016-12-02 12:19:39 +0100237 }
Lenka Trochtovac6f0e232017-01-17 10:35:49 +0100238 updateOppLauncherComponentState(bluetoothDisallowed);
Lenka Trochtova13a05192016-12-02 12:19:39 +0100239 }
240 };
241
fredcbf072a72012-05-09 16:52:50 -0700242 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
fredc0f420372012-04-12 00:02:00 -0700243 @Override
244 public void onReceive(Context context, Intent intent) {
245 String action = intent.getAction();
fredcbf072a72012-05-09 16:52:50 -0700246 if (BluetoothAdapter.ACTION_LOCAL_NAME_CHANGED.equals(action)) {
fredc0f420372012-04-12 00:02:00 -0700247 String newName = intent.getStringExtra(BluetoothAdapter.EXTRA_LOCAL_NAME);
Jeff Sharkey67609c72016-03-05 14:29:13 -0700248 if (DBG) Slog.d(TAG, "Bluetooth Adapter name changed to " + newName);
fredc0f420372012-04-12 00:02:00 -0700249 if (newName != null) {
250 storeNameAndAddress(newName, null);
251 }
fredc649fe492012-04-19 01:07:18 -0700252 } else if (Intent.ACTION_AIRPLANE_MODE_CHANGED.equals(action)) {
Zhihai Xu401202b2012-12-03 11:36:21 -0800253 synchronized(mReceiver) {
254 if (isBluetoothPersistedStateOn()) {
255 if (isAirplaneModeOn()) {
256 persistBluetoothSetting(BLUETOOTH_ON_AIRPLANE);
257 } else {
258 persistBluetoothSetting(BLUETOOTH_ON_BLUETOOTH);
259 }
260 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800261
262 int st = BluetoothAdapter.STATE_OFF;
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700263 try {
264 mBluetoothLock.readLock().lock();
265 if (mBluetooth != null) {
Nitin Arorad055adb2015-03-02 15:03:51 -0800266 st = mBluetooth.getState();
Nitin Arorad055adb2015-03-02 15:03:51 -0800267 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700268 } catch (RemoteException e) {
269 Slog.e(TAG, "Unable to call getState", e);
270 } finally {
271 mBluetoothLock.readLock().unlock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800272 }
Marie Janssencb21ad72016-12-13 10:51:02 -0800273 Slog.d(TAG, "State " + BluetoothAdapter.nameForState(st));
Nitin Arorad055adb2015-03-02 15:03:51 -0800274
Zhihai Xu401202b2012-12-03 11:36:21 -0800275 if (isAirplaneModeOn()) {
Nitin Arorad055adb2015-03-02 15:03:51 -0800276 // Clear registered LE apps to force shut-off
Marie Janssen2977c3e2016-11-09 12:01:24 -0800277 clearBleApps();
Nitin Arorad055adb2015-03-02 15:03:51 -0800278 if (st == BluetoothAdapter.STATE_BLE_ON) {
279 //if state is BLE_ON make sure you trigger disableBLE part
280 try {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700281 mBluetoothLock.readLock().lock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800282 if (mBluetooth != null) {
283 mBluetooth.onBrEdrDown();
Marie Janssen6a383a72016-10-25 10:47:51 -0700284 mEnable = false;
Nitin Arorad055adb2015-03-02 15:03:51 -0800285 mEnableExternal = false;
286 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700287 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700288 Slog.e(TAG,"Unable to call onBrEdrDown", e);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700289 } finally {
Pavlin Radoslavov7ee53be2016-06-09 12:58:07 -0700290 mBluetoothLock.readLock().unlock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800291 }
292 } else if (st == BluetoothAdapter.STATE_ON){
293 // disable without persisting the setting
Jeff Sharkey67609c72016-03-05 14:29:13 -0700294 Slog.d(TAG, "Calling disable");
Marie Janssen59804562016-12-28 14:13:21 -0800295 sendDisableMsg("airplane mode");
Nitin Arorad055adb2015-03-02 15:03:51 -0800296 }
Zhihai Xu401202b2012-12-03 11:36:21 -0800297 } else if (mEnableExternal) {
298 // enable without persisting the setting
Jeff Sharkey67609c72016-03-05 14:29:13 -0700299 Slog.d(TAG, "Calling enable");
Marie Janssen59804562016-12-28 14:13:21 -0800300 sendEnableMsg(mQuietEnableExternal, "airplane mode");
Zhihai Xu401202b2012-12-03 11:36:21 -0800301 }
fredc649fe492012-04-19 01:07:18 -0700302 }
fredc0f420372012-04-12 00:02:00 -0700303 }
304 }
305 };
306
307 BluetoothManagerService(Context context) {
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700308 mHandler = new BluetoothHandler(IoThread.get().getLooper());
Zhihai Xu40874a02012-10-08 17:57:03 -0700309
fredc0f420372012-04-12 00:02:00 -0700310 mContext = context;
Svetoslav Ganovc2ac5bd2016-06-29 17:31:44 -0700311
312 mPermissionReviewRequired = Build.PERMISSIONS_REVIEW_REQUIRED
313 || context.getResources().getBoolean(
314 com.android.internal.R.bool.config_permissionReviewRequired);
315
Marie Janssen59804562016-12-28 14:13:21 -0800316 mActiveLogs = new LinkedList<ActiveLog>();
fredc0f420372012-04-12 00:02:00 -0700317 mBluetooth = null;
Marie Janssen9db28eb2016-01-12 16:05:15 -0800318 mBluetoothBinder = null;
Nitin Arorad055adb2015-03-02 15:03:51 -0800319 mBluetoothGatt = null;
fredc0f420372012-04-12 00:02:00 -0700320 mBinding = false;
321 mUnbinding = false;
Zhihai Xu40874a02012-10-08 17:57:03 -0700322 mEnable = false;
323 mState = BluetoothAdapter.STATE_OFF;
Zhihai Xu401202b2012-12-03 11:36:21 -0800324 mQuietEnableExternal = false;
325 mEnableExternal = false;
fredc0f420372012-04-12 00:02:00 -0700326 mAddress = null;
327 mName = null;
Zhihai Xudd9d17d2013-01-08 17:05:58 -0800328 mErrorRecoveryRetryCounter = 0;
fredc0f420372012-04-12 00:02:00 -0700329 mContentResolver = context.getContentResolver();
Wei Wange4a744b2015-06-11 17:50:29 -0700330 // Observe BLE scan only mode settings change.
331 registerForBleScanModeChange();
fredcd6883532012-04-25 17:46:13 -0700332 mCallbacks = new RemoteCallbackList<IBluetoothManagerCallback>();
333 mStateChangeCallbacks = new RemoteCallbackList<IBluetoothStateChangeCallback>();
Miao Chou658bf2f2015-06-26 17:14:35 -0700334 IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_LOCAL_NAME_CHANGED);
Matthew Xie6fde3092012-07-11 17:10:07 -0700335 registerForAirplaneMode(filter);
Dianne Hackbornd83a0962014-05-02 16:28:33 -0700336 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
Matthew Xie6fde3092012-07-11 17:10:07 -0700337 mContext.registerReceiver(mReceiver, filter);
fredc0f420372012-04-12 00:02:00 -0700338 loadStoredNameAndAddress();
Zhihai Xu401202b2012-12-03 11:36:21 -0800339 if (isBluetoothPersistedStateOn()) {
340 mEnableExternal = true;
fredc0f420372012-04-12 00:02:00 -0700341 }
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200342
Marie Janssen59804562016-12-28 14:13:21 -0800343 int systemUiUid = -1;
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200344 try {
Marie Janssen59804562016-12-28 14:13:21 -0800345 systemUiUid = mContext.getPackageManager().getPackageUidAsUser("com.android.systemui",
Jeff Sharkeyc5967e92016-01-07 18:50:29 -0700346 PackageManager.MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM);
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200347 } catch (PackageManager.NameNotFoundException e) {
Joe LaPennaacddf2b2015-09-04 12:52:42 -0700348 // Some platforms, such as wearables do not have a system ui.
Jeff Sharkey67609c72016-03-05 14:29:13 -0700349 Slog.w(TAG, "Unable to resolve SystemUI's UID.", e);
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200350 }
Marie Janssen59804562016-12-28 14:13:21 -0800351 mSystemUiUid = systemUiUid;
fredc0f420372012-04-12 00:02:00 -0700352 }
353
fredc649fe492012-04-19 01:07:18 -0700354 /**
355 * Returns true if airplane mode is currently on
356 */
357 private final boolean isAirplaneModeOn() {
Christopher Tatec09cdce2012-09-10 16:50:14 -0700358 return Settings.Global.getInt(mContext.getContentResolver(),
359 Settings.Global.AIRPLANE_MODE_ON, 0) == 1;
fredc649fe492012-04-19 01:07:18 -0700360 }
361
362 /**
363 * Returns true if the Bluetooth saved state is "on"
364 */
365 private final boolean isBluetoothPersistedStateOn() {
Jeff Brownbf6f6f92012-09-25 15:03:20 -0700366 return Settings.Global.getInt(mContentResolver,
Andre Eisenbach8c184312016-09-06 18:03:10 -0700367 Settings.Global.BLUETOOTH_ON, BLUETOOTH_ON_BLUETOOTH) != BLUETOOTH_OFF;
Zhihai Xu401202b2012-12-03 11:36:21 -0800368 }
369
370 /**
371 * Returns true if the Bluetooth saved state is BLUETOOTH_ON_BLUETOOTH
372 */
373 private final boolean isBluetoothPersistedStateOnBluetooth() {
374 return Settings.Global.getInt(mContentResolver,
Andre Eisenbach8c184312016-09-06 18:03:10 -0700375 Settings.Global.BLUETOOTH_ON, BLUETOOTH_ON_BLUETOOTH) == BLUETOOTH_ON_BLUETOOTH;
fredc649fe492012-04-19 01:07:18 -0700376 }
377
378 /**
379 * Save the Bluetooth on/off state
fredc649fe492012-04-19 01:07:18 -0700380 */
Zhihai Xu401202b2012-12-03 11:36:21 -0800381 private void persistBluetoothSetting(int value) {
Marie Janssened50bbc2016-12-15 13:51:30 -0800382 if (DBG) Slog.d(TAG, "Persisting Bluetooth Setting: " + value);
383 // waive WRITE_SECURE_SETTINGS permission check
384 long callingIdentity = Binder.clearCallingIdentity();
Jeff Brownbf6f6f92012-09-25 15:03:20 -0700385 Settings.Global.putInt(mContext.getContentResolver(),
386 Settings.Global.BLUETOOTH_ON,
Zhihai Xu401202b2012-12-03 11:36:21 -0800387 value);
Marie Janssened50bbc2016-12-15 13:51:30 -0800388 Binder.restoreCallingIdentity(callingIdentity);
fredc649fe492012-04-19 01:07:18 -0700389 }
390
391 /**
392 * Returns true if the Bluetooth Adapter's name and address is
393 * locally cached
394 * @return
395 */
fredc0f420372012-04-12 00:02:00 -0700396 private boolean isNameAndAddressSet() {
397 return mName !=null && mAddress!= null && mName.length()>0 && mAddress.length()>0;
398 }
399
fredc649fe492012-04-19 01:07:18 -0700400 /**
401 * Retrieve the Bluetooth Adapter's name and address and save it in
402 * in the local cache
403 */
fredc0f420372012-04-12 00:02:00 -0700404 private void loadStoredNameAndAddress() {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700405 if (DBG) Slog.d(TAG, "Loading stored name and address");
Zhihai Xud31c3222012-10-31 16:08:57 -0700406 if (mContext.getResources().getBoolean
407 (com.android.internal.R.bool.config_bluetooth_address_validation) &&
408 Settings.Secure.getInt(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDR_VALID, 0) == 0) {
409 // if the valid flag is not set, don't load the address and name
Jeff Sharkey67609c72016-03-05 14:29:13 -0700410 if (DBG) Slog.d(TAG, "invalid bluetooth name and address stored");
Zhihai Xud31c3222012-10-31 16:08:57 -0700411 return;
412 }
fredc0f420372012-04-12 00:02:00 -0700413 mName = Settings.Secure.getString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_NAME);
414 mAddress = Settings.Secure.getString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDRESS);
Jeff Sharkey67609c72016-03-05 14:29:13 -0700415 if (DBG) Slog.d(TAG, "Stored bluetooth Name=" + mName + ",Address=" + mAddress);
fredc0f420372012-04-12 00:02:00 -0700416 }
417
fredc649fe492012-04-19 01:07:18 -0700418 /**
419 * Save the Bluetooth name and address in the persistent store.
420 * Only non-null values will be saved.
421 * @param name
422 * @param address
423 */
fredc0f420372012-04-12 00:02:00 -0700424 private void storeNameAndAddress(String name, String address) {
425 if (name != null) {
426 Settings.Secure.putString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_NAME, name);
fredc0f420372012-04-12 00:02:00 -0700427 mName = name;
Jeff Sharkey67609c72016-03-05 14:29:13 -0700428 if (DBG) Slog.d(TAG,"Stored Bluetooth name: " +
fredc649fe492012-04-19 01:07:18 -0700429 Settings.Secure.getString(mContentResolver,SECURE_SETTINGS_BLUETOOTH_NAME));
fredc0f420372012-04-12 00:02:00 -0700430 }
431
432 if (address != null) {
433 Settings.Secure.putString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDRESS, address);
fredc0f420372012-04-12 00:02:00 -0700434 mAddress=address;
Jeff Sharkey67609c72016-03-05 14:29:13 -0700435 if (DBG) Slog.d(TAG,"Stored Bluetoothaddress: " +
fredc649fe492012-04-19 01:07:18 -0700436 Settings.Secure.getString(mContentResolver,SECURE_SETTINGS_BLUETOOTH_ADDRESS));
fredc0f420372012-04-12 00:02:00 -0700437 }
Zhihai Xud31c3222012-10-31 16:08:57 -0700438
439 if ((name != null) && (address != null)) {
440 Settings.Secure.putInt(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDR_VALID, 1);
441 }
fredc0f420372012-04-12 00:02:00 -0700442 }
443
444 public IBluetooth registerAdapter(IBluetoothManagerCallback callback){
Natalie Silvanovich55db6462014-05-01 16:12:23 -0700445 if (callback == null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700446 Slog.w(TAG, "Callback is null in registerAdapter");
Natalie Silvanovich55db6462014-05-01 16:12:23 -0700447 return null;
448 }
fredc0f420372012-04-12 00:02:00 -0700449 Message msg = mHandler.obtainMessage(MESSAGE_REGISTER_ADAPTER);
450 msg.obj = callback;
451 mHandler.sendMessage(msg);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700452
453 return mBluetooth;
fredc0f420372012-04-12 00:02:00 -0700454 }
455
456 public void unregisterAdapter(IBluetoothManagerCallback callback) {
Natalie Silvanovich55db6462014-05-01 16:12:23 -0700457 if (callback == null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700458 Slog.w(TAG, "Callback is null in unregisterAdapter");
Natalie Silvanovich55db6462014-05-01 16:12:23 -0700459 return;
460 }
fredc0f420372012-04-12 00:02:00 -0700461 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
462 "Need BLUETOOTH permission");
463 Message msg = mHandler.obtainMessage(MESSAGE_UNREGISTER_ADAPTER);
464 msg.obj = callback;
465 mHandler.sendMessage(msg);
466 }
467
468 public void registerStateChangeCallback(IBluetoothStateChangeCallback callback) {
469 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
470 "Need BLUETOOTH permission");
Marie Janssencb21ad72016-12-13 10:51:02 -0800471 if (callback == null) {
472 Slog.w(TAG, "registerStateChangeCallback: Callback is null!");
473 return;
474 }
fredc0f420372012-04-12 00:02:00 -0700475 Message msg = mHandler.obtainMessage(MESSAGE_REGISTER_STATE_CHANGE_CALLBACK);
476 msg.obj = callback;
477 mHandler.sendMessage(msg);
478 }
479
480 public void unregisterStateChangeCallback(IBluetoothStateChangeCallback callback) {
481 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
482 "Need BLUETOOTH permission");
Marie Janssencb21ad72016-12-13 10:51:02 -0800483 if (callback == null) {
484 Slog.w(TAG, "unregisterStateChangeCallback: Callback is null!");
485 return;
486 }
fredc0f420372012-04-12 00:02:00 -0700487 Message msg = mHandler.obtainMessage(MESSAGE_UNREGISTER_STATE_CHANGE_CALLBACK);
488 msg.obj = callback;
489 mHandler.sendMessage(msg);
490 }
491
492 public boolean isEnabled() {
Zhihai Xu6eb76522012-11-29 15:41:04 -0800493 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
494 (!checkIfCallerIsForegroundUser())) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700495 Slog.w(TAG,"isEnabled(): not allowed for non-active and non system user");
Zhihai Xu40874a02012-10-08 17:57:03 -0700496 return false;
497 }
498
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700499 try {
500 mBluetoothLock.readLock().lock();
501 if (mBluetooth != null) return mBluetooth.isEnabled();
502 } catch (RemoteException e) {
503 Slog.e(TAG, "isEnabled()", e);
504 } finally {
505 mBluetoothLock.readLock().unlock();
fredc0f420372012-04-12 00:02:00 -0700506 }
507 return false;
508 }
509
Christine Hallstrom995c90a2016-05-25 15:49:08 -0700510 public int getState() {
511 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
512 (!checkIfCallerIsForegroundUser())) {
Marie Janssencb21ad72016-12-13 10:51:02 -0800513 Slog.w(TAG, "getState(): report OFF for non-active and non system user");
Christine Hallstrom995c90a2016-05-25 15:49:08 -0700514 return BluetoothAdapter.STATE_OFF;
515 }
516
517 try {
518 mBluetoothLock.readLock().lock();
519 if (mBluetooth != null) return mBluetooth.getState();
520 } catch (RemoteException e) {
521 Slog.e(TAG, "getState()", e);
522 } finally {
523 mBluetoothLock.readLock().unlock();
524 }
525 return BluetoothAdapter.STATE_OFF;
526 }
527
Nitin Arorad055adb2015-03-02 15:03:51 -0800528 class ClientDeathRecipient implements IBinder.DeathRecipient {
Marie Janssen59804562016-12-28 14:13:21 -0800529 private String mPackageName;
530
531 public ClientDeathRecipient(String packageName) {
532 mPackageName = packageName;
533 }
534
Nitin Arorad055adb2015-03-02 15:03:51 -0800535 public void binderDied() {
Marie Janssen59804562016-12-28 14:13:21 -0800536 if (DBG) Slog.d(TAG, "Binder is dead - unregister " + mPackageName);
Marie Janssen2977c3e2016-11-09 12:01:24 -0800537 if (isBleAppPresent()) {
538 // Nothing to do, another app is here.
539 return;
540 }
541 if (DBG) Slog.d(TAG, "Disabling LE only mode after application crash");
542 try {
543 mBluetoothLock.readLock().lock();
544 if (mBluetooth != null &&
545 mBluetooth.getState() == BluetoothAdapter.STATE_BLE_ON) {
546 mEnable = false;
547 mBluetooth.onBrEdrDown();
Nitin Arorad055adb2015-03-02 15:03:51 -0800548 }
Marie Janssen2977c3e2016-11-09 12:01:24 -0800549 } catch (RemoteException e) {
550 Slog.e(TAG,"Unable to call onBrEdrDown", e);
551 } finally {
552 mBluetoothLock.readLock().unlock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800553 }
554 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800555
Marie Janssen59804562016-12-28 14:13:21 -0800556 public String getPackageName() {
557 return mPackageName;
558 }
559 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800560
Wei Wang67d84162015-04-26 17:04:29 -0700561 @Override
562 public boolean isBleScanAlwaysAvailable() {
Marie Janssen6a383a72016-10-25 10:47:51 -0700563 if (isAirplaneModeOn() && !mEnable) {
564 return false;
565 }
Wei Wang67d84162015-04-26 17:04:29 -0700566 try {
567 return (Settings.Global.getInt(mContentResolver,
568 Settings.Global.BLE_SCAN_ALWAYS_AVAILABLE)) != 0;
569 } catch (SettingNotFoundException e) {
570 }
571 return false;
572 }
573
Wei Wange4a744b2015-06-11 17:50:29 -0700574 // Monitor change of BLE scan only mode settings.
575 private void registerForBleScanModeChange() {
576 ContentObserver contentObserver = new ContentObserver(null) {
577 @Override
578 public void onChange(boolean selfChange) {
Marie Janssen2977c3e2016-11-09 12:01:24 -0800579 if (isBleScanAlwaysAvailable()) {
580 // Nothing to do
581 return;
582 }
583 // BLE scan is not available.
584 disableBleScanMode();
585 clearBleApps();
586 try {
587 mBluetoothLock.readLock().lock();
588 if (mBluetooth != null) mBluetooth.onBrEdrDown();
589 } catch (RemoteException e) {
590 Slog.e(TAG, "error when disabling bluetooth", e);
591 } finally {
592 mBluetoothLock.readLock().unlock();
Wei Wange4a744b2015-06-11 17:50:29 -0700593 }
594 }
595 };
596
597 mContentResolver.registerContentObserver(
598 Settings.Global.getUriFor(Settings.Global.BLE_SCAN_ALWAYS_AVAILABLE),
599 false, contentObserver);
600 }
601
602 // Disable ble scan only mode.
603 private void disableBleScanMode() {
604 try {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700605 mBluetoothLock.writeLock().lock();
Wei Wange4a744b2015-06-11 17:50:29 -0700606 if (mBluetooth != null && (mBluetooth.getState() != BluetoothAdapter.STATE_ON)) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700607 if (DBG) Slog.d(TAG, "Reseting the mEnable flag for clean disable");
Wei Wange4a744b2015-06-11 17:50:29 -0700608 mEnable = false;
609 }
610 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700611 Slog.e(TAG, "getState()", e);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700612 } finally {
613 mBluetoothLock.writeLock().unlock();
Wei Wange4a744b2015-06-11 17:50:29 -0700614 }
615 }
616
Marie Janssen59804562016-12-28 14:13:21 -0800617 public int updateBleAppCount(IBinder token, boolean enable, String packageName) {
618 ClientDeathRecipient r = mBleApps.get(token);
619 if (r == null && enable) {
620 ClientDeathRecipient deathRec = new ClientDeathRecipient(packageName);
621 try {
622 token.linkToDeath(deathRec, 0);
623 } catch (RemoteException ex) {
624 throw new IllegalArgumentException("BLE app (" + packageName + ") already dead!");
Nitin Arorad055adb2015-03-02 15:03:51 -0800625 }
Marie Janssen59804562016-12-28 14:13:21 -0800626 mBleApps.put(token, deathRec);
627 if (DBG) Slog.d(TAG, "Registered for death of " + packageName);
628 } else if (!enable && r != null) {
629 // Unregister death recipient as the app goes away.
630 token.unlinkToDeath(r, 0);
631 mBleApps.remove(token);
632 if (DBG) Slog.d(TAG, "Unregistered for death of " + packageName);
Nitin Arorad055adb2015-03-02 15:03:51 -0800633 }
Marie Janssen2977c3e2016-11-09 12:01:24 -0800634 int appCount = mBleApps.size();
635 if (DBG) Slog.d(TAG, appCount + " registered Ble Apps");
636 if (appCount == 0 && mEnable) {
Wei Wange4a744b2015-06-11 17:50:29 -0700637 disableBleScanMode();
Nitin Arorad055adb2015-03-02 15:03:51 -0800638 }
Marie Janssen2977c3e2016-11-09 12:01:24 -0800639 return appCount;
Nitin Arorad055adb2015-03-02 15:03:51 -0800640 }
641
Wei Wange4a744b2015-06-11 17:50:29 -0700642 // Clear all apps using BLE scan only mode.
643 private void clearBleApps() {
Marie Janssen2977c3e2016-11-09 12:01:24 -0800644 mBleApps.clear();
Wei Wange4a744b2015-06-11 17:50:29 -0700645 }
646
Marie Janssen59804562016-12-28 14:13:21 -0800647 /** @hide */
Nitin Arorad055adb2015-03-02 15:03:51 -0800648 public boolean isBleAppPresent() {
Marie Janssen2977c3e2016-11-09 12:01:24 -0800649 if (DBG) Slog.d(TAG, "isBleAppPresent() count: " + mBleApps.size());
650 return mBleApps.size() > 0;
Nitin Arorad055adb2015-03-02 15:03:51 -0800651 }
652
653 /**
Marie Janssened50bbc2016-12-15 13:51:30 -0800654 * Action taken when GattService is turned on
Nitin Arorad055adb2015-03-02 15:03:51 -0800655 */
656 private void onBluetoothGattServiceUp() {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700657 if (DBG) Slog.d(TAG,"BluetoothGatt Service is Up");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700658 try {
659 mBluetoothLock.readLock().lock();
Marie Janssened50bbc2016-12-15 13:51:30 -0800660 if (mBluetooth == null) {
661 if (DBG) Slog.w(TAG, "onBluetoothServiceUp: mBluetooth is null!");
662 return;
663 }
664 int st = mBluetooth.getState();
665 if (st != BluetoothAdapter.STATE_BLE_ON) {
666 if (DBG) Slog.v(TAG, "onBluetoothServiceUp: state isn't BLE_ON: " +
667 BluetoothAdapter.nameForState(st));
668 return;
669 }
670 if (isBluetoothPersistedStateOnBluetooth() || !isBleAppPresent()) {
671 // This triggers transition to STATE_ON
Nitin Arorad055adb2015-03-02 15:03:51 -0800672 mBluetooth.onLeServiceUp();
Nitin Arorad055adb2015-03-02 15:03:51 -0800673 persistBluetoothSetting(BLUETOOTH_ON_BLUETOOTH);
Nitin Arorad055adb2015-03-02 15:03:51 -0800674 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700675 } catch (RemoteException e) {
676 Slog.e(TAG,"Unable to call onServiceUp", e);
677 } finally {
678 mBluetoothLock.readLock().unlock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800679 }
680 }
681
682 /**
683 * Inform BluetoothAdapter instances that BREDR part is down
684 * and turn off all service and stack if no LE app needs it
685 */
686 private void sendBrEdrDownCallback() {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700687 if (DBG) Slog.d(TAG,"Calling sendBrEdrDownCallback callbacks");
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700688
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700689 if (mBluetooth == null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700690 Slog.w(TAG, "Bluetooth handle is null");
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700691 return;
692 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800693
694 if (isBleAppPresent() == false) {
695 try {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700696 mBluetoothLock.readLock().lock();
697 if (mBluetooth != null) mBluetooth.onBrEdrDown();
698 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700699 Slog.e(TAG, "Call to onBrEdrDown() failed.", e);
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700700 } finally {
701 mBluetoothLock.readLock().unlock();
Nitin Arorad055adb2015-03-02 15:03:51 -0800702 }
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700703 } else {
704 // Need to stay at BLE ON. Disconnect all Gatt connections
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700705 try {
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700706 mBluetoothGatt.unregAll();
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700707 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700708 Slog.e(TAG, "Unable to disconnect all apps.", e);
Nitin Arorad055adb2015-03-02 15:03:51 -0800709 }
710 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800711 }
712
Marie Janssen59804562016-12-28 14:13:21 -0800713 public boolean enableNoAutoConnect(String packageName)
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700714 {
Lenka Trochtova13a05192016-12-02 12:19:39 +0100715 if (isBluetoothDisallowed()) {
716 if (DBG) {
717 Slog.d(TAG, "enableNoAutoConnect(): not enabling - bluetooth disallowed");
718 }
719 return false;
720 }
721
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700722 mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
723 "Need BLUETOOTH ADMIN permission");
Zhihai Xu40874a02012-10-08 17:57:03 -0700724
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700725 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700726 Slog.d(TAG,"enableNoAutoConnect(): mBluetooth =" + mBluetooth +
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700727 " mBinding = " + mBinding);
728 }
Martijn Coenen8385c5a2012-11-29 10:14:16 -0800729 int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
730
731 if (callingAppId != Process.NFC_UID) {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700732 throw new SecurityException("no permission to enable Bluetooth quietly");
733 }
Martijn Coenen8385c5a2012-11-29 10:14:16 -0800734
Zhihai Xu401202b2012-12-03 11:36:21 -0800735 synchronized(mReceiver) {
736 mQuietEnableExternal = true;
737 mEnableExternal = true;
Marie Janssen59804562016-12-28 14:13:21 -0800738 sendEnableMsg(true, packageName);
Zhihai Xu401202b2012-12-03 11:36:21 -0800739 }
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700740 return true;
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700741 }
Ajay Panicker4bb48302016-03-31 14:14:27 -0700742
Svetoslav Ganovc2ac5bd2016-06-29 17:31:44 -0700743 public boolean enable(String packageName) throws RemoteException {
Lenka Trochtova13a05192016-12-02 12:19:39 +0100744 if (isBluetoothDisallowed()) {
745 if (DBG) {
746 Slog.d(TAG,"enable(): not enabling - bluetooth disallowed");
747 }
748 return false;
749 }
750
Svetoslav Ganovc2ac5bd2016-06-29 17:31:44 -0700751 final int callingUid = Binder.getCallingUid();
752 final boolean callerSystem = UserHandle.getAppId(callingUid) == Process.SYSTEM_UID;
753
754 if (!callerSystem) {
755 if (!checkIfCallerIsForegroundUser()) {
756 Slog.w(TAG, "enable(): not allowed for non-active and non system user");
757 return false;
758 }
759
760 mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
761 "Need BLUETOOTH ADMIN permission");
762
Ivan Podogovafababd2016-12-05 16:46:52 +0000763 if (!isEnabled() && mPermissionReviewRequired) {
764 startConsentUi(packageName, callingUid, BluetoothAdapter.ACTION_REQUEST_ENABLE);
Svetoslav Ganovc2ac5bd2016-06-29 17:31:44 -0700765 return false;
766 }
fredcf2458862012-04-16 15:18:27 -0700767 }
768
Zhihai Xu401202b2012-12-03 11:36:21 -0800769 if (DBG) {
Marie Janssen59804562016-12-28 14:13:21 -0800770 Slog.d(TAG,"enable(" + packageName + "): mBluetooth =" + mBluetooth +
Marie Janssencb21ad72016-12-13 10:51:02 -0800771 " mBinding = " + mBinding + " mState = " +
772 BluetoothAdapter.nameForState(mState));
Sanket Agarwal090bf552016-04-21 14:10:55 -0700773 }
Zhihai Xu401202b2012-12-03 11:36:21 -0800774
775 synchronized(mReceiver) {
776 mQuietEnableExternal = false;
777 mEnableExternal = true;
778 // waive WRITE_SECURE_SETTINGS permission check
Marie Janssen59804562016-12-28 14:13:21 -0800779 sendEnableMsg(false, packageName);
Zhihai Xu401202b2012-12-03 11:36:21 -0800780 }
Jeff Sharkey67609c72016-03-05 14:29:13 -0700781 if (DBG) Slog.d(TAG, "enable returning");
Zhihai Xu401202b2012-12-03 11:36:21 -0800782 return true;
fredc0f420372012-04-12 00:02:00 -0700783 }
784
Svetoslav Ganovc2ac5bd2016-06-29 17:31:44 -0700785 public boolean disable(String packageName, boolean persist) throws RemoteException {
786 final int callingUid = Binder.getCallingUid();
787 final boolean callerSystem = UserHandle.getAppId(callingUid) == Process.SYSTEM_UID;
Zhihai Xu40874a02012-10-08 17:57:03 -0700788
Svetoslav Ganovc2ac5bd2016-06-29 17:31:44 -0700789 if (!callerSystem) {
790 if (!checkIfCallerIsForegroundUser()) {
791 Slog.w(TAG, "disable(): not allowed for non-active and non system user");
792 return false;
793 }
794
795 mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
796 "Need BLUETOOTH ADMIN permission");
797
Ivan Podogovafababd2016-12-05 16:46:52 +0000798 if (isEnabled() && mPermissionReviewRequired) {
799 startConsentUi(packageName, callingUid, BluetoothAdapter.ACTION_REQUEST_DISABLE);
Svetoslav Ganovc2ac5bd2016-06-29 17:31:44 -0700800 return false;
801 }
Zhihai Xu40874a02012-10-08 17:57:03 -0700802 }
803
fredcf2458862012-04-16 15:18:27 -0700804 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700805 Slog.d(TAG,"disable(): mBluetooth = " + mBluetooth +
Matthew Xiecdce0b92012-07-12 19:06:15 -0700806 " mBinding = " + mBinding);
807 }
fredcf2458862012-04-16 15:18:27 -0700808
Zhihai Xu401202b2012-12-03 11:36:21 -0800809 synchronized(mReceiver) {
810 if (persist) {
Zhihai Xu401202b2012-12-03 11:36:21 -0800811 persistBluetoothSetting(BLUETOOTH_OFF);
Zhihai Xu401202b2012-12-03 11:36:21 -0800812 }
813 mEnableExternal = false;
Marie Janssen59804562016-12-28 14:13:21 -0800814 sendDisableMsg(packageName);
Zhihai Xu401202b2012-12-03 11:36:21 -0800815 }
fredc0f420372012-04-12 00:02:00 -0700816 return true;
817 }
818
Ivan Podogovafababd2016-12-05 16:46:52 +0000819 private void startConsentUi(String packageName, int callingUid, String intentAction)
820 throws RemoteException {
Svetoslav Ganovc2ac5bd2016-06-29 17:31:44 -0700821 try {
822 // Validate the package only if we are going to use it
823 ApplicationInfo applicationInfo = mContext.getPackageManager()
824 .getApplicationInfoAsUser(packageName,
825 PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
826 UserHandle.getUserId(callingUid));
827 if (applicationInfo.uid != callingUid) {
828 throw new SecurityException("Package " + callingUid
829 + " not in uid " + callingUid);
830 }
831
Ivan Podogovafababd2016-12-05 16:46:52 +0000832 // Permission review mode, trigger a user prompt
833 Intent intent = new Intent(intentAction);
834 mContext.startActivity(intent);
Svetoslav Ganovc2ac5bd2016-06-29 17:31:44 -0700835 } catch (PackageManager.NameNotFoundException e) {
836 throw new RemoteException(e.getMessage());
837 }
Svetoslav Ganovc2ac5bd2016-06-29 17:31:44 -0700838 }
839
fredc649fe492012-04-19 01:07:18 -0700840 public void unbindAndFinish() {
fredcf2458862012-04-16 15:18:27 -0700841 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700842 Slog.d(TAG,"unbindAndFinish(): " + mBluetooth +
Marie Janssencb21ad72016-12-13 10:51:02 -0800843 " mBinding = " + mBinding + " mUnbinding = " + mUnbinding);
fredcf2458862012-04-16 15:18:27 -0700844 }
845
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700846 try {
847 mBluetoothLock.writeLock().lock();
fredc0f420372012-04-12 00:02:00 -0700848 if (mUnbinding) return;
849 mUnbinding = true;
Pavlin Radoslavove47ec142016-06-01 22:25:18 -0700850 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
Pavlin Radoslavov74f60c02016-09-21 17:28:11 -0700851 mHandler.removeMessages(MESSAGE_BIND_PROFILE_SERVICE);
Zhihai Xu40874a02012-10-08 17:57:03 -0700852 if (mBluetooth != null) {
Andre Eisenbach305fdab2015-11-11 21:43:26 -0800853 //Unregister callback object
854 try {
855 mBluetooth.unregisterCallback(mBluetoothCallback);
856 } catch (RemoteException re) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700857 Slog.e(TAG, "Unable to unregister BluetoothCallback",re);
fredcbf072a72012-05-09 16:52:50 -0700858 }
Marie Janssen9db28eb2016-01-12 16:05:15 -0800859 mBluetoothBinder = null;
fredcd6883532012-04-25 17:46:13 -0700860 mBluetooth = null;
fredc0f420372012-04-12 00:02:00 -0700861 mContext.unbindService(mConnection);
fredcd6883532012-04-25 17:46:13 -0700862 mUnbinding = false;
Zhihai Xu40874a02012-10-08 17:57:03 -0700863 mBinding = false;
fredcf2458862012-04-16 15:18:27 -0700864 } else {
Marie Janssencb21ad72016-12-13 10:51:02 -0800865 mUnbinding = false;
fredc0f420372012-04-12 00:02:00 -0700866 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800867 mBluetoothGatt = null;
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -0700868 } finally {
869 mBluetoothLock.writeLock().unlock();
fredc0f420372012-04-12 00:02:00 -0700870 }
871 }
872
Matthew Xieddf7e472013-03-01 18:41:02 -0800873 public IBluetoothGatt getBluetoothGatt() {
874 // sync protection
875 return mBluetoothGatt;
876 }
877
Benjamin Franze8b98922014-11-12 15:57:54 +0000878 @Override
879 public boolean bindBluetoothProfileService(int bluetoothProfile,
880 IBluetoothProfileServiceConnection proxy) {
881 if (!mEnable) {
882 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700883 Slog.d(TAG, "Trying to bind to profile: " + bluetoothProfile +
Benjamin Franze8b98922014-11-12 15:57:54 +0000884 ", while Bluetooth was disabled");
885 }
886 return false;
887 }
888 synchronized (mProfileServices) {
889 ProfileServiceConnections psc = mProfileServices.get(new Integer(bluetoothProfile));
890 if (psc == null) {
891 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700892 Slog.d(TAG, "Creating new ProfileServiceConnections object for"
Benjamin Franze8b98922014-11-12 15:57:54 +0000893 + " profile: " + bluetoothProfile);
894 }
Benjamin Franz5b614592014-12-09 18:58:45 +0000895
896 if (bluetoothProfile != BluetoothProfile.HEADSET) return false;
897
898 Intent intent = new Intent(IBluetoothHeadset.class.getName());
Benjamin Franze8b98922014-11-12 15:57:54 +0000899 psc = new ProfileServiceConnections(intent);
Benjamin Franz5b614592014-12-09 18:58:45 +0000900 if (!psc.bindService()) return false;
901
Benjamin Franze8b98922014-11-12 15:57:54 +0000902 mProfileServices.put(new Integer(bluetoothProfile), psc);
Benjamin Franze8b98922014-11-12 15:57:54 +0000903 }
904 }
905
906 // Introducing a delay to give the client app time to prepare
907 Message addProxyMsg = mHandler.obtainMessage(MESSAGE_ADD_PROXY_DELAYED);
908 addProxyMsg.arg1 = bluetoothProfile;
909 addProxyMsg.obj = proxy;
910 mHandler.sendMessageDelayed(addProxyMsg, ADD_PROXY_DELAY_MS);
911 return true;
912 }
913
914 @Override
915 public void unbindBluetoothProfileService(int bluetoothProfile,
916 IBluetoothProfileServiceConnection proxy) {
917 synchronized (mProfileServices) {
918 ProfileServiceConnections psc = mProfileServices.get(new Integer(bluetoothProfile));
919 if (psc == null) {
920 return;
921 }
922 psc.removeProxy(proxy);
923 }
924 }
925
926 private void unbindAllBluetoothProfileServices() {
927 synchronized (mProfileServices) {
928 for (Integer i : mProfileServices.keySet()) {
929 ProfileServiceConnections psc = mProfileServices.get(i);
Benjamin Franz5b614592014-12-09 18:58:45 +0000930 try {
931 mContext.unbindService(psc);
932 } catch (IllegalArgumentException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700933 Slog.e(TAG, "Unable to unbind service with intent: " + psc.mIntent, e);
Benjamin Franz5b614592014-12-09 18:58:45 +0000934 }
Benjamin Franze8b98922014-11-12 15:57:54 +0000935 psc.removeAllProxies();
936 }
937 mProfileServices.clear();
938 }
939 }
940
941 /**
Miao Chou658bf2f2015-06-26 17:14:35 -0700942 * Send enable message and set adapter name and address. Called when the boot phase becomes
943 * PHASE_SYSTEM_SERVICES_READY.
944 */
945 public void handleOnBootPhase() {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700946 if (DBG) Slog.d(TAG, "Bluetooth boot completed");
Lenka Trochtova13a05192016-12-02 12:19:39 +0100947 UserManagerInternal userManagerInternal =
948 LocalServices.getService(UserManagerInternal.class);
949 userManagerInternal.addUserRestrictionsListener(mUserRestrictionsListener);
Lenka Trochtovac6f0e232017-01-17 10:35:49 +0100950 final boolean isBluetoothDisallowed = isBluetoothDisallowed();
951 PackageManagerService packageManagerService =
952 (PackageManagerService) ServiceManager.getService("package");
953 if (packageManagerService != null && !packageManagerService.isOnlyCoreApps()) {
954 updateOppLauncherComponentState(isBluetoothDisallowed);
955 }
956 if (isBluetoothDisallowed) {
Lenka Trochtova13a05192016-12-02 12:19:39 +0100957 return;
958 }
Miao Chou658bf2f2015-06-26 17:14:35 -0700959 if (mEnableExternal && isBluetoothPersistedStateOnBluetooth()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700960 if (DBG) Slog.d(TAG, "Auto-enabling Bluetooth.");
Marie Janssen59804562016-12-28 14:13:21 -0800961 sendEnableMsg(mQuietEnableExternal, "system boot");
Ajay Panickerbf796d82016-03-11 13:47:20 -0800962 } else if (!isNameAndAddressSet()) {
963 if (DBG) Slog.d(TAG, "Getting adapter name and address");
Ajay Panicker4bb48302016-03-31 14:14:27 -0700964 Message getMsg = mHandler.obtainMessage(MESSAGE_GET_NAME_AND_ADDRESS);
965 mHandler.sendMessage(getMsg);
Miao Chou658bf2f2015-06-26 17:14:35 -0700966 }
Miao Chou658bf2f2015-06-26 17:14:35 -0700967 }
968
969 /**
970 * Called when switching to a different foreground user.
971 */
972 public void handleOnSwitchUser(int userHandle) {
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -0700973 if (DBG) Slog.d(TAG, "User " + userHandle + " switched");
974 mHandler.obtainMessage(MESSAGE_USER_SWITCHED, userHandle, 0).sendToTarget();
975 }
976
977 /**
978 * Called when user is unlocked.
979 */
980 public void handleOnUnlockUser(int userHandle) {
981 if (DBG) Slog.d(TAG, "User " + userHandle + " unlocked");
982 mHandler.obtainMessage(MESSAGE_USER_UNLOCKED, userHandle, 0).sendToTarget();
Miao Chou658bf2f2015-06-26 17:14:35 -0700983 }
984
985 /**
Benjamin Franze8b98922014-11-12 15:57:54 +0000986 * This class manages the clients connected to a given ProfileService
987 * and maintains the connection with that service.
988 */
989 final private class ProfileServiceConnections implements ServiceConnection,
990 IBinder.DeathRecipient {
991 final RemoteCallbackList<IBluetoothProfileServiceConnection> mProxies =
992 new RemoteCallbackList <IBluetoothProfileServiceConnection>();
993 IBinder mService;
994 ComponentName mClassName;
995 Intent mIntent;
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700996 boolean mInvokingProxyCallbacks = false;
Benjamin Franze8b98922014-11-12 15:57:54 +0000997
998 ProfileServiceConnections(Intent intent) {
999 mService = null;
1000 mClassName = null;
1001 mIntent = intent;
1002 }
1003
Benjamin Franz5b614592014-12-09 18:58:45 +00001004 private boolean bindService() {
1005 if (mIntent != null && mService == null &&
1006 doBind(mIntent, this, 0, UserHandle.CURRENT_OR_SELF)) {
Benjamin Franze8b98922014-11-12 15:57:54 +00001007 Message msg = mHandler.obtainMessage(MESSAGE_BIND_PROFILE_SERVICE);
1008 msg.obj = this;
1009 mHandler.sendMessageDelayed(msg, TIMEOUT_BIND_MS);
Benjamin Franz5b614592014-12-09 18:58:45 +00001010 return true;
Benjamin Franze8b98922014-11-12 15:57:54 +00001011 }
Jeff Sharkey67609c72016-03-05 14:29:13 -07001012 Slog.w(TAG, "Unable to bind with intent: " + mIntent);
Benjamin Franz5b614592014-12-09 18:58:45 +00001013 return false;
Benjamin Franze8b98922014-11-12 15:57:54 +00001014 }
1015
1016 private void addProxy(IBluetoothProfileServiceConnection proxy) {
1017 mProxies.register(proxy);
1018 if (mService != null) {
1019 try{
1020 proxy.onServiceConnected(mClassName, mService);
1021 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001022 Slog.e(TAG, "Unable to connect to proxy", e);
Benjamin Franze8b98922014-11-12 15:57:54 +00001023 }
1024 } else {
1025 if (!mHandler.hasMessages(MESSAGE_BIND_PROFILE_SERVICE, this)) {
1026 Message msg = mHandler.obtainMessage(MESSAGE_BIND_PROFILE_SERVICE);
1027 msg.obj = this;
1028 mHandler.sendMessage(msg);
1029 }
1030 }
1031 }
1032
1033 private void removeProxy(IBluetoothProfileServiceConnection proxy) {
1034 if (proxy != null) {
1035 if (mProxies.unregister(proxy)) {
1036 try {
1037 proxy.onServiceDisconnected(mClassName);
1038 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001039 Slog.e(TAG, "Unable to disconnect proxy", e);
Benjamin Franze8b98922014-11-12 15:57:54 +00001040 }
1041 }
1042 } else {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001043 Slog.w(TAG, "Trying to remove a null proxy");
Benjamin Franze8b98922014-11-12 15:57:54 +00001044 }
1045 }
1046
1047 private void removeAllProxies() {
1048 onServiceDisconnected(mClassName);
1049 mProxies.kill();
1050 }
1051
1052 @Override
1053 public void onServiceConnected(ComponentName className, IBinder service) {
1054 // remove timeout message
1055 mHandler.removeMessages(MESSAGE_BIND_PROFILE_SERVICE, this);
1056 mService = service;
1057 mClassName = className;
1058 try {
1059 mService.linkToDeath(this, 0);
1060 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001061 Slog.e(TAG, "Unable to linkToDeath", e);
Benjamin Franze8b98922014-11-12 15:57:54 +00001062 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001063
1064 if (mInvokingProxyCallbacks) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001065 Slog.e(TAG, "Proxy callbacks already in progress.");
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001066 return;
Benjamin Franze8b98922014-11-12 15:57:54 +00001067 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001068 mInvokingProxyCallbacks = true;
1069
1070 final int n = mProxies.beginBroadcast();
1071 try {
1072 for (int i = 0; i < n; i++) {
1073 try {
1074 mProxies.getBroadcastItem(i).onServiceConnected(className, service);
1075 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001076 Slog.e(TAG, "Unable to connect to proxy", e);
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001077 }
1078 }
1079 } finally {
1080 mProxies.finishBroadcast();
1081 mInvokingProxyCallbacks = false;
1082 }
Benjamin Franze8b98922014-11-12 15:57:54 +00001083 }
1084
1085 @Override
1086 public void onServiceDisconnected(ComponentName className) {
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001087 if (mService == null) return;
Benjamin Franze8b98922014-11-12 15:57:54 +00001088 mService.unlinkToDeath(this, 0);
1089 mService = null;
1090 mClassName = null;
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001091
1092 if (mInvokingProxyCallbacks) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001093 Slog.e(TAG, "Proxy callbacks already in progress.");
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001094 return;
Benjamin Franze8b98922014-11-12 15:57:54 +00001095 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001096 mInvokingProxyCallbacks = true;
1097
1098 final int n = mProxies.beginBroadcast();
1099 try {
1100 for (int i = 0; i < n; i++) {
1101 try {
1102 mProxies.getBroadcastItem(i).onServiceDisconnected(className);
1103 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001104 Slog.e(TAG, "Unable to disconnect from proxy", e);
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001105 }
1106 }
1107 } finally {
1108 mProxies.finishBroadcast();
1109 mInvokingProxyCallbacks = false;
1110 }
Benjamin Franze8b98922014-11-12 15:57:54 +00001111 }
1112
1113 @Override
1114 public void binderDied() {
1115 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001116 Slog.w(TAG, "Profile service for profile: " + mClassName
Benjamin Franze8b98922014-11-12 15:57:54 +00001117 + " died.");
1118 }
1119 onServiceDisconnected(mClassName);
1120 // Trigger rebind
1121 Message msg = mHandler.obtainMessage(MESSAGE_BIND_PROFILE_SERVICE);
1122 msg.obj = this;
1123 mHandler.sendMessageDelayed(msg, TIMEOUT_BIND_MS);
1124 }
1125 }
1126
fredcbf072a72012-05-09 16:52:50 -07001127 private void sendBluetoothStateCallback(boolean isUp) {
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001128 try {
1129 int n = mStateChangeCallbacks.beginBroadcast();
Jeff Sharkey67609c72016-03-05 14:29:13 -07001130 if (DBG) Slog.d(TAG,"Broadcasting onBluetoothStateChange("+isUp+") to " + n + " receivers.");
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001131 for (int i=0; i <n;i++) {
1132 try {
1133 mStateChangeCallbacks.getBroadcastItem(i).onBluetoothStateChange(isUp);
1134 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001135 Slog.e(TAG, "Unable to call onBluetoothStateChange() on callback #" + i , e);
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001136 }
fredcbf072a72012-05-09 16:52:50 -07001137 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -07001138 } finally {
1139 mStateChangeCallbacks.finishBroadcast();
fredcbf072a72012-05-09 16:52:50 -07001140 }
fredcbf072a72012-05-09 16:52:50 -07001141 }
1142
1143 /**
Zhihai Xu40874a02012-10-08 17:57:03 -07001144 * Inform BluetoothAdapter instances that Adapter service is up
1145 */
1146 private void sendBluetoothServiceUpCallback() {
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001147 try {
1148 int n = mCallbacks.beginBroadcast();
Jeff Sharkey67609c72016-03-05 14:29:13 -07001149 Slog.d(TAG,"Broadcasting onBluetoothServiceUp() to " + n + " receivers.");
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001150 for (int i=0; i <n;i++) {
1151 try {
1152 mCallbacks.getBroadcastItem(i).onBluetoothServiceUp(mBluetooth);
1153 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001154 Slog.e(TAG, "Unable to call onBluetoothServiceUp() on callback #" + i, e);
Zhihai Xu40874a02012-10-08 17:57:03 -07001155 }
1156 }
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001157 } finally {
1158 mCallbacks.finishBroadcast();
Zhihai Xu40874a02012-10-08 17:57:03 -07001159 }
1160 }
1161 /**
fredcbf072a72012-05-09 16:52:50 -07001162 * Inform BluetoothAdapter instances that Adapter service is down
1163 */
1164 private void sendBluetoothServiceDownCallback() {
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001165 try {
1166 int n = mCallbacks.beginBroadcast();
Jeff Sharkey67609c72016-03-05 14:29:13 -07001167 Slog.d(TAG,"Broadcasting onBluetoothServiceDown() to " + n + " receivers.");
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001168 for (int i=0; i <n;i++) {
1169 try {
1170 mCallbacks.getBroadcastItem(i).onBluetoothServiceDown();
1171 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001172 Slog.e(TAG, "Unable to call onBluetoothServiceDown() on callback #" + i, e);
fredcd6883532012-04-25 17:46:13 -07001173 }
1174 }
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001175 } finally {
1176 mCallbacks.finishBroadcast();
fredcd6883532012-04-25 17:46:13 -07001177 }
1178 }
Svet Ganov408abf72015-05-12 19:13:36 -07001179
fredc0f420372012-04-12 00:02:00 -07001180 public String getAddress() {
Matthew Xieaf5ddbf2012-12-04 10:47:43 -08001181 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
Svet Ganov408abf72015-05-12 19:13:36 -07001182 "Need BLUETOOTH permission");
Zhihai Xu40874a02012-10-08 17:57:03 -07001183
Zhihai Xu6eb76522012-11-29 15:41:04 -08001184 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
Svet Ganov408abf72015-05-12 19:13:36 -07001185 (!checkIfCallerIsForegroundUser())) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001186 Slog.w(TAG,"getAddress(): not allowed for non-active and non system user");
Zhihai Xu6eb76522012-11-29 15:41:04 -08001187 return null;
Zhihai Xu40874a02012-10-08 17:57:03 -07001188 }
1189
Svet Ganov408abf72015-05-12 19:13:36 -07001190 if (mContext.checkCallingOrSelfPermission(Manifest.permission.LOCAL_MAC_ADDRESS)
1191 != PackageManager.PERMISSION_GRANTED) {
1192 return BluetoothAdapter.DEFAULT_MAC_ADDRESS;
1193 }
1194
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001195 try {
1196 mBluetoothLock.readLock().lock();
1197 if (mBluetooth != null) return mBluetooth.getAddress();
1198 } catch (RemoteException e) {
1199 Slog.e(TAG, "getAddress(): Unable to retrieve address remotely. Returning cached address", e);
1200 } finally {
1201 mBluetoothLock.readLock().unlock();
fredc116d1d462012-04-20 14:47:08 -07001202 }
Ajay Panickerbf796d82016-03-11 13:47:20 -08001203
Matthew Xiecdce0b92012-07-12 19:06:15 -07001204 // mAddress is accessed from outside.
1205 // It is alright without a lock. Here, bluetooth is off, no other thread is
1206 // changing mAddress
fredc0f420372012-04-12 00:02:00 -07001207 return mAddress;
1208 }
fredc649fe492012-04-19 01:07:18 -07001209
fredc0f420372012-04-12 00:02:00 -07001210 public String getName() {
Matthew Xieaf5ddbf2012-12-04 10:47:43 -08001211 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
1212 "Need BLUETOOTH permission");
Zhihai Xu40874a02012-10-08 17:57:03 -07001213
Zhihai Xu6eb76522012-11-29 15:41:04 -08001214 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
1215 (!checkIfCallerIsForegroundUser())) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001216 Slog.w(TAG,"getName(): not allowed for non-active and non system user");
Zhihai Xu6eb76522012-11-29 15:41:04 -08001217 return null;
Zhihai Xu40874a02012-10-08 17:57:03 -07001218 }
1219
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001220 try {
1221 mBluetoothLock.readLock().lock();
1222 if (mBluetooth != null) return mBluetooth.getName();
1223 } catch (RemoteException e) {
1224 Slog.e(TAG, "getName(): Unable to retrieve name remotely. Returning cached name", e);
1225 } finally {
1226 mBluetoothLock.readLock().unlock();
fredc116d1d462012-04-20 14:47:08 -07001227 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001228
Matthew Xiecdce0b92012-07-12 19:06:15 -07001229 // mName is accessed from outside.
1230 // It alright without a lock. Here, bluetooth is off, no other thread is
1231 // changing mName
fredc0f420372012-04-12 00:02:00 -07001232 return mName;
1233 }
1234
fredc0f420372012-04-12 00:02:00 -07001235 private class BluetoothServiceConnection implements ServiceConnection {
Marie Janssencb21ad72016-12-13 10:51:02 -08001236 public void onServiceConnected(ComponentName componentName, IBinder service) {
1237 String name = componentName.getClassName();
1238 if (DBG) Slog.d(TAG, "BluetoothServiceConnection: " + name);
fredc0f420372012-04-12 00:02:00 -07001239 Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_SERVICE_CONNECTED);
Marie Janssencb21ad72016-12-13 10:51:02 -08001240 if (name.equals("com.android.bluetooth.btservice.AdapterService")) {
Matthew Xieddf7e472013-03-01 18:41:02 -08001241 msg.arg1 = SERVICE_IBLUETOOTH;
Marie Janssencb21ad72016-12-13 10:51:02 -08001242 } else if (name.equals("com.android.bluetooth.gatt.GattService")) {
Matthew Xieddf7e472013-03-01 18:41:02 -08001243 msg.arg1 = SERVICE_IBLUETOOTHGATT;
1244 } else {
Marie Janssencb21ad72016-12-13 10:51:02 -08001245 Slog.e(TAG, "Unknown service connected: " + name);
Matthew Xieddf7e472013-03-01 18:41:02 -08001246 return;
1247 }
fredc0f420372012-04-12 00:02:00 -07001248 msg.obj = service;
1249 mHandler.sendMessage(msg);
1250 }
1251
Marie Janssencb21ad72016-12-13 10:51:02 -08001252 public void onServiceDisconnected(ComponentName componentName) {
1253 // Called if we unexpectedly disconnect.
1254 String name = componentName.getClassName();
1255 if (DBG) Slog.d(TAG, "BluetoothServiceConnection, disconnected: " + name);
fredc0f420372012-04-12 00:02:00 -07001256 Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED);
Marie Janssencb21ad72016-12-13 10:51:02 -08001257 if (name.equals("com.android.bluetooth.btservice.AdapterService")) {
Matthew Xieddf7e472013-03-01 18:41:02 -08001258 msg.arg1 = SERVICE_IBLUETOOTH;
Marie Janssencb21ad72016-12-13 10:51:02 -08001259 } else if (name.equals("com.android.bluetooth.gatt.GattService")) {
Matthew Xieddf7e472013-03-01 18:41:02 -08001260 msg.arg1 = SERVICE_IBLUETOOTHGATT;
1261 } else {
Marie Janssencb21ad72016-12-13 10:51:02 -08001262 Slog.e(TAG, "Unknown service disconnected: " + name);
Matthew Xieddf7e472013-03-01 18:41:02 -08001263 return;
1264 }
fredc0f420372012-04-12 00:02:00 -07001265 mHandler.sendMessage(msg);
1266 }
1267 }
1268
1269 private BluetoothServiceConnection mConnection = new BluetoothServiceConnection();
1270
Zhihai Xu40874a02012-10-08 17:57:03 -07001271 private class BluetoothHandler extends Handler {
Ajay Panicker4bb48302016-03-31 14:14:27 -07001272 boolean mGetNameAddressOnly = false;
1273
Zhihai Xu40874a02012-10-08 17:57:03 -07001274 public BluetoothHandler(Looper looper) {
1275 super(looper);
1276 }
1277
fredc0f420372012-04-12 00:02:00 -07001278 @Override
1279 public void handleMessage(Message msg) {
fredc0f420372012-04-12 00:02:00 -07001280 switch (msg.what) {
Ajay Panicker4bb48302016-03-31 14:14:27 -07001281 case MESSAGE_GET_NAME_AND_ADDRESS:
1282 if (DBG) Slog.d(TAG, "MESSAGE_GET_NAME_AND_ADDRESS");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001283 try {
1284 mBluetoothLock.writeLock().lock();
Ajay Panicker4bb48302016-03-31 14:14:27 -07001285 if ((mBluetooth == null) && (!mBinding)) {
1286 if (DBG) Slog.d(TAG, "Binding to service to get name and address");
1287 mGetNameAddressOnly = true;
1288 Message timeoutMsg = mHandler.obtainMessage(MESSAGE_TIMEOUT_BIND);
1289 mHandler.sendMessageDelayed(timeoutMsg, TIMEOUT_BIND_MS);
1290 Intent i = new Intent(IBluetooth.class.getName());
1291 if (!doBind(i, mConnection,
1292 Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT,
1293 UserHandle.CURRENT)) {
1294 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
1295 } else {
1296 mBinding = true;
1297 }
1298 } else if (mBluetooth != null) {
1299 try {
1300 storeNameAndAddress(mBluetooth.getName(),
1301 mBluetooth.getAddress());
1302 } catch (RemoteException re) {
1303 Slog.e(TAG, "Unable to grab names", re);
1304 }
1305 if (mGetNameAddressOnly && !mEnable) {
1306 unbindAndFinish();
1307 }
1308 mGetNameAddressOnly = false;
1309 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001310 } finally {
1311 mBluetoothLock.writeLock().unlock();
Ajay Panicker4bb48302016-03-31 14:14:27 -07001312 }
1313 break;
1314
Matthew Xiecdce0b92012-07-12 19:06:15 -07001315 case MESSAGE_ENABLE:
fredcf2458862012-04-16 15:18:27 -07001316 if (DBG) {
Marie Janssencb21ad72016-12-13 10:51:02 -08001317 Slog.d(TAG, "MESSAGE_ENABLE(" + msg.arg1 + "): mBluetooth = " + mBluetooth);
fredc649fe492012-04-19 01:07:18 -07001318 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001319 mHandler.removeMessages(MESSAGE_RESTART_BLUETOOTH_SERVICE);
1320 mEnable = true;
Calvin Ona0b91d72016-06-15 17:58:23 -07001321
1322 // Use service interface to get the exact state
1323 try {
1324 mBluetoothLock.readLock().lock();
1325 if (mBluetooth != null) {
1326 int state = mBluetooth.getState();
1327 if (state == BluetoothAdapter.STATE_BLE_ON) {
Marie Janssene0bfa2e2016-12-20 11:21:12 -08001328 Slog.w(TAG, "BT Enable in BLE_ON State, going to ON");
Calvin Ona0b91d72016-06-15 17:58:23 -07001329 mBluetooth.onLeServiceUp();
Marie Janssene0bfa2e2016-12-20 11:21:12 -08001330 persistBluetoothSetting(BLUETOOTH_ON_BLUETOOTH);
Calvin Ona0b91d72016-06-15 17:58:23 -07001331 break;
1332 }
1333 }
1334 } catch (RemoteException e) {
1335 Slog.e(TAG, "", e);
1336 } finally {
1337 mBluetoothLock.readLock().unlock();
1338 }
1339
1340 mQuietEnable = (msg.arg1 == 1);
Pavlin Radoslavove47ec142016-06-01 22:25:18 -07001341 if (mBluetooth == null) {
Calvin Ona0b91d72016-06-15 17:58:23 -07001342 handleEnable(mQuietEnable);
Pavlin Radoslavove47ec142016-06-01 22:25:18 -07001343 } else {
1344 //
1345 // We need to wait until transitioned to STATE_OFF and
1346 // the previous Bluetooth process has exited. The
1347 // waiting period has three components:
1348 // (a) Wait until the local state is STATE_OFF. This
1349 // is accomplished by "waitForOnOff(false, true)".
1350 // (b) Wait until the STATE_OFF state is updated to
1351 // all components.
1352 // (c) Wait until the Bluetooth process exits, and
1353 // ActivityManager detects it.
1354 // The waiting for (b) and (c) is accomplished by
1355 // delaying the MESSAGE_RESTART_BLUETOOTH_SERVICE
1356 // message. On slower devices, that delay needs to be
1357 // on the order of (2 * SERVICE_RESTART_TIME_MS).
1358 //
1359 waitForOnOff(false, true);
Pavlin Radoslavove47ec142016-06-01 22:25:18 -07001360 Message restartMsg = mHandler.obtainMessage(
1361 MESSAGE_RESTART_BLUETOOTH_SERVICE);
1362 mHandler.sendMessageDelayed(restartMsg,
1363 2 * SERVICE_RESTART_TIME_MS);
1364 }
fredc649fe492012-04-19 01:07:18 -07001365 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001366
fredc0f420372012-04-12 00:02:00 -07001367 case MESSAGE_DISABLE:
Marie Janssencb21ad72016-12-13 10:51:02 -08001368 if (DBG) Slog.d(TAG, "MESSAGE_DISABLE: mBluetooth = " + mBluetooth);
Zhihai Xu40874a02012-10-08 17:57:03 -07001369 mHandler.removeMessages(MESSAGE_RESTART_BLUETOOTH_SERVICE);
1370 if (mEnable && mBluetooth != null) {
1371 waitForOnOff(true, false);
1372 mEnable = false;
Zhihai Xu401202b2012-12-03 11:36:21 -08001373 handleDisable();
Zhihai Xu40874a02012-10-08 17:57:03 -07001374 waitForOnOff(false, false);
1375 } else {
1376 mEnable = false;
Zhihai Xu401202b2012-12-03 11:36:21 -08001377 handleDisable();
Zhihai Xu40874a02012-10-08 17:57:03 -07001378 }
fredc0f420372012-04-12 00:02:00 -07001379 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001380
fredc0f420372012-04-12 00:02:00 -07001381 case MESSAGE_REGISTER_ADAPTER:
1382 {
1383 IBluetoothManagerCallback callback = (IBluetoothManagerCallback) msg.obj;
Marie Janssencb21ad72016-12-13 10:51:02 -08001384 mCallbacks.register(callback);
fredc0f420372012-04-12 00:02:00 -07001385 break;
Marie Janssencb21ad72016-12-13 10:51:02 -08001386 }
fredc0f420372012-04-12 00:02:00 -07001387 case MESSAGE_UNREGISTER_ADAPTER:
1388 {
1389 IBluetoothManagerCallback callback = (IBluetoothManagerCallback) msg.obj;
Marie Janssencb21ad72016-12-13 10:51:02 -08001390 mCallbacks.unregister(callback);
fredc0f420372012-04-12 00:02:00 -07001391 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001392 }
fredc0f420372012-04-12 00:02:00 -07001393 case MESSAGE_REGISTER_STATE_CHANGE_CALLBACK:
1394 {
1395 IBluetoothStateChangeCallback callback = (IBluetoothStateChangeCallback) msg.obj;
Marie Janssencb21ad72016-12-13 10:51:02 -08001396 mStateChangeCallbacks.register(callback);
fredc0f420372012-04-12 00:02:00 -07001397 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001398 }
fredc0f420372012-04-12 00:02:00 -07001399 case MESSAGE_UNREGISTER_STATE_CHANGE_CALLBACK:
1400 {
1401 IBluetoothStateChangeCallback callback = (IBluetoothStateChangeCallback) msg.obj;
Marie Janssencb21ad72016-12-13 10:51:02 -08001402 mStateChangeCallbacks.unregister(callback);
fredc0f420372012-04-12 00:02:00 -07001403 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001404 }
Benjamin Franze8b98922014-11-12 15:57:54 +00001405 case MESSAGE_ADD_PROXY_DELAYED:
1406 {
1407 ProfileServiceConnections psc = mProfileServices.get(
1408 new Integer(msg.arg1));
1409 if (psc == null) {
1410 break;
1411 }
1412 IBluetoothProfileServiceConnection proxy =
1413 (IBluetoothProfileServiceConnection) msg.obj;
1414 psc.addProxy(proxy);
1415 break;
1416 }
1417 case MESSAGE_BIND_PROFILE_SERVICE:
1418 {
1419 ProfileServiceConnections psc = (ProfileServiceConnections) msg.obj;
1420 removeMessages(MESSAGE_BIND_PROFILE_SERVICE, msg.obj);
1421 if (psc == null) {
1422 break;
1423 }
1424 psc.bindService();
1425 break;
1426 }
fredc0f420372012-04-12 00:02:00 -07001427 case MESSAGE_BLUETOOTH_SERVICE_CONNECTED:
1428 {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001429 if (DBG) Slog.d(TAG,"MESSAGE_BLUETOOTH_SERVICE_CONNECTED: " + msg.arg1);
fredc0f420372012-04-12 00:02:00 -07001430
1431 IBinder service = (IBinder) msg.obj;
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001432 try {
1433 mBluetoothLock.writeLock().lock();
Matthew Xieddf7e472013-03-01 18:41:02 -08001434 if (msg.arg1 == SERVICE_IBLUETOOTHGATT) {
1435 mBluetoothGatt = IBluetoothGatt.Stub.asInterface(service);
Nitin Arorad055adb2015-03-02 15:03:51 -08001436 onBluetoothGattServiceUp();
Matthew Xieddf7e472013-03-01 18:41:02 -08001437 break;
1438 } // else must be SERVICE_IBLUETOOTH
1439
1440 //Remove timeout
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001441 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
Matthew Xieddf7e472013-03-01 18:41:02 -08001442
fredc0f420372012-04-12 00:02:00 -07001443 mBinding = false;
Marie Janssen9db28eb2016-01-12 16:05:15 -08001444 mBluetoothBinder = service;
fredc0f420372012-04-12 00:02:00 -07001445 mBluetooth = IBluetooth.Stub.asInterface(service);
fredc0f420372012-04-12 00:02:00 -07001446
Ajay Panicker4bb48302016-03-31 14:14:27 -07001447 if (!isNameAndAddressSet()) {
1448 Message getMsg = mHandler.obtainMessage(MESSAGE_GET_NAME_AND_ADDRESS);
1449 mHandler.sendMessage(getMsg);
1450 if (mGetNameAddressOnly) return;
1451 }
1452
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001453 try {
1454 boolean enableHciSnoopLog = (Settings.Secure.getInt(mContentResolver,
1455 Settings.Secure.BLUETOOTH_HCI_LOG, 0) == 1);
1456 if (!mBluetooth.configHciSnoopLog(enableHciSnoopLog)) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001457 Slog.e(TAG,"IBluetooth.configHciSnoopLog return false");
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001458 }
1459 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001460 Slog.e(TAG,"Unable to call configHciSnoopLog", e);
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001461 }
1462
Matthew Xiecdce0b92012-07-12 19:06:15 -07001463 //Register callback object
fredcbf072a72012-05-09 16:52:50 -07001464 try {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001465 mBluetooth.registerCallback(mBluetoothCallback);
1466 } catch (RemoteException re) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001467 Slog.e(TAG, "Unable to register BluetoothCallback",re);
fredcbf072a72012-05-09 16:52:50 -07001468 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001469 //Inform BluetoothAdapter instances that service is up
Zhihai Xu40874a02012-10-08 17:57:03 -07001470 sendBluetoothServiceUpCallback();
1471
Matthew Xiecdce0b92012-07-12 19:06:15 -07001472 //Do enable request
1473 try {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001474 if (mQuietEnable == false) {
Marie Janssencb21ad72016-12-13 10:51:02 -08001475 if (!mBluetooth.enable()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001476 Slog.e(TAG,"IBluetooth.enable() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001477 }
Marie Janssencb21ad72016-12-13 10:51:02 -08001478 } else {
1479 if (!mBluetooth.enableNoAutoConnect()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001480 Slog.e(TAG,"IBluetooth.enableNoAutoConnect() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001481 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001482 }
1483 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001484 Slog.e(TAG,"Unable to call enable()",e);
Matthew Xiecdce0b92012-07-12 19:06:15 -07001485 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001486 } finally {
1487 mBluetoothLock.writeLock().unlock();
Freda8c6df02012-07-11 10:25:23 -07001488 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001489
1490 if (!mEnable) {
1491 waitForOnOff(true, false);
Zhihai Xu401202b2012-12-03 11:36:21 -08001492 handleDisable();
Zhihai Xu40874a02012-10-08 17:57:03 -07001493 waitForOnOff(false, false);
1494 }
fredc649fe492012-04-19 01:07:18 -07001495 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001496 }
fredcbf072a72012-05-09 16:52:50 -07001497 case MESSAGE_BLUETOOTH_STATE_CHANGE:
fredc0f420372012-04-12 00:02:00 -07001498 {
fredcbf072a72012-05-09 16:52:50 -07001499 int prevState = msg.arg1;
1500 int newState = msg.arg2;
Marie Janssencb21ad72016-12-13 10:51:02 -08001501 if (DBG) {
1502 Slog.d(TAG, "MESSAGE_BLUETOOTH_STATE_CHANGE: " + BluetoothAdapter.nameForState(prevState) + " > " +
1503 BluetoothAdapter.nameForState(newState));
1504 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001505 mState = newState;
1506 bluetoothStateChangeHandler(prevState, newState);
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001507 // handle error state transition case from TURNING_ON to OFF
1508 // unbind and rebind bluetooth service and enable bluetooth
Nitin Arorad055adb2015-03-02 15:03:51 -08001509 if ((prevState == BluetoothAdapter.STATE_BLE_TURNING_ON) &&
Calvin Ona0b91d72016-06-15 17:58:23 -07001510 (newState == BluetoothAdapter.STATE_OFF) &&
1511 (mBluetooth != null) && mEnable) {
Marie Janssen2977c3e2016-11-09 12:01:24 -08001512 recoverBluetoothServiceFromError(false);
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001513 }
Nitin Arorad055adb2015-03-02 15:03:51 -08001514 if ((prevState == BluetoothAdapter.STATE_TURNING_ON) &&
Calvin Ona0b91d72016-06-15 17:58:23 -07001515 (newState == BluetoothAdapter.STATE_BLE_ON) &&
1516 (mBluetooth != null) && mEnable) {
Marie Janssen2977c3e2016-11-09 12:01:24 -08001517 recoverBluetoothServiceFromError(true);
Nitin Arorad055adb2015-03-02 15:03:51 -08001518 }
Calvin Ona0b91d72016-06-15 17:58:23 -07001519 // If we tried to enable BT while BT was in the process of shutting down,
1520 // wait for the BT process to fully tear down and then force a restart
1521 // here. This is a bit of a hack (b/29363429).
1522 if ((prevState == BluetoothAdapter.STATE_BLE_TURNING_OFF) &&
1523 (newState == BluetoothAdapter.STATE_OFF)) {
1524 if (mEnable) {
1525 Slog.d(TAG, "Entering STATE_OFF but mEnabled is true; restarting.");
1526 waitForOnOff(false, true);
1527 Message restartMsg = mHandler.obtainMessage(
1528 MESSAGE_RESTART_BLUETOOTH_SERVICE);
1529 mHandler.sendMessageDelayed(restartMsg, 2 * SERVICE_RESTART_TIME_MS);
1530 }
1531 }
Nitin Arorad055adb2015-03-02 15:03:51 -08001532 if (newState == BluetoothAdapter.STATE_ON ||
Calvin Ona0b91d72016-06-15 17:58:23 -07001533 newState == BluetoothAdapter.STATE_BLE_ON) {
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001534 // bluetooth is working, reset the counter
1535 if (mErrorRecoveryRetryCounter != 0) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001536 Slog.w(TAG, "bluetooth is recovered from error");
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001537 mErrorRecoveryRetryCounter = 0;
1538 }
1539 }
fredc649fe492012-04-19 01:07:18 -07001540 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001541 }
fredc0f420372012-04-12 00:02:00 -07001542 case MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED:
1543 {
Marie Janssencb21ad72016-12-13 10:51:02 -08001544 Slog.e(TAG, "MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED(" + msg.arg1 + ")");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001545 try {
1546 mBluetoothLock.writeLock().lock();
Matthew Xieddf7e472013-03-01 18:41:02 -08001547 if (msg.arg1 == SERVICE_IBLUETOOTH) {
1548 // if service is unbinded already, do nothing and return
1549 if (mBluetooth == null) break;
1550 mBluetooth = null;
1551 } else if (msg.arg1 == SERVICE_IBLUETOOTHGATT) {
1552 mBluetoothGatt = null;
1553 break;
1554 } else {
Marie Janssencb21ad72016-12-13 10:51:02 -08001555 Slog.e(TAG, "Unknown argument for service disconnect!");
Matthew Xieddf7e472013-03-01 18:41:02 -08001556 break;
1557 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001558 } finally {
1559 mBluetoothLock.writeLock().unlock();
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301560 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001561
1562 if (mEnable) {
1563 mEnable = false;
1564 // Send a Bluetooth Restart message
1565 Message restartMsg = mHandler.obtainMessage(
1566 MESSAGE_RESTART_BLUETOOTH_SERVICE);
1567 mHandler.sendMessageDelayed(restartMsg,
1568 SERVICE_RESTART_TIME_MS);
1569 }
1570
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001571 sendBluetoothServiceDownCallback();
Zhihai Xu40874a02012-10-08 17:57:03 -07001572
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001573 // Send BT state broadcast to update
1574 // the BT icon correctly
1575 if ((mState == BluetoothAdapter.STATE_TURNING_ON) ||
Calvin Ona0b91d72016-06-15 17:58:23 -07001576 (mState == BluetoothAdapter.STATE_ON)) {
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001577 bluetoothStateChangeHandler(BluetoothAdapter.STATE_ON,
1578 BluetoothAdapter.STATE_TURNING_OFF);
1579 mState = BluetoothAdapter.STATE_TURNING_OFF;
Zhihai Xu40874a02012-10-08 17:57:03 -07001580 }
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001581 if (mState == BluetoothAdapter.STATE_TURNING_OFF) {
1582 bluetoothStateChangeHandler(BluetoothAdapter.STATE_TURNING_OFF,
1583 BluetoothAdapter.STATE_OFF);
1584 }
1585
1586 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
1587 mState = BluetoothAdapter.STATE_OFF;
fredc649fe492012-04-19 01:07:18 -07001588 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001589 }
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301590 case MESSAGE_RESTART_BLUETOOTH_SERVICE:
1591 {
Marie Janssencb21ad72016-12-13 10:51:02 -08001592 Slog.d(TAG, "MESSAGE_RESTART_BLUETOOTH_SERVICE");
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301593 /* Enable without persisting the setting as
1594 it doesnt change when IBluetooth
1595 service restarts */
Zhihai Xu40874a02012-10-08 17:57:03 -07001596 mEnable = true;
Zhihai Xu401202b2012-12-03 11:36:21 -08001597 handleEnable(mQuietEnable);
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301598 break;
1599 }
Marie Janssencb21ad72016-12-13 10:51:02 -08001600 case MESSAGE_TIMEOUT_BIND: {
1601 Slog.e(TAG, "MESSAGE_TIMEOUT_BIND");
1602 mBluetoothLock.writeLock().lock();
1603 mBinding = false;
1604 mBluetoothLock.writeLock().unlock();
1605 break;
1606 }
fredc0f420372012-04-12 00:02:00 -07001607 case MESSAGE_TIMEOUT_UNBIND:
1608 {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001609 Slog.e(TAG, "MESSAGE_TIMEOUT_UNBIND");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001610 mBluetoothLock.writeLock().lock();
1611 mUnbinding = false;
1612 mBluetoothLock.writeLock().unlock();
fredc649fe492012-04-19 01:07:18 -07001613 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001614 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001615
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001616 case MESSAGE_USER_SWITCHED: {
1617 if (DBG) Slog.d(TAG, "MESSAGE_USER_SWITCHED");
Zhihai Xu40874a02012-10-08 17:57:03 -07001618 mHandler.removeMessages(MESSAGE_USER_SWITCHED);
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001619
Zhihai Xu40874a02012-10-08 17:57:03 -07001620 /* disable and enable BT when detect a user switch */
1621 if (mEnable && mBluetooth != null) {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001622 try {
1623 mBluetoothLock.readLock().lock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001624 if (mBluetooth != null) {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001625 mBluetooth.unregisterCallback(mBluetoothCallback);
Zhihai Xu40874a02012-10-08 17:57:03 -07001626 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001627 } catch (RemoteException re) {
1628 Slog.e(TAG, "Unable to unregister", re);
1629 } finally {
1630 mBluetoothLock.readLock().unlock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001631 }
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001632
1633 if (mState == BluetoothAdapter.STATE_TURNING_OFF) {
1634 // MESSAGE_USER_SWITCHED happened right after MESSAGE_ENABLE
1635 bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_OFF);
1636 mState = BluetoothAdapter.STATE_OFF;
1637 }
1638 if (mState == BluetoothAdapter.STATE_OFF) {
1639 bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_TURNING_ON);
1640 mState = BluetoothAdapter.STATE_TURNING_ON;
1641 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001642
1643 waitForOnOff(true, false);
1644
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001645 if (mState == BluetoothAdapter.STATE_TURNING_ON) {
1646 bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_ON);
1647 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001648
Benjamin Franze8b98922014-11-12 15:57:54 +00001649 unbindAllBluetoothProfileServices();
Zhihai Xu40874a02012-10-08 17:57:03 -07001650 // disable
Zhihai Xu401202b2012-12-03 11:36:21 -08001651 handleDisable();
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001652 // Pbap service need receive STATE_TURNING_OFF intent to close
1653 bluetoothStateChangeHandler(BluetoothAdapter.STATE_ON,
1654 BluetoothAdapter.STATE_TURNING_OFF);
Zhihai Xu40874a02012-10-08 17:57:03 -07001655
Pavlin Radoslavov41401112016-06-27 15:25:18 -07001656 boolean didDisableTimeout = !waitForOnOff(false, true);
Zhihai Xu40874a02012-10-08 17:57:03 -07001657
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001658 bluetoothStateChangeHandler(BluetoothAdapter.STATE_TURNING_OFF,
Zhihai Xu40874a02012-10-08 17:57:03 -07001659 BluetoothAdapter.STATE_OFF);
Zhihai Xu40874a02012-10-08 17:57:03 -07001660 sendBluetoothServiceDownCallback();
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001661
Pavlin Radoslavove957a8a2016-05-24 15:28:41 -07001662 try {
1663 mBluetoothLock.writeLock().lock();
1664 if (mBluetooth != null) {
1665 mBluetooth = null;
1666 // Unbind
1667 mContext.unbindService(mConnection);
1668 }
1669 mBluetoothGatt = null;
1670 } finally {
1671 mBluetoothLock.writeLock().unlock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001672 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001673
Pavlin Radoslavov41401112016-06-27 15:25:18 -07001674 //
1675 // If disabling Bluetooth times out, wait for an
1676 // additional amount of time to ensure the process is
1677 // shut down completely before attempting to restart.
1678 //
1679 if (didDisableTimeout) {
1680 SystemClock.sleep(3000);
1681 } else {
1682 SystemClock.sleep(100);
1683 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001684
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001685 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
1686 mState = BluetoothAdapter.STATE_OFF;
Zhihai Xu40874a02012-10-08 17:57:03 -07001687 // enable
Zhihai Xu401202b2012-12-03 11:36:21 -08001688 handleEnable(mQuietEnable);
John Spurlock8a985d22014-02-25 09:40:05 -05001689 } else if (mBinding || mBluetooth != null) {
Zhihai Xu40874a02012-10-08 17:57:03 -07001690 Message userMsg = mHandler.obtainMessage(MESSAGE_USER_SWITCHED);
1691 userMsg.arg2 = 1 + msg.arg2;
Marie Janssencb21ad72016-12-13 10:51:02 -08001692 // if user is switched when service is binding retry after a delay
Zhihai Xu40874a02012-10-08 17:57:03 -07001693 mHandler.sendMessageDelayed(userMsg, USER_SWITCHED_TIME_MS);
1694 if (DBG) {
Marie Janssencb21ad72016-12-13 10:51:02 -08001695 Slog.d(TAG, "Retry MESSAGE_USER_SWITCHED " + userMsg.arg2);
Zhihai Xu40874a02012-10-08 17:57:03 -07001696 }
John Spurlock8a985d22014-02-25 09:40:05 -05001697 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001698 break;
1699 }
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001700 case MESSAGE_USER_UNLOCKED: {
1701 if (DBG) Slog.d(TAG, "MESSAGE_USER_UNLOCKED");
1702 mHandler.removeMessages(MESSAGE_USER_SWITCHED);
1703
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001704 if (mEnable && !mBinding && (mBluetooth == null)) {
1705 // We should be connected, but we gave up for some
1706 // reason; maybe the Bluetooth service wasn't encryption
1707 // aware, so try binding again.
1708 if (DBG) Slog.d(TAG, "Enabled but not bound; retrying after unlock");
1709 handleEnable(mQuietEnable);
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001710 }
1711 }
fredc0f420372012-04-12 00:02:00 -07001712 }
1713 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001714 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001715
Zhihai Xu401202b2012-12-03 11:36:21 -08001716 private void handleEnable(boolean quietMode) {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001717 mQuietEnable = quietMode;
1718
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001719 try {
1720 mBluetoothLock.writeLock().lock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001721 if ((mBluetooth == null) && (!mBinding)) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001722 //Start bind timeout and bind
1723 Message timeoutMsg=mHandler.obtainMessage(MESSAGE_TIMEOUT_BIND);
1724 mHandler.sendMessageDelayed(timeoutMsg,TIMEOUT_BIND_MS);
Matthew Xiecdce0b92012-07-12 19:06:15 -07001725 Intent i = new Intent(IBluetooth.class.getName());
Dianne Hackbornce09f5a2014-10-10 15:03:13 -07001726 if (!doBind(i, mConnection,Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT,
1727 UserHandle.CURRENT)) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001728 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
Zhihai Xu40874a02012-10-08 17:57:03 -07001729 } else {
1730 mBinding = true;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001731 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001732 } else if (mBluetooth != null) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001733 //Enable bluetooth
1734 try {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001735 if (!mQuietEnable) {
1736 if(!mBluetooth.enable()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001737 Slog.e(TAG,"IBluetooth.enable() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001738 }
1739 }
1740 else {
1741 if(!mBluetooth.enableNoAutoConnect()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001742 Slog.e(TAG,"IBluetooth.enableNoAutoConnect() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001743 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001744 }
1745 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001746 Slog.e(TAG,"Unable to call enable()",e);
Matthew Xiecdce0b92012-07-12 19:06:15 -07001747 }
1748 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001749 } finally {
1750 mBluetoothLock.writeLock().unlock();
Matthew Xiecdce0b92012-07-12 19:06:15 -07001751 }
1752 }
1753
Dianne Hackborn221ea892013-08-04 16:50:16 -07001754 boolean doBind(Intent intent, ServiceConnection conn, int flags, UserHandle user) {
1755 ComponentName comp = intent.resolveSystemService(mContext.getPackageManager(), 0);
1756 intent.setComponent(comp);
1757 if (comp == null || !mContext.bindServiceAsUser(intent, conn, flags, user)) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001758 Slog.e(TAG, "Fail to bind to: " + intent);
Dianne Hackborn221ea892013-08-04 16:50:16 -07001759 return false;
1760 }
1761 return true;
1762 }
1763
Zhihai Xu401202b2012-12-03 11:36:21 -08001764 private void handleDisable() {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001765 try {
1766 mBluetoothLock.readLock().lock();
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001767 if (mBluetooth != null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001768 if (DBG) Slog.d(TAG,"Sending off request.");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001769 if (!mBluetooth.disable()) {
1770 Slog.e(TAG,"IBluetooth.disable() returned false");
Matthew Xiecdce0b92012-07-12 19:06:15 -07001771 }
1772 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001773 } catch (RemoteException e) {
1774 Slog.e(TAG,"Unable to call disable()",e);
1775 } finally {
1776 mBluetoothLock.readLock().unlock();
Matthew Xiecdce0b92012-07-12 19:06:15 -07001777 }
1778 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001779
1780 private boolean checkIfCallerIsForegroundUser() {
1781 int foregroundUser;
1782 int callingUser = UserHandle.getCallingUserId();
Martijn Coenen8385c5a2012-11-29 10:14:16 -08001783 int callingUid = Binder.getCallingUid();
Zhihai Xu40874a02012-10-08 17:57:03 -07001784 long callingIdentity = Binder.clearCallingIdentity();
Benjamin Franze8b98922014-11-12 15:57:54 +00001785 UserManager um = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
1786 UserInfo ui = um.getProfileParent(callingUser);
1787 int parentUser = (ui != null) ? ui.id : UserHandle.USER_NULL;
Martijn Coenen8385c5a2012-11-29 10:14:16 -08001788 int callingAppId = UserHandle.getAppId(callingUid);
Zhihai Xu40874a02012-10-08 17:57:03 -07001789 boolean valid = false;
1790 try {
1791 foregroundUser = ActivityManager.getCurrentUser();
Martijn Coenen8385c5a2012-11-29 10:14:16 -08001792 valid = (callingUser == foregroundUser) ||
Benjamin Franze8b98922014-11-12 15:57:54 +00001793 parentUser == foregroundUser ||
Adrian Roosbd9a9a52014-08-18 15:31:57 +02001794 callingAppId == Process.NFC_UID ||
1795 callingAppId == mSystemUiUid;
Marie Janssencb21ad72016-12-13 10:51:02 -08001796 if (DBG && !valid) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001797 Slog.d(TAG, "checkIfCallerIsForegroundUser: valid=" + valid
Zhihai Xu40874a02012-10-08 17:57:03 -07001798 + " callingUser=" + callingUser
Benjamin Franze8b98922014-11-12 15:57:54 +00001799 + " parentUser=" + parentUser
Zhihai Xu40874a02012-10-08 17:57:03 -07001800 + " foregroundUser=" + foregroundUser);
1801 }
1802 } finally {
1803 Binder.restoreCallingIdentity(callingIdentity);
1804 }
1805 return valid;
1806 }
1807
Nitin Arorad055adb2015-03-02 15:03:51 -08001808 private void sendBleStateChanged(int prevState, int newState) {
Marie Janssencb21ad72016-12-13 10:51:02 -08001809 if (DBG) Slog.d(TAG,"Sending BLE State Change: " + BluetoothAdapter.nameForState(prevState) +
1810 " > " + BluetoothAdapter.nameForState(newState));
Nitin Arorad055adb2015-03-02 15:03:51 -08001811 // Send broadcast message to everyone else
1812 Intent intent = new Intent(BluetoothAdapter.ACTION_BLE_STATE_CHANGED);
1813 intent.putExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE, prevState);
1814 intent.putExtra(BluetoothAdapter.EXTRA_STATE, newState);
1815 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1816 mContext.sendBroadcastAsUser(intent, UserHandle.ALL, BLUETOOTH_PERM);
1817 }
1818
Zhihai Xu40874a02012-10-08 17:57:03 -07001819 private void bluetoothStateChangeHandler(int prevState, int newState) {
Nitin Arorad055adb2015-03-02 15:03:51 -08001820 boolean isStandardBroadcast = true;
Marie Janssencb21ad72016-12-13 10:51:02 -08001821 if (prevState == newState) { // No change. Nothing to do.
1822 return;
1823 }
1824 // Notify all proxy objects first of adapter state change
1825 if (newState == BluetoothAdapter.STATE_BLE_ON ||
1826 newState == BluetoothAdapter.STATE_OFF) {
1827 boolean intermediate_off = (prevState == BluetoothAdapter.STATE_TURNING_OFF
1828 && newState == BluetoothAdapter.STATE_BLE_ON);
Zhihai Xu40874a02012-10-08 17:57:03 -07001829
Marie Janssencb21ad72016-12-13 10:51:02 -08001830 if (newState == BluetoothAdapter.STATE_OFF) {
1831 // If Bluetooth is off, send service down event to proxy objects, and unbind
1832 if (DBG) Slog.d(TAG, "Bluetooth is complete send Service Down");
1833 sendBluetoothServiceDownCallback();
1834 unbindAndFinish();
Nitin Arorad055adb2015-03-02 15:03:51 -08001835 sendBleStateChanged(prevState, newState);
Marie Janssencb21ad72016-12-13 10:51:02 -08001836 // Don't broadcast as it has already been broadcast before
Nitin Arorad055adb2015-03-02 15:03:51 -08001837 isStandardBroadcast = false;
1838
Marie Janssencb21ad72016-12-13 10:51:02 -08001839 } else if (!intermediate_off) {
1840 // connect to GattService
1841 if (DBG) Slog.d(TAG, "Bluetooth is in LE only mode");
1842 if (mBluetoothGatt != null) {
1843 if (DBG) Slog.d(TAG, "Calling BluetoothGattServiceUp");
1844 onBluetoothGattServiceUp();
1845 } else {
1846 if (DBG) Slog.d(TAG, "Binding Bluetooth GATT service");
1847 if (mContext.getPackageManager().hasSystemFeature(
1848 PackageManager.FEATURE_BLUETOOTH_LE)) {
1849 Intent i = new Intent(IBluetoothGatt.class.getName());
1850 doBind(i, mConnection, Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT, UserHandle.CURRENT);
1851 }
Nitin Arorad055adb2015-03-02 15:03:51 -08001852 }
Marie Janssencb21ad72016-12-13 10:51:02 -08001853 sendBleStateChanged(prevState, newState);
1854 //Don't broadcase this as std intent
1855 isStandardBroadcast = false;
1856
1857 } else if (intermediate_off) {
1858 if (DBG) Slog.d(TAG, "Intermediate off, back to LE only mode");
1859 // For LE only mode, broadcast as is
1860 sendBleStateChanged(prevState, newState);
1861 sendBluetoothStateCallback(false); // BT is OFF for general users
1862 // Broadcast as STATE_OFF
1863 newState = BluetoothAdapter.STATE_OFF;
1864 sendBrEdrDownCallback();
Nitin Arorad055adb2015-03-02 15:03:51 -08001865 }
Marie Janssencb21ad72016-12-13 10:51:02 -08001866 } else if (newState == BluetoothAdapter.STATE_ON) {
1867 boolean isUp = (newState == BluetoothAdapter.STATE_ON);
1868 sendBluetoothStateCallback(isUp);
1869 sendBleStateChanged(prevState, newState);
1870
1871 } else if (newState == BluetoothAdapter.STATE_BLE_TURNING_ON ||
1872 newState == BluetoothAdapter.STATE_BLE_TURNING_OFF ) {
1873 sendBleStateChanged(prevState, newState);
1874 isStandardBroadcast = false;
1875
1876 } else if (newState == BluetoothAdapter.STATE_TURNING_ON ||
1877 newState == BluetoothAdapter.STATE_TURNING_OFF) {
1878 sendBleStateChanged(prevState, newState);
1879 }
1880
1881 if (isStandardBroadcast) {
1882 if (prevState == BluetoothAdapter.STATE_BLE_ON) {
1883 // Show prevState of BLE_ON as OFF to standard users
1884 prevState = BluetoothAdapter.STATE_OFF;
1885 }
1886 Intent intent = new Intent(BluetoothAdapter.ACTION_STATE_CHANGED);
1887 intent.putExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE, prevState);
1888 intent.putExtra(BluetoothAdapter.EXTRA_STATE, newState);
1889 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1890 mContext.sendBroadcastAsUser(intent, UserHandle.ALL, BLUETOOTH_PERM);
Zhihai Xu40874a02012-10-08 17:57:03 -07001891 }
1892 }
1893
1894 /**
1895 * if on is true, wait for state become ON
1896 * if off is true, wait for state become OFF
1897 * if both on and off are false, wait for state not ON
1898 */
1899 private boolean waitForOnOff(boolean on, boolean off) {
1900 int i = 0;
1901 while (i < 10) {
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001902 try {
1903 mBluetoothLock.readLock().lock();
1904 if (mBluetooth == null) break;
1905 if (on) {
1906 if (mBluetooth.getState() == BluetoothAdapter.STATE_ON) return true;
1907 } else if (off) {
1908 if (mBluetooth.getState() == BluetoothAdapter.STATE_OFF) return true;
1909 } else {
1910 if (mBluetooth.getState() != BluetoothAdapter.STATE_ON) return true;
Zhihai Xu40874a02012-10-08 17:57:03 -07001911 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001912 } catch (RemoteException e) {
1913 Slog.e(TAG, "getState()", e);
1914 break;
1915 } finally {
1916 mBluetoothLock.readLock().unlock();
Zhihai Xu40874a02012-10-08 17:57:03 -07001917 }
1918 if (on || off) {
1919 SystemClock.sleep(300);
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07001920 } else {
Zhihai Xu40874a02012-10-08 17:57:03 -07001921 SystemClock.sleep(50);
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07001922 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001923 i++;
1924 }
Jeff Sharkey67609c72016-03-05 14:29:13 -07001925 Slog.e(TAG,"waitForOnOff time out");
Zhihai Xu40874a02012-10-08 17:57:03 -07001926 return false;
1927 }
Zhihai Xu681ae7f2012-11-12 15:14:18 -08001928
Marie Janssen59804562016-12-28 14:13:21 -08001929 private void sendDisableMsg(String packageName) {
Zhihai Xu401202b2012-12-03 11:36:21 -08001930 mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_DISABLE));
Marie Janssen59804562016-12-28 14:13:21 -08001931 addActiveLog(packageName, false);
Zhihai Xu401202b2012-12-03 11:36:21 -08001932 }
1933
Marie Janssen59804562016-12-28 14:13:21 -08001934 private void sendEnableMsg(boolean quietMode, String packageName) {
Zhihai Xu401202b2012-12-03 11:36:21 -08001935 mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_ENABLE,
1936 quietMode ? 1 : 0, 0));
Marie Janssen59804562016-12-28 14:13:21 -08001937 addActiveLog(packageName, true);
1938 }
1939
1940 private void addActiveLog(String packageName, boolean enable) {
1941 synchronized (mActiveLogs) {
1942 if (mActiveLogs.size() > 10) {
1943 mActiveLogs.remove();
1944 }
1945 mActiveLogs.add(new ActiveLog(packageName, enable, System.currentTimeMillis()));
1946 }
Zhihai Xu401202b2012-12-03 11:36:21 -08001947 }
1948
Marie Janssen2977c3e2016-11-09 12:01:24 -08001949 private void recoverBluetoothServiceFromError(boolean clearBle) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001950 Slog.e(TAG,"recoverBluetoothServiceFromError");
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001951 try {
1952 mBluetoothLock.readLock().lock();
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001953 if (mBluetooth != null) {
1954 //Unregister callback object
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001955 mBluetooth.unregisterCallback(mBluetoothCallback);
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001956 }
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001957 } catch (RemoteException re) {
1958 Slog.e(TAG, "Unable to unregister", re);
1959 } finally {
1960 mBluetoothLock.readLock().unlock();
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001961 }
1962
1963 SystemClock.sleep(500);
1964
1965 // disable
1966 handleDisable();
1967
1968 waitForOnOff(false, true);
1969
1970 sendBluetoothServiceDownCallback();
Pavlin Radoslavoveb50a392016-05-22 22:16:41 -07001971
Pavlin Radoslavove957a8a2016-05-24 15:28:41 -07001972 try {
1973 mBluetoothLock.writeLock().lock();
1974 if (mBluetooth != null) {
1975 mBluetooth = null;
1976 // Unbind
1977 mContext.unbindService(mConnection);
1978 }
1979 mBluetoothGatt = null;
1980 } finally {
1981 mBluetoothLock.writeLock().unlock();
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001982 }
1983
1984 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
1985 mState = BluetoothAdapter.STATE_OFF;
1986
Marie Janssen2977c3e2016-11-09 12:01:24 -08001987 if (clearBle) {
1988 clearBleApps();
1989 }
1990
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001991 mEnable = false;
1992
1993 if (mErrorRecoveryRetryCounter++ < MAX_ERROR_RESTART_RETRIES) {
1994 // Send a Bluetooth Restart message to reenable bluetooth
1995 Message restartMsg = mHandler.obtainMessage(
1996 MESSAGE_RESTART_BLUETOOTH_SERVICE);
1997 mHandler.sendMessageDelayed(restartMsg, ERROR_RESTART_TIME_MS);
1998 } else {
1999 // todo: notify user to power down and power up phone to make bluetooth work.
2000 }
2001 }
Mike Lockwood726d4de2014-10-28 14:06:28 -07002002
Lenka Trochtova13a05192016-12-02 12:19:39 +01002003 private boolean isBluetoothDisallowed() {
2004 long callingIdentity = Binder.clearCallingIdentity();
2005 try {
2006 return mContext.getSystemService(UserManager.class)
2007 .hasUserRestriction(UserManager.DISALLOW_BLUETOOTH, UserHandle.SYSTEM);
2008 } finally {
2009 Binder.restoreCallingIdentity(callingIdentity);
2010 }
2011 }
2012
Lenka Trochtovac6f0e232017-01-17 10:35:49 +01002013 /**
2014 * Disables BluetoothOppLauncherActivity component, so the Bluetooth sharing option is not
2015 * offered to the user if Bluetooth is disallowed. Puts the component to its default state if
2016 * Bluetooth is not disallowed.
2017 *
2018 * @param bluetoothDisallowed whether the {@link UserManager.DISALLOW_BLUETOOTH} user
2019 * restriction was set.
2020 */
2021 private void updateOppLauncherComponentState(boolean bluetoothDisallowed) {
2022 final ComponentName oppLauncherComponent = new ComponentName("com.android.bluetooth",
2023 "com.android.bluetooth.opp.BluetoothOppLauncherActivity");
2024 final int newState = bluetoothDisallowed
2025 ? PackageManager.COMPONENT_ENABLED_STATE_DISABLED
2026 : PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
2027 try {
2028 mContext.getPackageManager()
2029 .setComponentEnabledSetting(oppLauncherComponent, newState, 0);
2030 } catch (Exception e) {
2031 // The component was not found, do nothing.
2032 }
2033 }
2034
Mike Lockwood726d4de2014-10-28 14:06:28 -07002035 @Override
Pavlin Radoslavov6e8faff2016-02-23 11:54:37 -08002036 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
2037 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DUMP, TAG);
2038 String errorMsg = null;
Marie Janssen59804562016-12-28 14:13:21 -08002039
2040 boolean protoOut = (args.length > 0) && args[0].startsWith("--proto");
2041
2042 if (!protoOut) {
2043 writer.println("Bluetooth Status");
2044 writer.println(" enabled: " + isEnabled());
2045 writer.println(" state: " + BluetoothAdapter.nameForState(mState));
2046 writer.println(" address: " + mAddress);
2047 writer.println(" name: " + mName);
2048 if (mEnable) {
2049 long onDuration = System.currentTimeMillis() - mActiveLogs.getLast().getTime();
2050 String onDurationString = String.format("%02d:%02d:%02d.%03d",
2051 (int)(onDuration / (1000 * 60 * 60)),
2052 (int)((onDuration / (1000 * 60)) % 60),
2053 (int)((onDuration / 1000) % 60),
2054 (int)(onDuration % 1000));
2055 writer.println(" time since enabled: " + onDurationString + "\n");
2056 }
2057
Marie Janssena95924d2017-01-18 09:37:52 -08002058 if (mActiveLogs.size() == 0) {
2059 writer.println("Bluetooth never enabled!");
2060 } else {
2061 writer.println("Enable log:");
2062 for (ActiveLog log : mActiveLogs) {
2063 writer.println(" " + log);
2064 }
Marie Janssen59804562016-12-28 14:13:21 -08002065 }
2066
Marie Janssena95924d2017-01-18 09:37:52 -08002067 String bleAppString = "No BLE Apps registered.";
2068 if (mBleApps.size() == 1) {
2069 bleAppString = "1 BLE App registered:";
2070 } else if (mBleApps.size() > 1) {
2071 bleAppString = mBleApps.size() + " BLE Apps registered:";
2072 }
2073 writer.println("\n" + bleAppString);
Marie Janssen59804562016-12-28 14:13:21 -08002074 for (ClientDeathRecipient app : mBleApps.values()) {
Marie Janssena95924d2017-01-18 09:37:52 -08002075 writer.println(" " + app.getPackageName());
Marie Janssen59804562016-12-28 14:13:21 -08002076 }
2077
Marie Janssena95924d2017-01-18 09:37:52 -08002078 writer.println("");
Marie Janssen59804562016-12-28 14:13:21 -08002079 writer.flush();
Marie Janssenf5ec5382017-01-03 11:37:38 -08002080 if (args.length == 0) {
Marie Janssena95924d2017-01-18 09:37:52 -08002081 // Add arg to produce output
2082 args = new String[1];
2083 args[0] = "--print";
Marie Janssenf5ec5382017-01-03 11:37:38 -08002084 }
Marie Janssen59804562016-12-28 14:13:21 -08002085 }
2086
Pavlin Radoslavov6e8faff2016-02-23 11:54:37 -08002087 if (mBluetoothBinder == null) {
2088 errorMsg = "Bluetooth Service not connected";
2089 } else {
2090 try {
2091 mBluetoothBinder.dump(fd, args);
2092 } catch (RemoteException re) {
Marie Janssen59804562016-12-28 14:13:21 -08002093 errorMsg = "RemoteException while dumping Bluetooth Service";
Pavlin Radoslavov6e8faff2016-02-23 11:54:37 -08002094 }
Mike Lockwood726d4de2014-10-28 14:06:28 -07002095 }
Pavlin Radoslavov6e8faff2016-02-23 11:54:37 -08002096 if (errorMsg != null) {
2097 // Silently return if we are extracting metrics in Protobuf format
Marie Janssen59804562016-12-28 14:13:21 -08002098 if (protoOut) return;
Pavlin Radoslavov6e8faff2016-02-23 11:54:37 -08002099 writer.println(errorMsg);
2100 }
Mike Lockwood726d4de2014-10-28 14:06:28 -07002101 }
fredc0f420372012-04-12 00:02:00 -07002102}