blob: 799a763845d24d6b534190baa28e9a0d8de8ab21 [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;
Matthew Xie32ab77b2013-05-08 19:26:57 -070038import android.content.pm.PackageManager;
Benjamin Franze8b98922014-11-12 15:57:54 +000039import android.content.pm.UserInfo;
Wei Wange4a744b2015-06-11 17:50:29 -070040import android.database.ContentObserver;
Zhihai Xu40874a02012-10-08 17:57:03 -070041import android.os.Binder;
fredc0f420372012-04-12 00:02:00 -070042import android.os.Handler;
fredc0f420372012-04-12 00:02:00 -070043import android.os.IBinder;
Zhihai Xu40874a02012-10-08 17:57:03 -070044import android.os.Looper;
fredc0f420372012-04-12 00:02:00 -070045import android.os.Message;
Zhihai Xu40874a02012-10-08 17:57:03 -070046import android.os.Process;
fredcd6883532012-04-25 17:46:13 -070047import android.os.RemoteCallbackList;
fredc0f420372012-04-12 00:02:00 -070048import android.os.RemoteException;
Zhihai Xu40874a02012-10-08 17:57:03 -070049import android.os.SystemClock;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070050import android.os.UserHandle;
Benjamin Franze8b98922014-11-12 15:57:54 +000051import android.os.UserManager;
fredc0f420372012-04-12 00:02:00 -070052import android.provider.Settings;
Wei Wang67d84162015-04-26 17:04:29 -070053import android.provider.Settings.SettingNotFoundException;
Jeff Sharkey67609c72016-03-05 14:29:13 -070054import android.util.Slog;
Mike Lockwood726d4de2014-10-28 14:06:28 -070055
56import java.io.FileDescriptor;
57import java.io.PrintWriter;
Benjamin Franze8b98922014-11-12 15:57:54 +000058import java.util.HashMap;
59import java.util.Map;
Miao Chou658bf2f2015-06-26 17:14:35 -070060
fredc0f420372012-04-12 00:02:00 -070061class BluetoothManagerService extends IBluetoothManager.Stub {
62 private static final String TAG = "BluetoothManagerService";
Pavlin Radoslavovb5a479c2015-06-20 22:55:04 -070063 private static final boolean DBG = false;
fredc0f420372012-04-12 00:02:00 -070064
fredc0f420372012-04-12 00:02:00 -070065 private static final String BLUETOOTH_ADMIN_PERM = android.Manifest.permission.BLUETOOTH_ADMIN;
66 private static final String BLUETOOTH_PERM = android.Manifest.permission.BLUETOOTH;
fredc0f420372012-04-12 00:02:00 -070067 private static final String ACTION_SERVICE_STATE_CHANGED="com.android.bluetooth.btservice.action.STATE_CHANGED";
68 private static final String EXTRA_ACTION="action";
Zhihai Xud31c3222012-10-31 16:08:57 -070069 private static final String SECURE_SETTINGS_BLUETOOTH_ADDR_VALID="bluetooth_addr_valid";
fredc0f420372012-04-12 00:02:00 -070070 private static final String SECURE_SETTINGS_BLUETOOTH_ADDRESS="bluetooth_address";
71 private static final String SECURE_SETTINGS_BLUETOOTH_NAME="bluetooth_name";
fredc0f420372012-04-12 00:02:00 -070072 private static final int TIMEOUT_BIND_MS = 3000; //Maximum msec to wait for a bind
73 private static final int TIMEOUT_SAVE_MS = 500; //Maximum msec to wait for a save
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +053074 //Maximum msec to wait for service restart
75 private static final int SERVICE_RESTART_TIME_MS = 200;
Zhihai Xudd9d17d2013-01-08 17:05:58 -080076 //Maximum msec to wait for restart due to error
77 private static final int ERROR_RESTART_TIME_MS = 3000;
Zhihai Xu40874a02012-10-08 17:57:03 -070078 //Maximum msec to delay MESSAGE_USER_SWITCHED
79 private static final int USER_SWITCHED_TIME_MS = 200;
Benjamin Franze8b98922014-11-12 15:57:54 +000080 // Delay for the addProxy function in msec
81 private static final int ADD_PROXY_DELAY_MS = 100;
fredc0f420372012-04-12 00:02:00 -070082
83 private static final int MESSAGE_ENABLE = 1;
84 private static final int MESSAGE_DISABLE = 2;
fredc649fe492012-04-19 01:07:18 -070085 private static final int MESSAGE_REGISTER_ADAPTER = 20;
86 private static final int MESSAGE_UNREGISTER_ADAPTER = 21;
87 private static final int MESSAGE_REGISTER_STATE_CHANGE_CALLBACK = 30;
88 private static final int MESSAGE_UNREGISTER_STATE_CHANGE_CALLBACK = 31;
89 private static final int MESSAGE_BLUETOOTH_SERVICE_CONNECTED = 40;
90 private static final int MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED = 41;
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +053091 private static final int MESSAGE_RESTART_BLUETOOTH_SERVICE = 42;
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -070092 private static final int MESSAGE_BLUETOOTH_STATE_CHANGE = 60;
93 private static final int MESSAGE_TIMEOUT_BIND = 100;
94 private static final int MESSAGE_TIMEOUT_UNBIND = 101;
Zhihai Xu40874a02012-10-08 17:57:03 -070095 private static final int MESSAGE_USER_SWITCHED = 300;
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -070096 private static final int MESSAGE_USER_UNLOCKED = 301;
Benjamin Franze8b98922014-11-12 15:57:54 +000097 private static final int MESSAGE_ADD_PROXY_DELAYED = 400;
98 private static final int MESSAGE_BIND_PROFILE_SERVICE = 401;
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -070099 private static final int MAX_SAVE_RETRIES = 3;
100 private static final int MAX_ERROR_RESTART_RETRIES = 6;
Zhihai Xudd9d17d2013-01-08 17:05:58 -0800101
Zhihai Xu401202b2012-12-03 11:36:21 -0800102 // Bluetooth persisted setting is off
103 private static final int BLUETOOTH_OFF=0;
104 // Bluetooth persisted setting is on
105 // and Airplane mode won't affect Bluetooth state at start up
106 private static final int BLUETOOTH_ON_BLUETOOTH=1;
107 // Bluetooth persisted setting is on
108 // but Airplane mode will affect Bluetooth state at start up
109 // and Airplane mode will have higher priority.
110 private static final int BLUETOOTH_ON_AIRPLANE=2;
fredc0f420372012-04-12 00:02:00 -0700111
Matthew Xieddf7e472013-03-01 18:41:02 -0800112 private static final int SERVICE_IBLUETOOTH = 1;
113 private static final int SERVICE_IBLUETOOTHGATT = 2;
114
fredc0f420372012-04-12 00:02:00 -0700115 private final Context mContext;
Nitin Arorad055adb2015-03-02 15:03:51 -0800116 private static int mBleAppCount = 0;
Matthew Xiecdce0b92012-07-12 19:06:15 -0700117
118 // Locks are not provided for mName and mAddress.
119 // They are accessed in handler or broadcast receiver, same thread context.
fredc0f420372012-04-12 00:02:00 -0700120 private String mAddress;
121 private String mName;
Matthew Xie6fde3092012-07-11 17:10:07 -0700122 private final ContentResolver mContentResolver;
123 private final RemoteCallbackList<IBluetoothManagerCallback> mCallbacks;
124 private final RemoteCallbackList<IBluetoothStateChangeCallback> mStateChangeCallbacks;
Marie Janssen9db28eb2016-01-12 16:05:15 -0800125 private IBinder mBluetoothBinder;
fredc649fe492012-04-19 01:07:18 -0700126 private IBluetooth mBluetooth;
Matthew Xieddf7e472013-03-01 18:41:02 -0800127 private IBluetoothGatt mBluetoothGatt;
fredc649fe492012-04-19 01:07:18 -0700128 private boolean mBinding;
129 private boolean mUnbinding;
Zhihai Xu401202b2012-12-03 11:36:21 -0800130 // used inside handler thread
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700131 private boolean mQuietEnable = false;
Zhihai Xu401202b2012-12-03 11:36:21 -0800132 // configuarion from external IBinder call which is used to
133 // synchronize with broadcast receiver.
134 private boolean mQuietEnableExternal;
135 // configuarion from external IBinder call which is used to
136 // synchronize with broadcast receiver.
137 private boolean mEnableExternal;
138 // used inside handler thread
Zhihai Xu40874a02012-10-08 17:57:03 -0700139 private boolean mEnable;
140 private int mState;
Zhihai Xu40874a02012-10-08 17:57:03 -0700141 private final BluetoothHandler mHandler;
Zhihai Xudd9d17d2013-01-08 17:05:58 -0800142 private int mErrorRecoveryRetryCounter;
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200143 private final int mSystemUiUid;
fredc0f420372012-04-12 00:02:00 -0700144
Benjamin Franze8b98922014-11-12 15:57:54 +0000145 // Save a ProfileServiceConnections object for each of the bound
146 // bluetooth profile services
147 private final Map <Integer, ProfileServiceConnections> mProfileServices =
148 new HashMap <Integer, ProfileServiceConnections>();
149
fredc649fe492012-04-19 01:07:18 -0700150 private void registerForAirplaneMode(IntentFilter filter) {
151 final ContentResolver resolver = mContext.getContentResolver();
Christopher Tatec09cdce2012-09-10 16:50:14 -0700152 final String airplaneModeRadios = Settings.Global.getString(resolver,
153 Settings.Global.AIRPLANE_MODE_RADIOS);
154 final String toggleableRadios = Settings.Global.getString(resolver,
155 Settings.Global.AIRPLANE_MODE_TOGGLEABLE_RADIOS);
fredc649fe492012-04-19 01:07:18 -0700156 boolean mIsAirplaneSensitive = airplaneModeRadios == null ? true :
Christopher Tatec09cdce2012-09-10 16:50:14 -0700157 airplaneModeRadios.contains(Settings.Global.RADIO_BLUETOOTH);
fredc649fe492012-04-19 01:07:18 -0700158 if (mIsAirplaneSensitive) {
159 filter.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED);
160 }
161 }
162
fredcbf072a72012-05-09 16:52:50 -0700163 private final IBluetoothCallback mBluetoothCallback = new IBluetoothCallback.Stub() {
164 @Override
165 public void onBluetoothStateChange(int prevState, int newState) throws RemoteException {
166 Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_STATE_CHANGE,prevState,newState);
167 mHandler.sendMessage(msg);
168 }
169 };
170
171 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
fredc0f420372012-04-12 00:02:00 -0700172 @Override
173 public void onReceive(Context context, Intent intent) {
174 String action = intent.getAction();
fredcbf072a72012-05-09 16:52:50 -0700175 if (BluetoothAdapter.ACTION_LOCAL_NAME_CHANGED.equals(action)) {
fredc0f420372012-04-12 00:02:00 -0700176 String newName = intent.getStringExtra(BluetoothAdapter.EXTRA_LOCAL_NAME);
Jeff Sharkey67609c72016-03-05 14:29:13 -0700177 if (DBG) Slog.d(TAG, "Bluetooth Adapter name changed to " + newName);
fredc0f420372012-04-12 00:02:00 -0700178 if (newName != null) {
179 storeNameAndAddress(newName, null);
180 }
fredc649fe492012-04-19 01:07:18 -0700181 } else if (Intent.ACTION_AIRPLANE_MODE_CHANGED.equals(action)) {
Zhihai Xu401202b2012-12-03 11:36:21 -0800182 synchronized(mReceiver) {
183 if (isBluetoothPersistedStateOn()) {
184 if (isAirplaneModeOn()) {
185 persistBluetoothSetting(BLUETOOTH_ON_AIRPLANE);
186 } else {
187 persistBluetoothSetting(BLUETOOTH_ON_BLUETOOTH);
188 }
189 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800190
191 int st = BluetoothAdapter.STATE_OFF;
192 if (mBluetooth != null) {
193 try {
194 st = mBluetooth.getState();
195 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700196 Slog.e(TAG,"Unable to call getState", e);
Nitin Arorad055adb2015-03-02 15:03:51 -0800197 }
198 }
Jeff Sharkey67609c72016-03-05 14:29:13 -0700199 Slog.d(TAG, "state" + st);
Nitin Arorad055adb2015-03-02 15:03:51 -0800200
Zhihai Xu401202b2012-12-03 11:36:21 -0800201 if (isAirplaneModeOn()) {
Nitin Arorad055adb2015-03-02 15:03:51 -0800202 // Clear registered LE apps to force shut-off
203 synchronized (this) {
204 mBleAppCount = 0;
Nitin Arora11f83882015-05-07 18:45:44 -0700205 mBleApps.clear();
Nitin Arorad055adb2015-03-02 15:03:51 -0800206 }
207 if (st == BluetoothAdapter.STATE_BLE_ON) {
208 //if state is BLE_ON make sure you trigger disableBLE part
209 try {
210 if (mBluetooth != null) {
211 mBluetooth.onBrEdrDown();
212 mEnableExternal = false;
213 }
214 } catch(RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700215 Slog.e(TAG,"Unable to call onBrEdrDown", e);
Nitin Arorad055adb2015-03-02 15:03:51 -0800216 }
217 } else if (st == BluetoothAdapter.STATE_ON){
218 // disable without persisting the setting
Jeff Sharkey67609c72016-03-05 14:29:13 -0700219 Slog.d(TAG, "Calling disable");
Nitin Arorad055adb2015-03-02 15:03:51 -0800220 sendDisableMsg();
221 }
Zhihai Xu401202b2012-12-03 11:36:21 -0800222 } else if (mEnableExternal) {
223 // enable without persisting the setting
Jeff Sharkey67609c72016-03-05 14:29:13 -0700224 Slog.d(TAG, "Calling enable");
Zhihai Xu401202b2012-12-03 11:36:21 -0800225 sendEnableMsg(mQuietEnableExternal);
226 }
fredc649fe492012-04-19 01:07:18 -0700227 }
fredc0f420372012-04-12 00:02:00 -0700228 }
229 }
230 };
231
232 BluetoothManagerService(Context context) {
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700233 mHandler = new BluetoothHandler(IoThread.get().getLooper());
Zhihai Xu40874a02012-10-08 17:57:03 -0700234
fredc0f420372012-04-12 00:02:00 -0700235 mContext = context;
236 mBluetooth = null;
Marie Janssen9db28eb2016-01-12 16:05:15 -0800237 mBluetoothBinder = null;
Nitin Arorad055adb2015-03-02 15:03:51 -0800238 mBluetoothGatt = null;
fredc0f420372012-04-12 00:02:00 -0700239 mBinding = false;
240 mUnbinding = false;
Zhihai Xu40874a02012-10-08 17:57:03 -0700241 mEnable = false;
242 mState = BluetoothAdapter.STATE_OFF;
Zhihai Xu401202b2012-12-03 11:36:21 -0800243 mQuietEnableExternal = false;
244 mEnableExternal = false;
fredc0f420372012-04-12 00:02:00 -0700245 mAddress = null;
246 mName = null;
Zhihai Xudd9d17d2013-01-08 17:05:58 -0800247 mErrorRecoveryRetryCounter = 0;
fredc0f420372012-04-12 00:02:00 -0700248 mContentResolver = context.getContentResolver();
Wei Wange4a744b2015-06-11 17:50:29 -0700249 // Observe BLE scan only mode settings change.
250 registerForBleScanModeChange();
fredcd6883532012-04-25 17:46:13 -0700251 mCallbacks = new RemoteCallbackList<IBluetoothManagerCallback>();
252 mStateChangeCallbacks = new RemoteCallbackList<IBluetoothStateChangeCallback>();
Miao Chou658bf2f2015-06-26 17:14:35 -0700253 IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_LOCAL_NAME_CHANGED);
Matthew Xie6fde3092012-07-11 17:10:07 -0700254 registerForAirplaneMode(filter);
Dianne Hackbornd83a0962014-05-02 16:28:33 -0700255 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
Matthew Xie6fde3092012-07-11 17:10:07 -0700256 mContext.registerReceiver(mReceiver, filter);
fredc0f420372012-04-12 00:02:00 -0700257 loadStoredNameAndAddress();
Zhihai Xu401202b2012-12-03 11:36:21 -0800258 if (isBluetoothPersistedStateOn()) {
259 mEnableExternal = true;
fredc0f420372012-04-12 00:02:00 -0700260 }
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200261
262 int sysUiUid = -1;
263 try {
Jeff Sharkeye06b4d12016-01-06 14:51:50 -0700264 sysUiUid = mContext.getPackageManager().getPackageUidAsUser("com.android.systemui",
Jeff Sharkeyc5967e92016-01-07 18:50:29 -0700265 PackageManager.MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM);
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200266 } catch (PackageManager.NameNotFoundException e) {
Joe LaPennaacddf2b2015-09-04 12:52:42 -0700267 // Some platforms, such as wearables do not have a system ui.
Jeff Sharkey67609c72016-03-05 14:29:13 -0700268 Slog.w(TAG, "Unable to resolve SystemUI's UID.", e);
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200269 }
270 mSystemUiUid = sysUiUid;
fredc0f420372012-04-12 00:02:00 -0700271 }
272
fredc649fe492012-04-19 01:07:18 -0700273 /**
274 * Returns true if airplane mode is currently on
275 */
276 private final boolean isAirplaneModeOn() {
Christopher Tatec09cdce2012-09-10 16:50:14 -0700277 return Settings.Global.getInt(mContext.getContentResolver(),
278 Settings.Global.AIRPLANE_MODE_ON, 0) == 1;
fredc649fe492012-04-19 01:07:18 -0700279 }
280
281 /**
282 * Returns true if the Bluetooth saved state is "on"
283 */
284 private final boolean isBluetoothPersistedStateOn() {
Jeff Brownbf6f6f92012-09-25 15:03:20 -0700285 return Settings.Global.getInt(mContentResolver,
Zhihai Xu401202b2012-12-03 11:36:21 -0800286 Settings.Global.BLUETOOTH_ON, 0) != BLUETOOTH_OFF;
287 }
288
289 /**
290 * Returns true if the Bluetooth saved state is BLUETOOTH_ON_BLUETOOTH
291 */
292 private final boolean isBluetoothPersistedStateOnBluetooth() {
293 return Settings.Global.getInt(mContentResolver,
294 Settings.Global.BLUETOOTH_ON, 0) == BLUETOOTH_ON_BLUETOOTH;
fredc649fe492012-04-19 01:07:18 -0700295 }
296
297 /**
298 * Save the Bluetooth on/off state
299 *
300 */
Zhihai Xu401202b2012-12-03 11:36:21 -0800301 private void persistBluetoothSetting(int value) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -0700302 Settings.Global.putInt(mContext.getContentResolver(),
303 Settings.Global.BLUETOOTH_ON,
Zhihai Xu401202b2012-12-03 11:36:21 -0800304 value);
fredc649fe492012-04-19 01:07:18 -0700305 }
306
307 /**
308 * Returns true if the Bluetooth Adapter's name and address is
309 * locally cached
310 * @return
311 */
fredc0f420372012-04-12 00:02:00 -0700312 private boolean isNameAndAddressSet() {
313 return mName !=null && mAddress!= null && mName.length()>0 && mAddress.length()>0;
314 }
315
fredc649fe492012-04-19 01:07:18 -0700316 /**
317 * Retrieve the Bluetooth Adapter's name and address and save it in
318 * in the local cache
319 */
fredc0f420372012-04-12 00:02:00 -0700320 private void loadStoredNameAndAddress() {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700321 if (DBG) Slog.d(TAG, "Loading stored name and address");
Zhihai Xud31c3222012-10-31 16:08:57 -0700322 if (mContext.getResources().getBoolean
323 (com.android.internal.R.bool.config_bluetooth_address_validation) &&
324 Settings.Secure.getInt(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDR_VALID, 0) == 0) {
325 // if the valid flag is not set, don't load the address and name
Jeff Sharkey67609c72016-03-05 14:29:13 -0700326 if (DBG) Slog.d(TAG, "invalid bluetooth name and address stored");
Zhihai Xud31c3222012-10-31 16:08:57 -0700327 return;
328 }
fredc0f420372012-04-12 00:02:00 -0700329 mName = Settings.Secure.getString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_NAME);
330 mAddress = Settings.Secure.getString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDRESS);
Jeff Sharkey67609c72016-03-05 14:29:13 -0700331 if (DBG) Slog.d(TAG, "Stored bluetooth Name=" + mName + ",Address=" + mAddress);
fredc0f420372012-04-12 00:02:00 -0700332 }
333
fredc649fe492012-04-19 01:07:18 -0700334 /**
335 * Save the Bluetooth name and address in the persistent store.
336 * Only non-null values will be saved.
337 * @param name
338 * @param address
339 */
fredc0f420372012-04-12 00:02:00 -0700340 private void storeNameAndAddress(String name, String address) {
341 if (name != null) {
342 Settings.Secure.putString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_NAME, name);
fredc0f420372012-04-12 00:02:00 -0700343 mName = name;
Jeff Sharkey67609c72016-03-05 14:29:13 -0700344 if (DBG) Slog.d(TAG,"Stored Bluetooth name: " +
fredc649fe492012-04-19 01:07:18 -0700345 Settings.Secure.getString(mContentResolver,SECURE_SETTINGS_BLUETOOTH_NAME));
fredc0f420372012-04-12 00:02:00 -0700346 }
347
348 if (address != null) {
349 Settings.Secure.putString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDRESS, address);
fredc0f420372012-04-12 00:02:00 -0700350 mAddress=address;
Jeff Sharkey67609c72016-03-05 14:29:13 -0700351 if (DBG) Slog.d(TAG,"Stored Bluetoothaddress: " +
fredc649fe492012-04-19 01:07:18 -0700352 Settings.Secure.getString(mContentResolver,SECURE_SETTINGS_BLUETOOTH_ADDRESS));
fredc0f420372012-04-12 00:02:00 -0700353 }
Zhihai Xud31c3222012-10-31 16:08:57 -0700354
355 if ((name != null) && (address != null)) {
356 Settings.Secure.putInt(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDR_VALID, 1);
357 }
fredc0f420372012-04-12 00:02:00 -0700358 }
359
360 public IBluetooth registerAdapter(IBluetoothManagerCallback callback){
Natalie Silvanovich55db6462014-05-01 16:12:23 -0700361 if (callback == null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700362 Slog.w(TAG, "Callback is null in registerAdapter");
Natalie Silvanovich55db6462014-05-01 16:12:23 -0700363 return null;
364 }
fredc0f420372012-04-12 00:02:00 -0700365 Message msg = mHandler.obtainMessage(MESSAGE_REGISTER_ADAPTER);
366 msg.obj = callback;
367 mHandler.sendMessage(msg);
368 synchronized(mConnection) {
369 return mBluetooth;
370 }
371 }
372
373 public void unregisterAdapter(IBluetoothManagerCallback callback) {
Natalie Silvanovich55db6462014-05-01 16:12:23 -0700374 if (callback == null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700375 Slog.w(TAG, "Callback is null in unregisterAdapter");
Natalie Silvanovich55db6462014-05-01 16:12:23 -0700376 return;
377 }
fredc0f420372012-04-12 00:02:00 -0700378 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
379 "Need BLUETOOTH permission");
380 Message msg = mHandler.obtainMessage(MESSAGE_UNREGISTER_ADAPTER);
381 msg.obj = callback;
382 mHandler.sendMessage(msg);
383 }
384
385 public void registerStateChangeCallback(IBluetoothStateChangeCallback callback) {
386 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
387 "Need BLUETOOTH permission");
388 Message msg = mHandler.obtainMessage(MESSAGE_REGISTER_STATE_CHANGE_CALLBACK);
389 msg.obj = callback;
390 mHandler.sendMessage(msg);
391 }
392
393 public void unregisterStateChangeCallback(IBluetoothStateChangeCallback callback) {
394 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
395 "Need BLUETOOTH permission");
396 Message msg = mHandler.obtainMessage(MESSAGE_UNREGISTER_STATE_CHANGE_CALLBACK);
397 msg.obj = callback;
398 mHandler.sendMessage(msg);
399 }
400
401 public boolean isEnabled() {
Zhihai Xu6eb76522012-11-29 15:41:04 -0800402 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
403 (!checkIfCallerIsForegroundUser())) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700404 Slog.w(TAG,"isEnabled(): not allowed for non-active and non system user");
Zhihai Xu40874a02012-10-08 17:57:03 -0700405 return false;
406 }
407
fredc0f420372012-04-12 00:02:00 -0700408 synchronized(mConnection) {
409 try {
410 return (mBluetooth != null && mBluetooth.isEnabled());
411 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700412 Slog.e(TAG, "isEnabled()", e);
fredc0f420372012-04-12 00:02:00 -0700413 }
414 }
415 return false;
416 }
417
Nitin Arorad055adb2015-03-02 15:03:51 -0800418 class ClientDeathRecipient implements IBinder.DeathRecipient {
419 public void binderDied() {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700420 if (DBG) Slog.d(TAG, "Binder is dead - unregister Ble App");
Nitin Arorad055adb2015-03-02 15:03:51 -0800421 if (mBleAppCount > 0) --mBleAppCount;
422
423 if (mBleAppCount == 0) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700424 if (DBG) Slog.d(TAG, "Disabling LE only mode after application crash");
Nitin Arorad055adb2015-03-02 15:03:51 -0800425 try {
426 if (mBluetooth != null) {
427 mBluetooth.onBrEdrDown();
428 }
429 } catch(RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700430 Slog.e(TAG,"Unable to call onBrEdrDown", e);
Nitin Arorad055adb2015-03-02 15:03:51 -0800431 }
432 }
433 }
434 }
435
436 /** Internal death rec list */
437 Map<IBinder, ClientDeathRecipient> mBleApps = new HashMap<IBinder, ClientDeathRecipient>();
438
Wei Wang67d84162015-04-26 17:04:29 -0700439 @Override
440 public boolean isBleScanAlwaysAvailable() {
441 try {
442 return (Settings.Global.getInt(mContentResolver,
443 Settings.Global.BLE_SCAN_ALWAYS_AVAILABLE)) != 0;
444 } catch (SettingNotFoundException e) {
445 }
446 return false;
447 }
448
Wei Wange4a744b2015-06-11 17:50:29 -0700449 // Monitor change of BLE scan only mode settings.
450 private void registerForBleScanModeChange() {
451 ContentObserver contentObserver = new ContentObserver(null) {
452 @Override
453 public void onChange(boolean selfChange) {
454 if (!isBleScanAlwaysAvailable()) {
455 disableBleScanMode();
456 clearBleApps();
457 try {
458 if (mBluetooth != null) mBluetooth.onBrEdrDown();
459 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700460 Slog.e(TAG, "error when disabling bluetooth", e);
Wei Wange4a744b2015-06-11 17:50:29 -0700461 }
462 }
463 }
464 };
465
466 mContentResolver.registerContentObserver(
467 Settings.Global.getUriFor(Settings.Global.BLE_SCAN_ALWAYS_AVAILABLE),
468 false, contentObserver);
469 }
470
471 // Disable ble scan only mode.
472 private void disableBleScanMode() {
473 try {
474 if (mBluetooth != null && (mBluetooth.getState() != BluetoothAdapter.STATE_ON)) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700475 if (DBG) Slog.d(TAG, "Reseting the mEnable flag for clean disable");
Wei Wange4a744b2015-06-11 17:50:29 -0700476 mEnable = false;
477 }
478 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700479 Slog.e(TAG, "getState()", e);
Wei Wange4a744b2015-06-11 17:50:29 -0700480 }
481 }
482
Nitin Arorad055adb2015-03-02 15:03:51 -0800483 public int updateBleAppCount(IBinder token, boolean enable) {
484 if (enable) {
485 ClientDeathRecipient r = mBleApps.get(token);
486 if (r == null) {
487 ClientDeathRecipient deathRec = new ClientDeathRecipient();
488 try {
489 token.linkToDeath(deathRec, 0);
490 } catch (RemoteException ex) {
491 throw new IllegalArgumentException("Wake lock is already dead.");
492 }
493 mBleApps.put(token, deathRec);
494 synchronized (this) {
495 ++mBleAppCount;
496 }
Jeff Sharkey67609c72016-03-05 14:29:13 -0700497 if (DBG) Slog.d(TAG, "Registered for death Notification");
Nitin Arorad055adb2015-03-02 15:03:51 -0800498 }
499
500 } else {
501 ClientDeathRecipient r = mBleApps.get(token);
502 if (r != null) {
Wei Wange4a744b2015-06-11 17:50:29 -0700503 // Unregister death recipient as the app goes away.
504 token.unlinkToDeath(r, 0);
Nitin Arorad055adb2015-03-02 15:03:51 -0800505 mBleApps.remove(token);
506 synchronized (this) {
507 if (mBleAppCount > 0) --mBleAppCount;
508 }
Jeff Sharkey67609c72016-03-05 14:29:13 -0700509 if (DBG) Slog.d(TAG, "Unregistered for death Notification");
Nitin Arorad055adb2015-03-02 15:03:51 -0800510 }
511 }
Jeff Sharkey67609c72016-03-05 14:29:13 -0700512 if (DBG) Slog.d(TAG, "Updated BleAppCount" + mBleAppCount);
Nitin Arorad055adb2015-03-02 15:03:51 -0800513 if (mBleAppCount == 0 && mEnable) {
Wei Wange4a744b2015-06-11 17:50:29 -0700514 disableBleScanMode();
Nitin Arorad055adb2015-03-02 15:03:51 -0800515 }
516 return mBleAppCount;
517 }
518
Wei Wange4a744b2015-06-11 17:50:29 -0700519 // Clear all apps using BLE scan only mode.
520 private void clearBleApps() {
521 synchronized (this) {
522 mBleApps.clear();
523 mBleAppCount = 0;
524 }
525 }
526
Nitin Arorad055adb2015-03-02 15:03:51 -0800527 /** @hide*/
528 public boolean isBleAppPresent() {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700529 if (DBG) Slog.d(TAG, "isBleAppPresent() count: " + mBleAppCount);
Nitin Arorad055adb2015-03-02 15:03:51 -0800530 return (mBleAppCount > 0);
531 }
532
533 /**
534 * Action taken when GattService is turned off
535 */
536 private void onBluetoothGattServiceUp() {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700537 if (DBG) Slog.d(TAG,"BluetoothGatt Service is Up");
Nitin Arorad055adb2015-03-02 15:03:51 -0800538 try{
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700539 if (isBleAppPresent() == false && mBluetooth != null
540 && mBluetooth.getState() == BluetoothAdapter.STATE_BLE_ON) {
Nitin Arorad055adb2015-03-02 15:03:51 -0800541 mBluetooth.onLeServiceUp();
542
543 // waive WRITE_SECURE_SETTINGS permission check
544 long callingIdentity = Binder.clearCallingIdentity();
545 persistBluetoothSetting(BLUETOOTH_ON_BLUETOOTH);
546 Binder.restoreCallingIdentity(callingIdentity);
547 }
548 } catch(RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700549 Slog.e(TAG,"Unable to call onServiceUp", e);
Nitin Arorad055adb2015-03-02 15:03:51 -0800550 }
551 }
552
553 /**
554 * Inform BluetoothAdapter instances that BREDR part is down
555 * and turn off all service and stack if no LE app needs it
556 */
557 private void sendBrEdrDownCallback() {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700558 if (DBG) Slog.d(TAG,"Calling sendBrEdrDownCallback callbacks");
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700559
560 if(mBluetooth == null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700561 Slog.w(TAG, "Bluetooth handle is null");
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700562 return;
563 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800564
565 if (isBleAppPresent() == false) {
566 try {
567 mBluetooth.onBrEdrDown();
568 } catch(RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700569 Slog.e(TAG, "Call to onBrEdrDown() failed.", e);
Nitin Arorad055adb2015-03-02 15:03:51 -0800570 }
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700571 } else {
572 // Need to stay at BLE ON. Disconnect all Gatt connections
Nitin Arorad055adb2015-03-02 15:03:51 -0800573 try{
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700574 mBluetoothGatt.unregAll();
Nitin Arorad055adb2015-03-02 15:03:51 -0800575 } catch(RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700576 Slog.e(TAG, "Unable to disconnect all apps.", e);
Nitin Arorad055adb2015-03-02 15:03:51 -0800577 }
578 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800579 }
580
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700581 public boolean enableNoAutoConnect()
582 {
583 mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
584 "Need BLUETOOTH ADMIN permission");
Zhihai Xu40874a02012-10-08 17:57:03 -0700585
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700586 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700587 Slog.d(TAG,"enableNoAutoConnect(): mBluetooth =" + mBluetooth +
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700588 " mBinding = " + mBinding);
589 }
Martijn Coenen8385c5a2012-11-29 10:14:16 -0800590 int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
591
592 if (callingAppId != Process.NFC_UID) {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700593 throw new SecurityException("no permission to enable Bluetooth quietly");
594 }
Martijn Coenen8385c5a2012-11-29 10:14:16 -0800595
Zhihai Xu401202b2012-12-03 11:36:21 -0800596 synchronized(mReceiver) {
597 mQuietEnableExternal = true;
598 mEnableExternal = true;
599 sendEnableMsg(true);
600 }
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700601 return true;
602
603 }
fredc0f420372012-04-12 00:02:00 -0700604 public boolean enable() {
Zhihai Xu6eb76522012-11-29 15:41:04 -0800605 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
606 (!checkIfCallerIsForegroundUser())) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700607 Slog.w(TAG,"enable(): not allowed for non-active and non system user");
Zhihai Xu40874a02012-10-08 17:57:03 -0700608 return false;
fredcf2458862012-04-16 15:18:27 -0700609 }
610
Zhihai Xu401202b2012-12-03 11:36:21 -0800611 mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
612 "Need BLUETOOTH ADMIN permission");
613 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700614 Slog.d(TAG,"enable(): mBluetooth =" + mBluetooth +
Zhihai Xu401202b2012-12-03 11:36:21 -0800615 " mBinding = " + mBinding);
616 }
617
618 synchronized(mReceiver) {
619 mQuietEnableExternal = false;
620 mEnableExternal = true;
621 // waive WRITE_SECURE_SETTINGS permission check
Zhihai Xu401202b2012-12-03 11:36:21 -0800622 sendEnableMsg(false);
623 }
Jeff Sharkey67609c72016-03-05 14:29:13 -0700624 if (DBG) Slog.d(TAG, "enable returning");
Zhihai Xu401202b2012-12-03 11:36:21 -0800625 return true;
fredc0f420372012-04-12 00:02:00 -0700626 }
627
628 public boolean disable(boolean persist) {
629 mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
630 "Need BLUETOOTH ADMIN permissicacheNameAndAddresson");
Zhihai Xu40874a02012-10-08 17:57:03 -0700631
Zhihai Xu6eb76522012-11-29 15:41:04 -0800632 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
633 (!checkIfCallerIsForegroundUser())) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700634 Slog.w(TAG,"disable(): not allowed for non-active and non system user");
Zhihai Xu40874a02012-10-08 17:57:03 -0700635 return false;
636 }
637
fredcf2458862012-04-16 15:18:27 -0700638 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700639 Slog.d(TAG,"disable(): mBluetooth = " + mBluetooth +
Matthew Xiecdce0b92012-07-12 19:06:15 -0700640 " mBinding = " + mBinding);
641 }
fredcf2458862012-04-16 15:18:27 -0700642
Zhihai Xu401202b2012-12-03 11:36:21 -0800643 synchronized(mReceiver) {
644 if (persist) {
645 // waive WRITE_SECURE_SETTINGS permission check
646 long callingIdentity = Binder.clearCallingIdentity();
647 persistBluetoothSetting(BLUETOOTH_OFF);
648 Binder.restoreCallingIdentity(callingIdentity);
649 }
650 mEnableExternal = false;
651 sendDisableMsg();
652 }
fredc0f420372012-04-12 00:02:00 -0700653 return true;
654 }
655
fredc649fe492012-04-19 01:07:18 -0700656 public void unbindAndFinish() {
fredcf2458862012-04-16 15:18:27 -0700657 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700658 Slog.d(TAG,"unbindAndFinish(): " + mBluetooth +
Matthew Xiecdce0b92012-07-12 19:06:15 -0700659 " mBinding = " + mBinding);
fredcf2458862012-04-16 15:18:27 -0700660 }
661
fredc0f420372012-04-12 00:02:00 -0700662 synchronized (mConnection) {
663 if (mUnbinding) return;
664 mUnbinding = true;
Zhihai Xu40874a02012-10-08 17:57:03 -0700665 if (mBluetooth != null) {
Andre Eisenbach305fdab2015-11-11 21:43:26 -0800666 //Unregister callback object
667 try {
668 mBluetooth.unregisterCallback(mBluetoothCallback);
669 } catch (RemoteException re) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700670 Slog.e(TAG, "Unable to unregister BluetoothCallback",re);
fredcbf072a72012-05-09 16:52:50 -0700671 }
Andre Eisenbach305fdab2015-11-11 21:43:26 -0800672
Jeff Sharkey67609c72016-03-05 14:29:13 -0700673 if (DBG) Slog.d(TAG, "Sending unbind request.");
Marie Janssen9db28eb2016-01-12 16:05:15 -0800674 mBluetoothBinder = null;
fredcd6883532012-04-25 17:46:13 -0700675 mBluetooth = null;
676 //Unbind
fredc0f420372012-04-12 00:02:00 -0700677 mContext.unbindService(mConnection);
fredcd6883532012-04-25 17:46:13 -0700678 mUnbinding = false;
Zhihai Xu40874a02012-10-08 17:57:03 -0700679 mBinding = false;
fredcf2458862012-04-16 15:18:27 -0700680 } else {
681 mUnbinding=false;
fredc0f420372012-04-12 00:02:00 -0700682 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800683 mBluetoothGatt = null;
fredc0f420372012-04-12 00:02:00 -0700684 }
685 }
686
Matthew Xieddf7e472013-03-01 18:41:02 -0800687 public IBluetoothGatt getBluetoothGatt() {
688 // sync protection
689 return mBluetoothGatt;
690 }
691
Benjamin Franze8b98922014-11-12 15:57:54 +0000692 @Override
693 public boolean bindBluetoothProfileService(int bluetoothProfile,
694 IBluetoothProfileServiceConnection proxy) {
695 if (!mEnable) {
696 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700697 Slog.d(TAG, "Trying to bind to profile: " + bluetoothProfile +
Benjamin Franze8b98922014-11-12 15:57:54 +0000698 ", while Bluetooth was disabled");
699 }
700 return false;
701 }
702 synchronized (mProfileServices) {
703 ProfileServiceConnections psc = mProfileServices.get(new Integer(bluetoothProfile));
704 if (psc == null) {
705 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700706 Slog.d(TAG, "Creating new ProfileServiceConnections object for"
Benjamin Franze8b98922014-11-12 15:57:54 +0000707 + " profile: " + bluetoothProfile);
708 }
Benjamin Franz5b614592014-12-09 18:58:45 +0000709
710 if (bluetoothProfile != BluetoothProfile.HEADSET) return false;
711
712 Intent intent = new Intent(IBluetoothHeadset.class.getName());
Benjamin Franze8b98922014-11-12 15:57:54 +0000713 psc = new ProfileServiceConnections(intent);
Benjamin Franz5b614592014-12-09 18:58:45 +0000714 if (!psc.bindService()) return false;
715
Benjamin Franze8b98922014-11-12 15:57:54 +0000716 mProfileServices.put(new Integer(bluetoothProfile), psc);
Benjamin Franze8b98922014-11-12 15:57:54 +0000717 }
718 }
719
720 // Introducing a delay to give the client app time to prepare
721 Message addProxyMsg = mHandler.obtainMessage(MESSAGE_ADD_PROXY_DELAYED);
722 addProxyMsg.arg1 = bluetoothProfile;
723 addProxyMsg.obj = proxy;
724 mHandler.sendMessageDelayed(addProxyMsg, ADD_PROXY_DELAY_MS);
725 return true;
726 }
727
728 @Override
729 public void unbindBluetoothProfileService(int bluetoothProfile,
730 IBluetoothProfileServiceConnection proxy) {
731 synchronized (mProfileServices) {
732 ProfileServiceConnections psc = mProfileServices.get(new Integer(bluetoothProfile));
733 if (psc == null) {
734 return;
735 }
736 psc.removeProxy(proxy);
737 }
738 }
739
740 private void unbindAllBluetoothProfileServices() {
741 synchronized (mProfileServices) {
742 for (Integer i : mProfileServices.keySet()) {
743 ProfileServiceConnections psc = mProfileServices.get(i);
Benjamin Franz5b614592014-12-09 18:58:45 +0000744 try {
745 mContext.unbindService(psc);
746 } catch (IllegalArgumentException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700747 Slog.e(TAG, "Unable to unbind service with intent: " + psc.mIntent, e);
Benjamin Franz5b614592014-12-09 18:58:45 +0000748 }
Benjamin Franze8b98922014-11-12 15:57:54 +0000749 psc.removeAllProxies();
750 }
751 mProfileServices.clear();
752 }
753 }
754
755 /**
Miao Chou658bf2f2015-06-26 17:14:35 -0700756 * Send enable message and set adapter name and address. Called when the boot phase becomes
757 * PHASE_SYSTEM_SERVICES_READY.
758 */
759 public void handleOnBootPhase() {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700760 if (DBG) Slog.d(TAG, "Bluetooth boot completed");
Miao Chou658bf2f2015-06-26 17:14:35 -0700761 if (mEnableExternal && isBluetoothPersistedStateOnBluetooth()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700762 if (DBG) Slog.d(TAG, "Auto-enabling Bluetooth.");
Miao Chou658bf2f2015-06-26 17:14:35 -0700763 sendEnableMsg(mQuietEnableExternal);
Ajay Panickerbf796d82016-03-11 13:47:20 -0800764 } else if (!isNameAndAddressSet()) {
765 if (DBG) Slog.d(TAG, "Getting adapter name and address");
766 enable();
767 waitForOnOff(true, false);
768 disable(true);
Miao Chou658bf2f2015-06-26 17:14:35 -0700769 }
Miao Chou658bf2f2015-06-26 17:14:35 -0700770 }
771
772 /**
773 * Called when switching to a different foreground user.
774 */
775 public void handleOnSwitchUser(int userHandle) {
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -0700776 if (DBG) Slog.d(TAG, "User " + userHandle + " switched");
777 mHandler.obtainMessage(MESSAGE_USER_SWITCHED, userHandle, 0).sendToTarget();
778 }
779
780 /**
781 * Called when user is unlocked.
782 */
783 public void handleOnUnlockUser(int userHandle) {
784 if (DBG) Slog.d(TAG, "User " + userHandle + " unlocked");
785 mHandler.obtainMessage(MESSAGE_USER_UNLOCKED, userHandle, 0).sendToTarget();
Miao Chou658bf2f2015-06-26 17:14:35 -0700786 }
787
788 /**
Benjamin Franze8b98922014-11-12 15:57:54 +0000789 * This class manages the clients connected to a given ProfileService
790 * and maintains the connection with that service.
791 */
792 final private class ProfileServiceConnections implements ServiceConnection,
793 IBinder.DeathRecipient {
794 final RemoteCallbackList<IBluetoothProfileServiceConnection> mProxies =
795 new RemoteCallbackList <IBluetoothProfileServiceConnection>();
796 IBinder mService;
797 ComponentName mClassName;
798 Intent mIntent;
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700799 boolean mInvokingProxyCallbacks = false;
Benjamin Franze8b98922014-11-12 15:57:54 +0000800
801 ProfileServiceConnections(Intent intent) {
802 mService = null;
803 mClassName = null;
804 mIntent = intent;
805 }
806
Benjamin Franz5b614592014-12-09 18:58:45 +0000807 private boolean bindService() {
808 if (mIntent != null && mService == null &&
809 doBind(mIntent, this, 0, UserHandle.CURRENT_OR_SELF)) {
Benjamin Franze8b98922014-11-12 15:57:54 +0000810 Message msg = mHandler.obtainMessage(MESSAGE_BIND_PROFILE_SERVICE);
811 msg.obj = this;
812 mHandler.sendMessageDelayed(msg, TIMEOUT_BIND_MS);
Benjamin Franz5b614592014-12-09 18:58:45 +0000813 return true;
Benjamin Franze8b98922014-11-12 15:57:54 +0000814 }
Jeff Sharkey67609c72016-03-05 14:29:13 -0700815 Slog.w(TAG, "Unable to bind with intent: " + mIntent);
Benjamin Franz5b614592014-12-09 18:58:45 +0000816 return false;
Benjamin Franze8b98922014-11-12 15:57:54 +0000817 }
818
819 private void addProxy(IBluetoothProfileServiceConnection proxy) {
820 mProxies.register(proxy);
821 if (mService != null) {
822 try{
823 proxy.onServiceConnected(mClassName, mService);
824 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700825 Slog.e(TAG, "Unable to connect to proxy", e);
Benjamin Franze8b98922014-11-12 15:57:54 +0000826 }
827 } else {
828 if (!mHandler.hasMessages(MESSAGE_BIND_PROFILE_SERVICE, this)) {
829 Message msg = mHandler.obtainMessage(MESSAGE_BIND_PROFILE_SERVICE);
830 msg.obj = this;
831 mHandler.sendMessage(msg);
832 }
833 }
834 }
835
836 private void removeProxy(IBluetoothProfileServiceConnection proxy) {
837 if (proxy != null) {
838 if (mProxies.unregister(proxy)) {
839 try {
840 proxy.onServiceDisconnected(mClassName);
841 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700842 Slog.e(TAG, "Unable to disconnect proxy", e);
Benjamin Franze8b98922014-11-12 15:57:54 +0000843 }
844 }
845 } else {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700846 Slog.w(TAG, "Trying to remove a null proxy");
Benjamin Franze8b98922014-11-12 15:57:54 +0000847 }
848 }
849
850 private void removeAllProxies() {
851 onServiceDisconnected(mClassName);
852 mProxies.kill();
853 }
854
855 @Override
856 public void onServiceConnected(ComponentName className, IBinder service) {
857 // remove timeout message
858 mHandler.removeMessages(MESSAGE_BIND_PROFILE_SERVICE, this);
859 mService = service;
860 mClassName = className;
861 try {
862 mService.linkToDeath(this, 0);
863 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700864 Slog.e(TAG, "Unable to linkToDeath", e);
Benjamin Franze8b98922014-11-12 15:57:54 +0000865 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700866
867 if (mInvokingProxyCallbacks) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700868 Slog.e(TAG, "Proxy callbacks already in progress.");
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700869 return;
Benjamin Franze8b98922014-11-12 15:57:54 +0000870 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700871 mInvokingProxyCallbacks = true;
872
873 final int n = mProxies.beginBroadcast();
874 try {
875 for (int i = 0; i < n; i++) {
876 try {
877 mProxies.getBroadcastItem(i).onServiceConnected(className, service);
878 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700879 Slog.e(TAG, "Unable to connect to proxy", e);
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700880 }
881 }
882 } finally {
883 mProxies.finishBroadcast();
884 mInvokingProxyCallbacks = false;
885 }
Benjamin Franze8b98922014-11-12 15:57:54 +0000886 }
887
888 @Override
889 public void onServiceDisconnected(ComponentName className) {
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700890 if (mService == null) return;
Benjamin Franze8b98922014-11-12 15:57:54 +0000891 mService.unlinkToDeath(this, 0);
892 mService = null;
893 mClassName = null;
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700894
895 if (mInvokingProxyCallbacks) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700896 Slog.e(TAG, "Proxy callbacks already in progress.");
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700897 return;
Benjamin Franze8b98922014-11-12 15:57:54 +0000898 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700899 mInvokingProxyCallbacks = true;
900
901 final int n = mProxies.beginBroadcast();
902 try {
903 for (int i = 0; i < n; i++) {
904 try {
905 mProxies.getBroadcastItem(i).onServiceDisconnected(className);
906 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700907 Slog.e(TAG, "Unable to disconnect from proxy", e);
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700908 }
909 }
910 } finally {
911 mProxies.finishBroadcast();
912 mInvokingProxyCallbacks = false;
913 }
Benjamin Franze8b98922014-11-12 15:57:54 +0000914 }
915
916 @Override
917 public void binderDied() {
918 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700919 Slog.w(TAG, "Profile service for profile: " + mClassName
Benjamin Franze8b98922014-11-12 15:57:54 +0000920 + " died.");
921 }
922 onServiceDisconnected(mClassName);
923 // Trigger rebind
924 Message msg = mHandler.obtainMessage(MESSAGE_BIND_PROFILE_SERVICE);
925 msg.obj = this;
926 mHandler.sendMessageDelayed(msg, TIMEOUT_BIND_MS);
927 }
928 }
929
fredcbf072a72012-05-09 16:52:50 -0700930 private void sendBluetoothStateCallback(boolean isUp) {
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700931 try {
932 int n = mStateChangeCallbacks.beginBroadcast();
Jeff Sharkey67609c72016-03-05 14:29:13 -0700933 if (DBG) Slog.d(TAG,"Broadcasting onBluetoothStateChange("+isUp+") to " + n + " receivers.");
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700934 for (int i=0; i <n;i++) {
935 try {
936 mStateChangeCallbacks.getBroadcastItem(i).onBluetoothStateChange(isUp);
937 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700938 Slog.e(TAG, "Unable to call onBluetoothStateChange() on callback #" + i , e);
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700939 }
fredcbf072a72012-05-09 16:52:50 -0700940 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700941 } finally {
942 mStateChangeCallbacks.finishBroadcast();
fredcbf072a72012-05-09 16:52:50 -0700943 }
fredcbf072a72012-05-09 16:52:50 -0700944 }
945
946 /**
Zhihai Xu40874a02012-10-08 17:57:03 -0700947 * Inform BluetoothAdapter instances that Adapter service is up
948 */
949 private void sendBluetoothServiceUpCallback() {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700950 if (DBG) Slog.d(TAG,"Calling onBluetoothServiceUp callbacks");
Andre Eisenbach305fdab2015-11-11 21:43:26 -0800951 try {
952 int n = mCallbacks.beginBroadcast();
Jeff Sharkey67609c72016-03-05 14:29:13 -0700953 Slog.d(TAG,"Broadcasting onBluetoothServiceUp() to " + n + " receivers.");
Andre Eisenbach305fdab2015-11-11 21:43:26 -0800954 for (int i=0; i <n;i++) {
955 try {
956 mCallbacks.getBroadcastItem(i).onBluetoothServiceUp(mBluetooth);
957 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700958 Slog.e(TAG, "Unable to call onBluetoothServiceUp() on callback #" + i, e);
Zhihai Xu40874a02012-10-08 17:57:03 -0700959 }
960 }
Andre Eisenbach305fdab2015-11-11 21:43:26 -0800961 } finally {
962 mCallbacks.finishBroadcast();
Zhihai Xu40874a02012-10-08 17:57:03 -0700963 }
964 }
965 /**
fredcbf072a72012-05-09 16:52:50 -0700966 * Inform BluetoothAdapter instances that Adapter service is down
967 */
968 private void sendBluetoothServiceDownCallback() {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700969 if (DBG) Slog.d(TAG,"Calling onBluetoothServiceDown callbacks");
Andre Eisenbach305fdab2015-11-11 21:43:26 -0800970 try {
971 int n = mCallbacks.beginBroadcast();
Jeff Sharkey67609c72016-03-05 14:29:13 -0700972 Slog.d(TAG,"Broadcasting onBluetoothServiceDown() to " + n + " receivers.");
Andre Eisenbach305fdab2015-11-11 21:43:26 -0800973 for (int i=0; i <n;i++) {
974 try {
975 mCallbacks.getBroadcastItem(i).onBluetoothServiceDown();
976 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700977 Slog.e(TAG, "Unable to call onBluetoothServiceDown() on callback #" + i, e);
fredcd6883532012-04-25 17:46:13 -0700978 }
979 }
Andre Eisenbach305fdab2015-11-11 21:43:26 -0800980 } finally {
981 mCallbacks.finishBroadcast();
fredcd6883532012-04-25 17:46:13 -0700982 }
983 }
Svet Ganov408abf72015-05-12 19:13:36 -0700984
fredc0f420372012-04-12 00:02:00 -0700985 public String getAddress() {
Matthew Xieaf5ddbf2012-12-04 10:47:43 -0800986 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
Svet Ganov408abf72015-05-12 19:13:36 -0700987 "Need BLUETOOTH permission");
Zhihai Xu40874a02012-10-08 17:57:03 -0700988
Zhihai Xu6eb76522012-11-29 15:41:04 -0800989 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
Svet Ganov408abf72015-05-12 19:13:36 -0700990 (!checkIfCallerIsForegroundUser())) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700991 Slog.w(TAG,"getAddress(): not allowed for non-active and non system user");
Zhihai Xu6eb76522012-11-29 15:41:04 -0800992 return null;
Zhihai Xu40874a02012-10-08 17:57:03 -0700993 }
994
Svet Ganov408abf72015-05-12 19:13:36 -0700995 if (mContext.checkCallingOrSelfPermission(Manifest.permission.LOCAL_MAC_ADDRESS)
996 != PackageManager.PERMISSION_GRANTED) {
997 return BluetoothAdapter.DEFAULT_MAC_ADDRESS;
998 }
999
fredc116d1d462012-04-20 14:47:08 -07001000 synchronized(mConnection) {
1001 if (mBluetooth != null) {
1002 try {
1003 return mBluetooth.getAddress();
1004 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001005 Slog.e(TAG, "getAddress(): Unable to retrieve address remotely..Returning cached address",e);
fredc116d1d462012-04-20 14:47:08 -07001006 }
1007 }
1008 }
Ajay Panickerbf796d82016-03-11 13:47:20 -08001009
Matthew Xiecdce0b92012-07-12 19:06:15 -07001010 // mAddress is accessed from outside.
1011 // It is alright without a lock. Here, bluetooth is off, no other thread is
1012 // changing mAddress
fredc0f420372012-04-12 00:02:00 -07001013 return mAddress;
1014 }
fredc649fe492012-04-19 01:07:18 -07001015
fredc0f420372012-04-12 00:02:00 -07001016 public String getName() {
Matthew Xieaf5ddbf2012-12-04 10:47:43 -08001017 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
1018 "Need BLUETOOTH permission");
Zhihai Xu40874a02012-10-08 17:57:03 -07001019
Zhihai Xu6eb76522012-11-29 15:41:04 -08001020 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
1021 (!checkIfCallerIsForegroundUser())) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001022 Slog.w(TAG,"getName(): not allowed for non-active and non system user");
Zhihai Xu6eb76522012-11-29 15:41:04 -08001023 return null;
Zhihai Xu40874a02012-10-08 17:57:03 -07001024 }
1025
fredc116d1d462012-04-20 14:47:08 -07001026 synchronized(mConnection) {
1027 if (mBluetooth != null) {
1028 try {
1029 return mBluetooth.getName();
1030 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001031 Slog.e(TAG, "getName(): Unable to retrieve name remotely..Returning cached name",e);
fredc116d1d462012-04-20 14:47:08 -07001032 }
1033 }
1034 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001035 // mName is accessed from outside.
1036 // It alright without a lock. Here, bluetooth is off, no other thread is
1037 // changing mName
fredc0f420372012-04-12 00:02:00 -07001038 return mName;
1039 }
1040
fredc0f420372012-04-12 00:02:00 -07001041 private class BluetoothServiceConnection implements ServiceConnection {
fredc0f420372012-04-12 00:02:00 -07001042 public void onServiceConnected(ComponentName className, IBinder service) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001043 if (DBG) Slog.d(TAG, "BluetoothServiceConnection: " + className.getClassName());
fredc0f420372012-04-12 00:02:00 -07001044 Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_SERVICE_CONNECTED);
Matthew Xieddf7e472013-03-01 18:41:02 -08001045 // TBD if (className.getClassName().equals(IBluetooth.class.getName())) {
1046 if (className.getClassName().equals("com.android.bluetooth.btservice.AdapterService")) {
1047 msg.arg1 = SERVICE_IBLUETOOTH;
1048 // } else if (className.getClassName().equals(IBluetoothGatt.class.getName())) {
1049 } else if (className.getClassName().equals("com.android.bluetooth.gatt.GattService")) {
1050 msg.arg1 = SERVICE_IBLUETOOTHGATT;
1051 } else {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001052 Slog.e(TAG, "Unknown service connected: " + className.getClassName());
Matthew Xieddf7e472013-03-01 18:41:02 -08001053 return;
1054 }
fredc0f420372012-04-12 00:02:00 -07001055 msg.obj = service;
1056 mHandler.sendMessage(msg);
1057 }
1058
1059 public void onServiceDisconnected(ComponentName className) {
fredc0f420372012-04-12 00:02:00 -07001060 // Called if we unexpected disconnected.
Jeff Sharkey67609c72016-03-05 14:29:13 -07001061 if (DBG) Slog.d(TAG, "BluetoothServiceConnection, disconnected: " +
Matthew Xieddf7e472013-03-01 18:41:02 -08001062 className.getClassName());
fredc0f420372012-04-12 00:02:00 -07001063 Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED);
Matthew Xieddf7e472013-03-01 18:41:02 -08001064 if (className.getClassName().equals("com.android.bluetooth.btservice.AdapterService")) {
1065 msg.arg1 = SERVICE_IBLUETOOTH;
1066 } else if (className.getClassName().equals("com.android.bluetooth.gatt.GattService")) {
1067 msg.arg1 = SERVICE_IBLUETOOTHGATT;
1068 } else {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001069 Slog.e(TAG, "Unknown service disconnected: " + className.getClassName());
Matthew Xieddf7e472013-03-01 18:41:02 -08001070 return;
1071 }
fredc0f420372012-04-12 00:02:00 -07001072 mHandler.sendMessage(msg);
1073 }
1074 }
1075
1076 private BluetoothServiceConnection mConnection = new BluetoothServiceConnection();
1077
Zhihai Xu40874a02012-10-08 17:57:03 -07001078 private class BluetoothHandler extends Handler {
1079 public BluetoothHandler(Looper looper) {
1080 super(looper);
1081 }
1082
fredc0f420372012-04-12 00:02:00 -07001083 @Override
1084 public void handleMessage(Message msg) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001085 if (DBG) Slog.d (TAG, "Message: " + msg.what);
fredc0f420372012-04-12 00:02:00 -07001086 switch (msg.what) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001087 case MESSAGE_ENABLE:
fredcf2458862012-04-16 15:18:27 -07001088 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001089 Slog.d(TAG, "MESSAGE_ENABLE: mBluetooth = " + mBluetooth);
fredc649fe492012-04-19 01:07:18 -07001090 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001091 mHandler.removeMessages(MESSAGE_RESTART_BLUETOOTH_SERVICE);
1092 mEnable = true;
Zhihai Xu401202b2012-12-03 11:36:21 -08001093 handleEnable(msg.arg1 == 1);
fredc649fe492012-04-19 01:07:18 -07001094 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001095
fredc0f420372012-04-12 00:02:00 -07001096 case MESSAGE_DISABLE:
Zhihai Xu40874a02012-10-08 17:57:03 -07001097 mHandler.removeMessages(MESSAGE_RESTART_BLUETOOTH_SERVICE);
1098 if (mEnable && mBluetooth != null) {
1099 waitForOnOff(true, false);
1100 mEnable = false;
Zhihai Xu401202b2012-12-03 11:36:21 -08001101 handleDisable();
Zhihai Xu40874a02012-10-08 17:57:03 -07001102 waitForOnOff(false, false);
1103 } else {
1104 mEnable = false;
Zhihai Xu401202b2012-12-03 11:36:21 -08001105 handleDisable();
Zhihai Xu40874a02012-10-08 17:57:03 -07001106 }
fredc0f420372012-04-12 00:02:00 -07001107 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001108
fredc0f420372012-04-12 00:02:00 -07001109 case MESSAGE_REGISTER_ADAPTER:
1110 {
1111 IBluetoothManagerCallback callback = (IBluetoothManagerCallback) msg.obj;
fredcd6883532012-04-25 17:46:13 -07001112 boolean added = mCallbacks.register(callback);
Jeff Sharkey67609c72016-03-05 14:29:13 -07001113 Slog.d(TAG,"Added callback: " + (callback == null? "null": callback) +":" +added );
fredc0f420372012-04-12 00:02:00 -07001114 }
1115 break;
1116 case MESSAGE_UNREGISTER_ADAPTER:
1117 {
1118 IBluetoothManagerCallback callback = (IBluetoothManagerCallback) msg.obj;
fredcd6883532012-04-25 17:46:13 -07001119 boolean removed = mCallbacks.unregister(callback);
Jeff Sharkey67609c72016-03-05 14:29:13 -07001120 Slog.d(TAG,"Removed callback: " + (callback == null? "null": callback) +":" + removed);
fredc0f420372012-04-12 00:02:00 -07001121 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001122 }
fredc0f420372012-04-12 00:02:00 -07001123 case MESSAGE_REGISTER_STATE_CHANGE_CALLBACK:
1124 {
1125 IBluetoothStateChangeCallback callback = (IBluetoothStateChangeCallback) msg.obj;
Matthew Xie9b693992013-10-10 11:21:40 -07001126 if (callback != null) {
1127 mStateChangeCallbacks.register(callback);
1128 }
fredc0f420372012-04-12 00:02:00 -07001129 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001130 }
fredc0f420372012-04-12 00:02:00 -07001131 case MESSAGE_UNREGISTER_STATE_CHANGE_CALLBACK:
1132 {
1133 IBluetoothStateChangeCallback callback = (IBluetoothStateChangeCallback) msg.obj;
Matthew Xie9b693992013-10-10 11:21:40 -07001134 if (callback != null) {
1135 mStateChangeCallbacks.unregister(callback);
1136 }
fredc0f420372012-04-12 00:02:00 -07001137 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001138 }
Benjamin Franze8b98922014-11-12 15:57:54 +00001139 case MESSAGE_ADD_PROXY_DELAYED:
1140 {
1141 ProfileServiceConnections psc = mProfileServices.get(
1142 new Integer(msg.arg1));
1143 if (psc == null) {
1144 break;
1145 }
1146 IBluetoothProfileServiceConnection proxy =
1147 (IBluetoothProfileServiceConnection) msg.obj;
1148 psc.addProxy(proxy);
1149 break;
1150 }
1151 case MESSAGE_BIND_PROFILE_SERVICE:
1152 {
1153 ProfileServiceConnections psc = (ProfileServiceConnections) msg.obj;
1154 removeMessages(MESSAGE_BIND_PROFILE_SERVICE, msg.obj);
1155 if (psc == null) {
1156 break;
1157 }
1158 psc.bindService();
1159 break;
1160 }
fredc0f420372012-04-12 00:02:00 -07001161 case MESSAGE_BLUETOOTH_SERVICE_CONNECTED:
1162 {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001163 if (DBG) Slog.d(TAG,"MESSAGE_BLUETOOTH_SERVICE_CONNECTED: " + msg.arg1);
fredc0f420372012-04-12 00:02:00 -07001164
1165 IBinder service = (IBinder) msg.obj;
1166 synchronized(mConnection) {
Matthew Xieddf7e472013-03-01 18:41:02 -08001167 if (msg.arg1 == SERVICE_IBLUETOOTHGATT) {
1168 mBluetoothGatt = IBluetoothGatt.Stub.asInterface(service);
Nitin Arorad055adb2015-03-02 15:03:51 -08001169 onBluetoothGattServiceUp();
Matthew Xieddf7e472013-03-01 18:41:02 -08001170 break;
1171 } // else must be SERVICE_IBLUETOOTH
1172
1173 //Remove timeout
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001174 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
Matthew Xieddf7e472013-03-01 18:41:02 -08001175
fredc0f420372012-04-12 00:02:00 -07001176 mBinding = false;
Marie Janssen9db28eb2016-01-12 16:05:15 -08001177 mBluetoothBinder = service;
fredc0f420372012-04-12 00:02:00 -07001178 mBluetooth = IBluetooth.Stub.asInterface(service);
fredc0f420372012-04-12 00:02:00 -07001179
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001180 try {
1181 boolean enableHciSnoopLog = (Settings.Secure.getInt(mContentResolver,
1182 Settings.Secure.BLUETOOTH_HCI_LOG, 0) == 1);
1183 if (!mBluetooth.configHciSnoopLog(enableHciSnoopLog)) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001184 Slog.e(TAG,"IBluetooth.configHciSnoopLog return false");
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001185 }
1186 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001187 Slog.e(TAG,"Unable to call configHciSnoopLog", e);
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001188 }
1189
Ajay Panickerbf796d82016-03-11 13:47:20 -08001190 if (!isNameAndAddressSet()) {
1191 try {
1192 storeNameAndAddress(mBluetooth.getName(),
1193 mBluetooth.getAddress());
1194 } catch (RemoteException re) {
1195 Slog.e(TAG, "Unable to grab names", re);
1196 }
1197 }
1198
Matthew Xiecdce0b92012-07-12 19:06:15 -07001199 //Register callback object
fredcbf072a72012-05-09 16:52:50 -07001200 try {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001201 mBluetooth.registerCallback(mBluetoothCallback);
1202 } catch (RemoteException re) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001203 Slog.e(TAG, "Unable to register BluetoothCallback",re);
fredcbf072a72012-05-09 16:52:50 -07001204 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001205 //Inform BluetoothAdapter instances that service is up
Zhihai Xu40874a02012-10-08 17:57:03 -07001206 sendBluetoothServiceUpCallback();
1207
Matthew Xiecdce0b92012-07-12 19:06:15 -07001208 //Do enable request
1209 try {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001210 if (mQuietEnable == false) {
1211 if(!mBluetooth.enable()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001212 Slog.e(TAG,"IBluetooth.enable() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001213 }
1214 }
1215 else
1216 {
1217 if(!mBluetooth.enableNoAutoConnect()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001218 Slog.e(TAG,"IBluetooth.enableNoAutoConnect() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001219 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001220 }
1221 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001222 Slog.e(TAG,"Unable to call enable()",e);
Matthew Xiecdce0b92012-07-12 19:06:15 -07001223 }
Freda8c6df02012-07-11 10:25:23 -07001224 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001225
1226 if (!mEnable) {
1227 waitForOnOff(true, false);
Zhihai Xu401202b2012-12-03 11:36:21 -08001228 handleDisable();
Zhihai Xu40874a02012-10-08 17:57:03 -07001229 waitForOnOff(false, false);
1230 }
fredc649fe492012-04-19 01:07:18 -07001231 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001232 }
fredc649fe492012-04-19 01:07:18 -07001233 case MESSAGE_TIMEOUT_BIND: {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001234 Slog.e(TAG, "MESSAGE_TIMEOUT_BIND");
fredc0f420372012-04-12 00:02:00 -07001235 synchronized(mConnection) {
1236 mBinding = false;
1237 }
fredc649fe492012-04-19 01:07:18 -07001238 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001239 }
fredcbf072a72012-05-09 16:52:50 -07001240 case MESSAGE_BLUETOOTH_STATE_CHANGE:
fredc0f420372012-04-12 00:02:00 -07001241 {
fredcbf072a72012-05-09 16:52:50 -07001242 int prevState = msg.arg1;
1243 int newState = msg.arg2;
Jeff Sharkey67609c72016-03-05 14:29:13 -07001244 if (DBG) Slog.d(TAG, "MESSAGE_BLUETOOTH_STATE_CHANGE: prevState = " + prevState + ", newState=" + newState);
Zhihai Xu40874a02012-10-08 17:57:03 -07001245 mState = newState;
1246 bluetoothStateChangeHandler(prevState, newState);
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001247 // handle error state transition case from TURNING_ON to OFF
1248 // unbind and rebind bluetooth service and enable bluetooth
Nitin Arorad055adb2015-03-02 15:03:51 -08001249 if ((prevState == BluetoothAdapter.STATE_BLE_TURNING_ON) &&
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001250 (newState == BluetoothAdapter.STATE_OFF) &&
1251 (mBluetooth != null) && mEnable) {
1252 recoverBluetoothServiceFromError();
1253 }
Nitin Arorad055adb2015-03-02 15:03:51 -08001254 if ((prevState == BluetoothAdapter.STATE_TURNING_ON) &&
1255 (newState == BluetoothAdapter.STATE_BLE_ON) &&
1256 (mBluetooth != null) && mEnable) {
1257 recoverBluetoothServiceFromError();
1258 }
1259 if (newState == BluetoothAdapter.STATE_ON ||
1260 newState == BluetoothAdapter.STATE_BLE_ON) {
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001261 // bluetooth is working, reset the counter
1262 if (mErrorRecoveryRetryCounter != 0) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001263 Slog.w(TAG, "bluetooth is recovered from error");
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001264 mErrorRecoveryRetryCounter = 0;
1265 }
1266 }
fredc649fe492012-04-19 01:07:18 -07001267 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001268 }
fredc0f420372012-04-12 00:02:00 -07001269 case MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED:
1270 {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001271 Slog.e(TAG, "MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED: " + msg.arg1);
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301272 synchronized(mConnection) {
Matthew Xieddf7e472013-03-01 18:41:02 -08001273 if (msg.arg1 == SERVICE_IBLUETOOTH) {
1274 // if service is unbinded already, do nothing and return
1275 if (mBluetooth == null) break;
1276 mBluetooth = null;
1277 } else if (msg.arg1 == SERVICE_IBLUETOOTHGATT) {
1278 mBluetoothGatt = null;
1279 break;
1280 } else {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001281 Slog.e(TAG, "Bad msg.arg1: " + msg.arg1);
Matthew Xieddf7e472013-03-01 18:41:02 -08001282 break;
1283 }
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301284 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001285
1286 if (mEnable) {
1287 mEnable = false;
1288 // Send a Bluetooth Restart message
1289 Message restartMsg = mHandler.obtainMessage(
1290 MESSAGE_RESTART_BLUETOOTH_SERVICE);
1291 mHandler.sendMessageDelayed(restartMsg,
1292 SERVICE_RESTART_TIME_MS);
1293 }
1294
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001295 sendBluetoothServiceDownCallback();
Zhihai Xu40874a02012-10-08 17:57:03 -07001296
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001297 // Send BT state broadcast to update
1298 // the BT icon correctly
1299 if ((mState == BluetoothAdapter.STATE_TURNING_ON) ||
1300 (mState == BluetoothAdapter.STATE_ON)) {
1301 bluetoothStateChangeHandler(BluetoothAdapter.STATE_ON,
1302 BluetoothAdapter.STATE_TURNING_OFF);
1303 mState = BluetoothAdapter.STATE_TURNING_OFF;
Zhihai Xu40874a02012-10-08 17:57:03 -07001304 }
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001305 if (mState == BluetoothAdapter.STATE_TURNING_OFF) {
1306 bluetoothStateChangeHandler(BluetoothAdapter.STATE_TURNING_OFF,
1307 BluetoothAdapter.STATE_OFF);
1308 }
1309
1310 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
1311 mState = BluetoothAdapter.STATE_OFF;
fredc649fe492012-04-19 01:07:18 -07001312 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001313 }
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301314 case MESSAGE_RESTART_BLUETOOTH_SERVICE:
1315 {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001316 Slog.d(TAG, "MESSAGE_RESTART_BLUETOOTH_SERVICE:"
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301317 +" Restart IBluetooth service");
1318 /* Enable without persisting the setting as
1319 it doesnt change when IBluetooth
1320 service restarts */
Zhihai Xu40874a02012-10-08 17:57:03 -07001321 mEnable = true;
Zhihai Xu401202b2012-12-03 11:36:21 -08001322 handleEnable(mQuietEnable);
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301323 break;
1324 }
1325
fredc0f420372012-04-12 00:02:00 -07001326 case MESSAGE_TIMEOUT_UNBIND:
1327 {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001328 Slog.e(TAG, "MESSAGE_TIMEOUT_UNBIND");
fredc0f420372012-04-12 00:02:00 -07001329 synchronized(mConnection) {
1330 mUnbinding = false;
1331 }
fredc649fe492012-04-19 01:07:18 -07001332 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001333 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001334
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001335 case MESSAGE_USER_SWITCHED: {
1336 if (DBG) Slog.d(TAG, "MESSAGE_USER_SWITCHED");
Zhihai Xu40874a02012-10-08 17:57:03 -07001337 mHandler.removeMessages(MESSAGE_USER_SWITCHED);
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001338
Zhihai Xu40874a02012-10-08 17:57:03 -07001339 /* disable and enable BT when detect a user switch */
1340 if (mEnable && mBluetooth != null) {
1341 synchronized (mConnection) {
1342 if (mBluetooth != null) {
1343 //Unregister callback object
1344 try {
1345 mBluetooth.unregisterCallback(mBluetoothCallback);
1346 } catch (RemoteException re) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001347 Slog.e(TAG, "Unable to unregister",re);
Zhihai Xu40874a02012-10-08 17:57:03 -07001348 }
1349 }
1350 }
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001351
1352 if (mState == BluetoothAdapter.STATE_TURNING_OFF) {
1353 // MESSAGE_USER_SWITCHED happened right after MESSAGE_ENABLE
1354 bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_OFF);
1355 mState = BluetoothAdapter.STATE_OFF;
1356 }
1357 if (mState == BluetoothAdapter.STATE_OFF) {
1358 bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_TURNING_ON);
1359 mState = BluetoothAdapter.STATE_TURNING_ON;
1360 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001361
1362 waitForOnOff(true, false);
1363
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001364 if (mState == BluetoothAdapter.STATE_TURNING_ON) {
1365 bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_ON);
1366 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001367
Benjamin Franze8b98922014-11-12 15:57:54 +00001368 unbindAllBluetoothProfileServices();
Zhihai Xu40874a02012-10-08 17:57:03 -07001369 // disable
Zhihai Xu401202b2012-12-03 11:36:21 -08001370 handleDisable();
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001371 // Pbap service need receive STATE_TURNING_OFF intent to close
1372 bluetoothStateChangeHandler(BluetoothAdapter.STATE_ON,
1373 BluetoothAdapter.STATE_TURNING_OFF);
Zhihai Xu40874a02012-10-08 17:57:03 -07001374
1375 waitForOnOff(false, true);
1376
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001377 bluetoothStateChangeHandler(BluetoothAdapter.STATE_TURNING_OFF,
Zhihai Xu40874a02012-10-08 17:57:03 -07001378 BluetoothAdapter.STATE_OFF);
Zhihai Xu40874a02012-10-08 17:57:03 -07001379 sendBluetoothServiceDownCallback();
1380 synchronized (mConnection) {
1381 if (mBluetooth != null) {
1382 mBluetooth = null;
1383 //Unbind
1384 mContext.unbindService(mConnection);
1385 }
Pavlin Radoslavov29b8c4a2015-08-03 17:44:47 -07001386 mBluetoothGatt = null;
Zhihai Xu40874a02012-10-08 17:57:03 -07001387 }
1388 SystemClock.sleep(100);
1389
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001390 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
1391 mState = BluetoothAdapter.STATE_OFF;
Zhihai Xu40874a02012-10-08 17:57:03 -07001392 // enable
Zhihai Xu401202b2012-12-03 11:36:21 -08001393 handleEnable(mQuietEnable);
John Spurlock8a985d22014-02-25 09:40:05 -05001394 } else if (mBinding || mBluetooth != null) {
Zhihai Xu40874a02012-10-08 17:57:03 -07001395 Message userMsg = mHandler.obtainMessage(MESSAGE_USER_SWITCHED);
1396 userMsg.arg2 = 1 + msg.arg2;
1397 // if user is switched when service is being binding
1398 // delay sending MESSAGE_USER_SWITCHED
1399 mHandler.sendMessageDelayed(userMsg, USER_SWITCHED_TIME_MS);
1400 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001401 Slog.d(TAG, "delay MESSAGE_USER_SWITCHED " + userMsg.arg2);
Zhihai Xu40874a02012-10-08 17:57:03 -07001402 }
John Spurlock8a985d22014-02-25 09:40:05 -05001403 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001404 break;
1405 }
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001406 case MESSAGE_USER_UNLOCKED: {
1407 if (DBG) Slog.d(TAG, "MESSAGE_USER_UNLOCKED");
1408 mHandler.removeMessages(MESSAGE_USER_SWITCHED);
1409
1410 synchronized (mConnection) {
1411 if (mEnable && !mBinding && (mBluetooth == null)) {
1412 // We should be connected, but we gave up for some
1413 // reason; maybe the Bluetooth service wasn't encryption
1414 // aware, so try binding again.
1415 if (DBG) Slog.d(TAG, "Enabled but not bound; retrying after unlock");
1416 handleEnable(mQuietEnable);
1417 }
1418 }
1419 }
fredc0f420372012-04-12 00:02:00 -07001420 }
1421 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001422 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001423
Zhihai Xu401202b2012-12-03 11:36:21 -08001424 private void handleEnable(boolean quietMode) {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001425 mQuietEnable = quietMode;
1426
Matthew Xiecdce0b92012-07-12 19:06:15 -07001427 synchronized(mConnection) {
Zhihai Xu40874a02012-10-08 17:57:03 -07001428 if ((mBluetooth == null) && (!mBinding)) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001429 //Start bind timeout and bind
1430 Message timeoutMsg=mHandler.obtainMessage(MESSAGE_TIMEOUT_BIND);
1431 mHandler.sendMessageDelayed(timeoutMsg,TIMEOUT_BIND_MS);
Matthew Xiecdce0b92012-07-12 19:06:15 -07001432 Intent i = new Intent(IBluetooth.class.getName());
Dianne Hackbornce09f5a2014-10-10 15:03:13 -07001433 if (!doBind(i, mConnection,Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT,
1434 UserHandle.CURRENT)) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001435 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
Zhihai Xu40874a02012-10-08 17:57:03 -07001436 } else {
1437 mBinding = true;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001438 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001439 } else if (mBluetooth != null) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001440 //Enable bluetooth
1441 try {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001442 if (!mQuietEnable) {
1443 if(!mBluetooth.enable()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001444 Slog.e(TAG,"IBluetooth.enable() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001445 }
1446 }
1447 else {
1448 if(!mBluetooth.enableNoAutoConnect()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001449 Slog.e(TAG,"IBluetooth.enableNoAutoConnect() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001450 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001451 }
1452 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001453 Slog.e(TAG,"Unable to call enable()",e);
Matthew Xiecdce0b92012-07-12 19:06:15 -07001454 }
1455 }
1456 }
1457 }
1458
Dianne Hackborn221ea892013-08-04 16:50:16 -07001459 boolean doBind(Intent intent, ServiceConnection conn, int flags, UserHandle user) {
1460 ComponentName comp = intent.resolveSystemService(mContext.getPackageManager(), 0);
1461 intent.setComponent(comp);
1462 if (comp == null || !mContext.bindServiceAsUser(intent, conn, flags, user)) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001463 Slog.e(TAG, "Fail to bind to: " + intent);
Dianne Hackborn221ea892013-08-04 16:50:16 -07001464 return false;
1465 }
1466 return true;
1467 }
1468
Zhihai Xu401202b2012-12-03 11:36:21 -08001469 private void handleDisable() {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001470 synchronized(mConnection) {
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001471 if (mBluetooth != null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001472 if (DBG) Slog.d(TAG,"Sending off request.");
Matthew Xiecdce0b92012-07-12 19:06:15 -07001473
1474 try {
1475 if(!mBluetooth.disable()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001476 Slog.e(TAG,"IBluetooth.disable() returned false");
Matthew Xiecdce0b92012-07-12 19:06:15 -07001477 }
1478 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001479 Slog.e(TAG,"Unable to call disable()",e);
Matthew Xiecdce0b92012-07-12 19:06:15 -07001480 }
1481 }
1482 }
1483 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001484
1485 private boolean checkIfCallerIsForegroundUser() {
1486 int foregroundUser;
1487 int callingUser = UserHandle.getCallingUserId();
Martijn Coenen8385c5a2012-11-29 10:14:16 -08001488 int callingUid = Binder.getCallingUid();
Zhihai Xu40874a02012-10-08 17:57:03 -07001489 long callingIdentity = Binder.clearCallingIdentity();
Benjamin Franze8b98922014-11-12 15:57:54 +00001490 UserManager um = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
1491 UserInfo ui = um.getProfileParent(callingUser);
1492 int parentUser = (ui != null) ? ui.id : UserHandle.USER_NULL;
Martijn Coenen8385c5a2012-11-29 10:14:16 -08001493 int callingAppId = UserHandle.getAppId(callingUid);
Zhihai Xu40874a02012-10-08 17:57:03 -07001494 boolean valid = false;
1495 try {
1496 foregroundUser = ActivityManager.getCurrentUser();
Martijn Coenen8385c5a2012-11-29 10:14:16 -08001497 valid = (callingUser == foregroundUser) ||
Benjamin Franze8b98922014-11-12 15:57:54 +00001498 parentUser == foregroundUser ||
Adrian Roosbd9a9a52014-08-18 15:31:57 +02001499 callingAppId == Process.NFC_UID ||
1500 callingAppId == mSystemUiUid;
Zhihai Xu40874a02012-10-08 17:57:03 -07001501 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001502 Slog.d(TAG, "checkIfCallerIsForegroundUser: valid=" + valid
Zhihai Xu40874a02012-10-08 17:57:03 -07001503 + " callingUser=" + callingUser
Benjamin Franze8b98922014-11-12 15:57:54 +00001504 + " parentUser=" + parentUser
Zhihai Xu40874a02012-10-08 17:57:03 -07001505 + " foregroundUser=" + foregroundUser);
1506 }
1507 } finally {
1508 Binder.restoreCallingIdentity(callingIdentity);
1509 }
1510 return valid;
1511 }
1512
Nitin Arorad055adb2015-03-02 15:03:51 -08001513 private void sendBleStateChanged(int prevState, int newState) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001514 if (DBG) Slog.d(TAG,"BLE State Change Intent: " + prevState + " -> " + newState);
Nitin Arorad055adb2015-03-02 15:03:51 -08001515 // Send broadcast message to everyone else
1516 Intent intent = new Intent(BluetoothAdapter.ACTION_BLE_STATE_CHANGED);
1517 intent.putExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE, prevState);
1518 intent.putExtra(BluetoothAdapter.EXTRA_STATE, newState);
1519 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1520 mContext.sendBroadcastAsUser(intent, UserHandle.ALL, BLUETOOTH_PERM);
1521 }
1522
Zhihai Xu40874a02012-10-08 17:57:03 -07001523 private void bluetoothStateChangeHandler(int prevState, int newState) {
Nitin Arorad055adb2015-03-02 15:03:51 -08001524 boolean isStandardBroadcast = true;
Zhihai Xu40874a02012-10-08 17:57:03 -07001525 if (prevState != newState) {
1526 //Notify all proxy objects first of adapter state change
Nitin Arorad055adb2015-03-02 15:03:51 -08001527 if (newState == BluetoothAdapter.STATE_BLE_ON
1528 || newState == BluetoothAdapter.STATE_OFF) {
1529 boolean intermediate_off = (prevState == BluetoothAdapter.STATE_TURNING_OFF
1530 && newState == BluetoothAdapter.STATE_BLE_ON);
Zhihai Xu40874a02012-10-08 17:57:03 -07001531
Nitin Arorad055adb2015-03-02 15:03:51 -08001532 if (newState == BluetoothAdapter.STATE_OFF) {
1533 // If Bluetooth is off, send service down event to proxy objects, and unbind
Jeff Sharkey67609c72016-03-05 14:29:13 -07001534 if (DBG) Slog.d(TAG, "Bluetooth is complete turn off");
Nitin Arorad055adb2015-03-02 15:03:51 -08001535 if (canUnbindBluetoothService()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001536 if (DBG) Slog.d(TAG, "Good to unbind!");
Matthew Xieddf7e472013-03-01 18:41:02 -08001537 sendBluetoothServiceDownCallback();
1538 unbindAndFinish();
Nitin Arorad055adb2015-03-02 15:03:51 -08001539 sendBleStateChanged(prevState, newState);
1540 // Don't broadcast as it has already been broadcast before
1541 isStandardBroadcast = false;
Matthew Xieddf7e472013-03-01 18:41:02 -08001542 }
Nitin Arorad055adb2015-03-02 15:03:51 -08001543
1544 } else if (!intermediate_off) {
1545 // connect to GattService
Jeff Sharkey67609c72016-03-05 14:29:13 -07001546 if (DBG) Slog.d(TAG, "Bluetooth is in LE only mode");
Nitin Arorad055adb2015-03-02 15:03:51 -08001547 if (mBluetoothGatt != null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001548 if (DBG) Slog.d(TAG, "Calling BluetoothGattServiceUp");
Nitin Arorad055adb2015-03-02 15:03:51 -08001549 onBluetoothGattServiceUp();
1550 } else {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001551 if (DBG) Slog.d(TAG, "Binding Bluetooth GATT service");
Nitin Arorad055adb2015-03-02 15:03:51 -08001552 if (mContext.getPackageManager().hasSystemFeature(
1553 PackageManager.FEATURE_BLUETOOTH_LE)) {
1554 Intent i = new Intent(IBluetoothGatt.class.getName());
1555 doBind(i, mConnection, Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT, UserHandle.CURRENT);
1556 }
1557 }
1558 sendBleStateChanged(prevState, newState);
1559 //Don't broadcase this as std intent
1560 isStandardBroadcast = false;
1561
1562 } else if (intermediate_off){
Jeff Sharkey67609c72016-03-05 14:29:13 -07001563 if (DBG) Slog.d(TAG, "Intermediate off, back to LE only mode");
Nitin Arorad055adb2015-03-02 15:03:51 -08001564 // For LE only mode, broadcast as is
1565 sendBleStateChanged(prevState, newState);
1566 sendBluetoothStateCallback(false); // BT is OFF for general users
1567 // Broadcast as STATE_OFF
1568 newState = BluetoothAdapter.STATE_OFF;
1569 sendBrEdrDownCallback();
Zhihai Xu40874a02012-10-08 17:57:03 -07001570 }
Nitin Arorad055adb2015-03-02 15:03:51 -08001571 } else if (newState == BluetoothAdapter.STATE_ON) {
1572 boolean isUp = (newState==BluetoothAdapter.STATE_ON);
1573 sendBluetoothStateCallback(isUp);
1574 sendBleStateChanged(prevState, newState);
1575
1576 } else if (newState == BluetoothAdapter.STATE_BLE_TURNING_ON
1577 || newState == BluetoothAdapter.STATE_BLE_TURNING_OFF ) {
1578 sendBleStateChanged(prevState, newState);
1579 isStandardBroadcast = false;
1580
1581 } else if (newState == BluetoothAdapter.STATE_TURNING_ON
1582 || newState == BluetoothAdapter.STATE_TURNING_OFF) {
1583 sendBleStateChanged(prevState, newState);
Zhihai Xu40874a02012-10-08 17:57:03 -07001584 }
1585
Nitin Arorad055adb2015-03-02 15:03:51 -08001586 if (isStandardBroadcast) {
1587 if (prevState == BluetoothAdapter.STATE_BLE_ON) {
1588 // Show prevState of BLE_ON as OFF to standard users
1589 prevState = BluetoothAdapter.STATE_OFF;
1590 }
1591 Intent intent = new Intent(BluetoothAdapter.ACTION_STATE_CHANGED);
1592 intent.putExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE, prevState);
1593 intent.putExtra(BluetoothAdapter.EXTRA_STATE, newState);
1594 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1595 mContext.sendBroadcastAsUser(intent, UserHandle.ALL, BLUETOOTH_PERM);
1596 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001597 }
1598 }
1599
1600 /**
1601 * if on is true, wait for state become ON
1602 * if off is true, wait for state become OFF
1603 * if both on and off are false, wait for state not ON
1604 */
1605 private boolean waitForOnOff(boolean on, boolean off) {
1606 int i = 0;
1607 while (i < 10) {
1608 synchronized(mConnection) {
1609 try {
1610 if (mBluetooth == null) break;
1611 if (on) {
1612 if (mBluetooth.getState() == BluetoothAdapter.STATE_ON) return true;
1613 } else if (off) {
1614 if (mBluetooth.getState() == BluetoothAdapter.STATE_OFF) return true;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07001615 } else {
Zhihai Xu40874a02012-10-08 17:57:03 -07001616 if (mBluetooth.getState() != BluetoothAdapter.STATE_ON) return true;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07001617 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001618 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001619 Slog.e(TAG, "getState()", e);
Zhihai Xu40874a02012-10-08 17:57:03 -07001620 break;
1621 }
1622 }
1623 if (on || off) {
1624 SystemClock.sleep(300);
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07001625 } else {
Zhihai Xu40874a02012-10-08 17:57:03 -07001626 SystemClock.sleep(50);
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07001627 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001628 i++;
1629 }
Jeff Sharkey67609c72016-03-05 14:29:13 -07001630 Slog.e(TAG,"waitForOnOff time out");
Zhihai Xu40874a02012-10-08 17:57:03 -07001631 return false;
1632 }
Zhihai Xu681ae7f2012-11-12 15:14:18 -08001633
Zhihai Xu401202b2012-12-03 11:36:21 -08001634 private void sendDisableMsg() {
1635 mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_DISABLE));
1636 }
1637
1638 private void sendEnableMsg(boolean quietMode) {
1639 mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_ENABLE,
1640 quietMode ? 1 : 0, 0));
1641 }
1642
Zhihai Xu681ae7f2012-11-12 15:14:18 -08001643 private boolean canUnbindBluetoothService() {
1644 synchronized(mConnection) {
1645 //Only unbind with mEnable flag not set
1646 //For race condition: disable and enable back-to-back
1647 //Avoid unbind right after enable due to callback from disable
1648 //Only unbind with Bluetooth at OFF state
1649 //Only unbind without any MESSAGE_BLUETOOTH_STATE_CHANGE message
1650 try {
1651 if (mEnable || (mBluetooth == null)) return false;
1652 if (mHandler.hasMessages(MESSAGE_BLUETOOTH_STATE_CHANGE)) return false;
1653 return (mBluetooth.getState() == BluetoothAdapter.STATE_OFF);
1654 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001655 Slog.e(TAG, "getState()", e);
Zhihai Xu681ae7f2012-11-12 15:14:18 -08001656 }
1657 }
1658 return false;
1659 }
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001660
1661 private void recoverBluetoothServiceFromError() {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001662 Slog.e(TAG,"recoverBluetoothServiceFromError");
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001663 synchronized (mConnection) {
1664 if (mBluetooth != null) {
1665 //Unregister callback object
1666 try {
1667 mBluetooth.unregisterCallback(mBluetoothCallback);
1668 } catch (RemoteException re) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001669 Slog.e(TAG, "Unable to unregister",re);
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001670 }
1671 }
1672 }
1673
1674 SystemClock.sleep(500);
1675
1676 // disable
1677 handleDisable();
1678
1679 waitForOnOff(false, true);
1680
1681 sendBluetoothServiceDownCallback();
1682 synchronized (mConnection) {
1683 if (mBluetooth != null) {
1684 mBluetooth = null;
1685 //Unbind
1686 mContext.unbindService(mConnection);
1687 }
Pavlin Radoslavov29b8c4a2015-08-03 17:44:47 -07001688 mBluetoothGatt = null;
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001689 }
1690
1691 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
1692 mState = BluetoothAdapter.STATE_OFF;
1693
1694 mEnable = false;
1695
1696 if (mErrorRecoveryRetryCounter++ < MAX_ERROR_RESTART_RETRIES) {
1697 // Send a Bluetooth Restart message to reenable bluetooth
1698 Message restartMsg = mHandler.obtainMessage(
1699 MESSAGE_RESTART_BLUETOOTH_SERVICE);
1700 mHandler.sendMessageDelayed(restartMsg, ERROR_RESTART_TIME_MS);
1701 } else {
1702 // todo: notify user to power down and power up phone to make bluetooth work.
1703 }
1704 }
Mike Lockwood726d4de2014-10-28 14:06:28 -07001705
1706 @Override
Pavlin Radoslavov6e8faff2016-02-23 11:54:37 -08001707 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1708 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DUMP, TAG);
1709 String errorMsg = null;
1710 if (mBluetoothBinder == null) {
1711 errorMsg = "Bluetooth Service not connected";
1712 } else {
1713 try {
1714 mBluetoothBinder.dump(fd, args);
1715 } catch (RemoteException re) {
1716 errorMsg = "RemoteException while calling Bluetooth Service";
1717 }
Mike Lockwood726d4de2014-10-28 14:06:28 -07001718 }
Pavlin Radoslavov6e8faff2016-02-23 11:54:37 -08001719 if (errorMsg != null) {
1720 // Silently return if we are extracting metrics in Protobuf format
1721 if ((args.length > 0) && args[0].startsWith("--proto"))
1722 return;
1723 writer.println(errorMsg);
1724 }
Mike Lockwood726d4de2014-10-28 14:06:28 -07001725 }
fredc0f420372012-04-12 00:02:00 -07001726}