blob: 0a814ab579d39179781a1b65f5269680425761b5 [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;
Ajay Panicker4bb48302016-03-31 14:14:27 -070095 private static final int MESSAGE_GET_NAME_AND_ADDRESS = 200;
Zhihai Xu40874a02012-10-08 17:57:03 -070096 private static final int MESSAGE_USER_SWITCHED = 300;
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -070097 private static final int MESSAGE_USER_UNLOCKED = 301;
Benjamin Franze8b98922014-11-12 15:57:54 +000098 private static final int MESSAGE_ADD_PROXY_DELAYED = 400;
99 private static final int MESSAGE_BIND_PROFILE_SERVICE = 401;
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -0700100 private static final int MAX_SAVE_RETRIES = 3;
101 private static final int MAX_ERROR_RESTART_RETRIES = 6;
Zhihai Xudd9d17d2013-01-08 17:05:58 -0800102
Zhihai Xu401202b2012-12-03 11:36:21 -0800103 // Bluetooth persisted setting is off
104 private static final int BLUETOOTH_OFF=0;
105 // Bluetooth persisted setting is on
106 // and Airplane mode won't affect Bluetooth state at start up
107 private static final int BLUETOOTH_ON_BLUETOOTH=1;
108 // Bluetooth persisted setting is on
109 // but Airplane mode will affect Bluetooth state at start up
110 // and Airplane mode will have higher priority.
111 private static final int BLUETOOTH_ON_AIRPLANE=2;
fredc0f420372012-04-12 00:02:00 -0700112
Matthew Xieddf7e472013-03-01 18:41:02 -0800113 private static final int SERVICE_IBLUETOOTH = 1;
114 private static final int SERVICE_IBLUETOOTHGATT = 2;
115
fredc0f420372012-04-12 00:02:00 -0700116 private final Context mContext;
Nitin Arorad055adb2015-03-02 15:03:51 -0800117 private static int mBleAppCount = 0;
Matthew Xiecdce0b92012-07-12 19:06:15 -0700118
119 // Locks are not provided for mName and mAddress.
120 // They are accessed in handler or broadcast receiver, same thread context.
fredc0f420372012-04-12 00:02:00 -0700121 private String mAddress;
122 private String mName;
Matthew Xie6fde3092012-07-11 17:10:07 -0700123 private final ContentResolver mContentResolver;
124 private final RemoteCallbackList<IBluetoothManagerCallback> mCallbacks;
125 private final RemoteCallbackList<IBluetoothStateChangeCallback> mStateChangeCallbacks;
Marie Janssen9db28eb2016-01-12 16:05:15 -0800126 private IBinder mBluetoothBinder;
fredc649fe492012-04-19 01:07:18 -0700127 private IBluetooth mBluetooth;
Matthew Xieddf7e472013-03-01 18:41:02 -0800128 private IBluetoothGatt mBluetoothGatt;
fredc649fe492012-04-19 01:07:18 -0700129 private boolean mBinding;
130 private boolean mUnbinding;
Zhihai Xu401202b2012-12-03 11:36:21 -0800131 // used inside handler thread
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700132 private boolean mQuietEnable = false;
Zhihai Xu401202b2012-12-03 11:36:21 -0800133 // configuarion from external IBinder call which is used to
134 // synchronize with broadcast receiver.
135 private boolean mQuietEnableExternal;
136 // configuarion from external IBinder call which is used to
137 // synchronize with broadcast receiver.
138 private boolean mEnableExternal;
139 // used inside handler thread
Zhihai Xu40874a02012-10-08 17:57:03 -0700140 private boolean mEnable;
141 private int mState;
Zhihai Xu40874a02012-10-08 17:57:03 -0700142 private final BluetoothHandler mHandler;
Zhihai Xudd9d17d2013-01-08 17:05:58 -0800143 private int mErrorRecoveryRetryCounter;
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200144 private final int mSystemUiUid;
fredc0f420372012-04-12 00:02:00 -0700145
Benjamin Franze8b98922014-11-12 15:57:54 +0000146 // Save a ProfileServiceConnections object for each of the bound
147 // bluetooth profile services
148 private final Map <Integer, ProfileServiceConnections> mProfileServices =
149 new HashMap <Integer, ProfileServiceConnections>();
150
fredc649fe492012-04-19 01:07:18 -0700151 private void registerForAirplaneMode(IntentFilter filter) {
152 final ContentResolver resolver = mContext.getContentResolver();
Christopher Tatec09cdce2012-09-10 16:50:14 -0700153 final String airplaneModeRadios = Settings.Global.getString(resolver,
154 Settings.Global.AIRPLANE_MODE_RADIOS);
155 final String toggleableRadios = Settings.Global.getString(resolver,
156 Settings.Global.AIRPLANE_MODE_TOGGLEABLE_RADIOS);
fredc649fe492012-04-19 01:07:18 -0700157 boolean mIsAirplaneSensitive = airplaneModeRadios == null ? true :
Christopher Tatec09cdce2012-09-10 16:50:14 -0700158 airplaneModeRadios.contains(Settings.Global.RADIO_BLUETOOTH);
fredc649fe492012-04-19 01:07:18 -0700159 if (mIsAirplaneSensitive) {
160 filter.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED);
161 }
162 }
163
fredcbf072a72012-05-09 16:52:50 -0700164 private final IBluetoothCallback mBluetoothCallback = new IBluetoothCallback.Stub() {
165 @Override
166 public void onBluetoothStateChange(int prevState, int newState) throws RemoteException {
167 Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_STATE_CHANGE,prevState,newState);
168 mHandler.sendMessage(msg);
169 }
170 };
171
172 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
fredc0f420372012-04-12 00:02:00 -0700173 @Override
174 public void onReceive(Context context, Intent intent) {
175 String action = intent.getAction();
fredcbf072a72012-05-09 16:52:50 -0700176 if (BluetoothAdapter.ACTION_LOCAL_NAME_CHANGED.equals(action)) {
fredc0f420372012-04-12 00:02:00 -0700177 String newName = intent.getStringExtra(BluetoothAdapter.EXTRA_LOCAL_NAME);
Jeff Sharkey67609c72016-03-05 14:29:13 -0700178 if (DBG) Slog.d(TAG, "Bluetooth Adapter name changed to " + newName);
fredc0f420372012-04-12 00:02:00 -0700179 if (newName != null) {
180 storeNameAndAddress(newName, null);
181 }
fredc649fe492012-04-19 01:07:18 -0700182 } else if (Intent.ACTION_AIRPLANE_MODE_CHANGED.equals(action)) {
Zhihai Xu401202b2012-12-03 11:36:21 -0800183 synchronized(mReceiver) {
184 if (isBluetoothPersistedStateOn()) {
185 if (isAirplaneModeOn()) {
186 persistBluetoothSetting(BLUETOOTH_ON_AIRPLANE);
187 } else {
188 persistBluetoothSetting(BLUETOOTH_ON_BLUETOOTH);
189 }
190 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800191
192 int st = BluetoothAdapter.STATE_OFF;
193 if (mBluetooth != null) {
194 try {
195 st = mBluetooth.getState();
196 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700197 Slog.e(TAG,"Unable to call getState", e);
Nitin Arorad055adb2015-03-02 15:03:51 -0800198 }
199 }
Jeff Sharkey67609c72016-03-05 14:29:13 -0700200 Slog.d(TAG, "state" + st);
Nitin Arorad055adb2015-03-02 15:03:51 -0800201
Zhihai Xu401202b2012-12-03 11:36:21 -0800202 if (isAirplaneModeOn()) {
Nitin Arorad055adb2015-03-02 15:03:51 -0800203 // Clear registered LE apps to force shut-off
204 synchronized (this) {
205 mBleAppCount = 0;
Nitin Arora11f83882015-05-07 18:45:44 -0700206 mBleApps.clear();
Nitin Arorad055adb2015-03-02 15:03:51 -0800207 }
208 if (st == BluetoothAdapter.STATE_BLE_ON) {
209 //if state is BLE_ON make sure you trigger disableBLE part
210 try {
211 if (mBluetooth != null) {
212 mBluetooth.onBrEdrDown();
213 mEnableExternal = false;
214 }
215 } catch(RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700216 Slog.e(TAG,"Unable to call onBrEdrDown", e);
Nitin Arorad055adb2015-03-02 15:03:51 -0800217 }
218 } else if (st == BluetoothAdapter.STATE_ON){
219 // disable without persisting the setting
Jeff Sharkey67609c72016-03-05 14:29:13 -0700220 Slog.d(TAG, "Calling disable");
Nitin Arorad055adb2015-03-02 15:03:51 -0800221 sendDisableMsg();
222 }
Zhihai Xu401202b2012-12-03 11:36:21 -0800223 } else if (mEnableExternal) {
224 // enable without persisting the setting
Jeff Sharkey67609c72016-03-05 14:29:13 -0700225 Slog.d(TAG, "Calling enable");
Zhihai Xu401202b2012-12-03 11:36:21 -0800226 sendEnableMsg(mQuietEnableExternal);
227 }
fredc649fe492012-04-19 01:07:18 -0700228 }
fredc0f420372012-04-12 00:02:00 -0700229 }
230 }
231 };
232
233 BluetoothManagerService(Context context) {
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700234 mHandler = new BluetoothHandler(IoThread.get().getLooper());
Zhihai Xu40874a02012-10-08 17:57:03 -0700235
fredc0f420372012-04-12 00:02:00 -0700236 mContext = context;
237 mBluetooth = null;
Marie Janssen9db28eb2016-01-12 16:05:15 -0800238 mBluetoothBinder = null;
Nitin Arorad055adb2015-03-02 15:03:51 -0800239 mBluetoothGatt = null;
fredc0f420372012-04-12 00:02:00 -0700240 mBinding = false;
241 mUnbinding = false;
Zhihai Xu40874a02012-10-08 17:57:03 -0700242 mEnable = false;
243 mState = BluetoothAdapter.STATE_OFF;
Zhihai Xu401202b2012-12-03 11:36:21 -0800244 mQuietEnableExternal = false;
245 mEnableExternal = false;
fredc0f420372012-04-12 00:02:00 -0700246 mAddress = null;
247 mName = null;
Zhihai Xudd9d17d2013-01-08 17:05:58 -0800248 mErrorRecoveryRetryCounter = 0;
fredc0f420372012-04-12 00:02:00 -0700249 mContentResolver = context.getContentResolver();
Wei Wange4a744b2015-06-11 17:50:29 -0700250 // Observe BLE scan only mode settings change.
251 registerForBleScanModeChange();
fredcd6883532012-04-25 17:46:13 -0700252 mCallbacks = new RemoteCallbackList<IBluetoothManagerCallback>();
253 mStateChangeCallbacks = new RemoteCallbackList<IBluetoothStateChangeCallback>();
Miao Chou658bf2f2015-06-26 17:14:35 -0700254 IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_LOCAL_NAME_CHANGED);
Matthew Xie6fde3092012-07-11 17:10:07 -0700255 registerForAirplaneMode(filter);
Dianne Hackbornd83a0962014-05-02 16:28:33 -0700256 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
Matthew Xie6fde3092012-07-11 17:10:07 -0700257 mContext.registerReceiver(mReceiver, filter);
fredc0f420372012-04-12 00:02:00 -0700258 loadStoredNameAndAddress();
Zhihai Xu401202b2012-12-03 11:36:21 -0800259 if (isBluetoothPersistedStateOn()) {
260 mEnableExternal = true;
fredc0f420372012-04-12 00:02:00 -0700261 }
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200262
263 int sysUiUid = -1;
264 try {
Jeff Sharkeye06b4d12016-01-06 14:51:50 -0700265 sysUiUid = mContext.getPackageManager().getPackageUidAsUser("com.android.systemui",
Jeff Sharkeyc5967e92016-01-07 18:50:29 -0700266 PackageManager.MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM);
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200267 } catch (PackageManager.NameNotFoundException e) {
Joe LaPennaacddf2b2015-09-04 12:52:42 -0700268 // Some platforms, such as wearables do not have a system ui.
Jeff Sharkey67609c72016-03-05 14:29:13 -0700269 Slog.w(TAG, "Unable to resolve SystemUI's UID.", e);
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200270 }
271 mSystemUiUid = sysUiUid;
fredc0f420372012-04-12 00:02:00 -0700272 }
273
fredc649fe492012-04-19 01:07:18 -0700274 /**
275 * Returns true if airplane mode is currently on
276 */
277 private final boolean isAirplaneModeOn() {
Christopher Tatec09cdce2012-09-10 16:50:14 -0700278 return Settings.Global.getInt(mContext.getContentResolver(),
279 Settings.Global.AIRPLANE_MODE_ON, 0) == 1;
fredc649fe492012-04-19 01:07:18 -0700280 }
281
282 /**
283 * Returns true if the Bluetooth saved state is "on"
284 */
285 private final boolean isBluetoothPersistedStateOn() {
Jeff Brownbf6f6f92012-09-25 15:03:20 -0700286 return Settings.Global.getInt(mContentResolver,
Zhihai Xu401202b2012-12-03 11:36:21 -0800287 Settings.Global.BLUETOOTH_ON, 0) != BLUETOOTH_OFF;
288 }
289
290 /**
291 * Returns true if the Bluetooth saved state is BLUETOOTH_ON_BLUETOOTH
292 */
293 private final boolean isBluetoothPersistedStateOnBluetooth() {
294 return Settings.Global.getInt(mContentResolver,
295 Settings.Global.BLUETOOTH_ON, 0) == BLUETOOTH_ON_BLUETOOTH;
fredc649fe492012-04-19 01:07:18 -0700296 }
297
298 /**
299 * Save the Bluetooth on/off state
300 *
301 */
Zhihai Xu401202b2012-12-03 11:36:21 -0800302 private void persistBluetoothSetting(int value) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -0700303 Settings.Global.putInt(mContext.getContentResolver(),
304 Settings.Global.BLUETOOTH_ON,
Zhihai Xu401202b2012-12-03 11:36:21 -0800305 value);
fredc649fe492012-04-19 01:07:18 -0700306 }
307
308 /**
309 * Returns true if the Bluetooth Adapter's name and address is
310 * locally cached
311 * @return
312 */
fredc0f420372012-04-12 00:02:00 -0700313 private boolean isNameAndAddressSet() {
314 return mName !=null && mAddress!= null && mName.length()>0 && mAddress.length()>0;
315 }
316
fredc649fe492012-04-19 01:07:18 -0700317 /**
318 * Retrieve the Bluetooth Adapter's name and address and save it in
319 * in the local cache
320 */
fredc0f420372012-04-12 00:02:00 -0700321 private void loadStoredNameAndAddress() {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700322 if (DBG) Slog.d(TAG, "Loading stored name and address");
Zhihai Xud31c3222012-10-31 16:08:57 -0700323 if (mContext.getResources().getBoolean
324 (com.android.internal.R.bool.config_bluetooth_address_validation) &&
325 Settings.Secure.getInt(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDR_VALID, 0) == 0) {
326 // if the valid flag is not set, don't load the address and name
Jeff Sharkey67609c72016-03-05 14:29:13 -0700327 if (DBG) Slog.d(TAG, "invalid bluetooth name and address stored");
Zhihai Xud31c3222012-10-31 16:08:57 -0700328 return;
329 }
fredc0f420372012-04-12 00:02:00 -0700330 mName = Settings.Secure.getString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_NAME);
331 mAddress = Settings.Secure.getString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDRESS);
Jeff Sharkey67609c72016-03-05 14:29:13 -0700332 if (DBG) Slog.d(TAG, "Stored bluetooth Name=" + mName + ",Address=" + mAddress);
fredc0f420372012-04-12 00:02:00 -0700333 }
334
fredc649fe492012-04-19 01:07:18 -0700335 /**
336 * Save the Bluetooth name and address in the persistent store.
337 * Only non-null values will be saved.
338 * @param name
339 * @param address
340 */
fredc0f420372012-04-12 00:02:00 -0700341 private void storeNameAndAddress(String name, String address) {
342 if (name != null) {
343 Settings.Secure.putString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_NAME, name);
fredc0f420372012-04-12 00:02:00 -0700344 mName = name;
Jeff Sharkey67609c72016-03-05 14:29:13 -0700345 if (DBG) Slog.d(TAG,"Stored Bluetooth name: " +
fredc649fe492012-04-19 01:07:18 -0700346 Settings.Secure.getString(mContentResolver,SECURE_SETTINGS_BLUETOOTH_NAME));
fredc0f420372012-04-12 00:02:00 -0700347 }
348
349 if (address != null) {
350 Settings.Secure.putString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDRESS, address);
fredc0f420372012-04-12 00:02:00 -0700351 mAddress=address;
Jeff Sharkey67609c72016-03-05 14:29:13 -0700352 if (DBG) Slog.d(TAG,"Stored Bluetoothaddress: " +
fredc649fe492012-04-19 01:07:18 -0700353 Settings.Secure.getString(mContentResolver,SECURE_SETTINGS_BLUETOOTH_ADDRESS));
fredc0f420372012-04-12 00:02:00 -0700354 }
Zhihai Xud31c3222012-10-31 16:08:57 -0700355
356 if ((name != null) && (address != null)) {
357 Settings.Secure.putInt(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDR_VALID, 1);
358 }
fredc0f420372012-04-12 00:02:00 -0700359 }
360
361 public IBluetooth registerAdapter(IBluetoothManagerCallback callback){
Natalie Silvanovich55db6462014-05-01 16:12:23 -0700362 if (callback == null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700363 Slog.w(TAG, "Callback is null in registerAdapter");
Natalie Silvanovich55db6462014-05-01 16:12:23 -0700364 return null;
365 }
fredc0f420372012-04-12 00:02:00 -0700366 Message msg = mHandler.obtainMessage(MESSAGE_REGISTER_ADAPTER);
367 msg.obj = callback;
368 mHandler.sendMessage(msg);
369 synchronized(mConnection) {
370 return mBluetooth;
371 }
372 }
373
374 public void unregisterAdapter(IBluetoothManagerCallback callback) {
Natalie Silvanovich55db6462014-05-01 16:12:23 -0700375 if (callback == null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700376 Slog.w(TAG, "Callback is null in unregisterAdapter");
Natalie Silvanovich55db6462014-05-01 16:12:23 -0700377 return;
378 }
fredc0f420372012-04-12 00:02:00 -0700379 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
380 "Need BLUETOOTH permission");
381 Message msg = mHandler.obtainMessage(MESSAGE_UNREGISTER_ADAPTER);
382 msg.obj = callback;
383 mHandler.sendMessage(msg);
384 }
385
386 public void registerStateChangeCallback(IBluetoothStateChangeCallback callback) {
387 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
388 "Need BLUETOOTH permission");
389 Message msg = mHandler.obtainMessage(MESSAGE_REGISTER_STATE_CHANGE_CALLBACK);
390 msg.obj = callback;
391 mHandler.sendMessage(msg);
392 }
393
394 public void unregisterStateChangeCallback(IBluetoothStateChangeCallback callback) {
395 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
396 "Need BLUETOOTH permission");
397 Message msg = mHandler.obtainMessage(MESSAGE_UNREGISTER_STATE_CHANGE_CALLBACK);
398 msg.obj = callback;
399 mHandler.sendMessage(msg);
400 }
401
402 public boolean isEnabled() {
Zhihai Xu6eb76522012-11-29 15:41:04 -0800403 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
404 (!checkIfCallerIsForegroundUser())) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700405 Slog.w(TAG,"isEnabled(): not allowed for non-active and non system user");
Zhihai Xu40874a02012-10-08 17:57:03 -0700406 return false;
407 }
408
fredc0f420372012-04-12 00:02:00 -0700409 synchronized(mConnection) {
410 try {
411 return (mBluetooth != null && mBluetooth.isEnabled());
412 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700413 Slog.e(TAG, "isEnabled()", e);
fredc0f420372012-04-12 00:02:00 -0700414 }
415 }
416 return false;
417 }
418
Nitin Arorad055adb2015-03-02 15:03:51 -0800419 class ClientDeathRecipient implements IBinder.DeathRecipient {
420 public void binderDied() {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700421 if (DBG) Slog.d(TAG, "Binder is dead - unregister Ble App");
Nitin Arorad055adb2015-03-02 15:03:51 -0800422 if (mBleAppCount > 0) --mBleAppCount;
423
424 if (mBleAppCount == 0) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700425 if (DBG) Slog.d(TAG, "Disabling LE only mode after application crash");
Nitin Arorad055adb2015-03-02 15:03:51 -0800426 try {
427 if (mBluetooth != null) {
428 mBluetooth.onBrEdrDown();
429 }
430 } catch(RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700431 Slog.e(TAG,"Unable to call onBrEdrDown", e);
Nitin Arorad055adb2015-03-02 15:03:51 -0800432 }
433 }
434 }
435 }
436
437 /** Internal death rec list */
438 Map<IBinder, ClientDeathRecipient> mBleApps = new HashMap<IBinder, ClientDeathRecipient>();
439
Wei Wang67d84162015-04-26 17:04:29 -0700440 @Override
441 public boolean isBleScanAlwaysAvailable() {
442 try {
443 return (Settings.Global.getInt(mContentResolver,
444 Settings.Global.BLE_SCAN_ALWAYS_AVAILABLE)) != 0;
445 } catch (SettingNotFoundException e) {
446 }
447 return false;
448 }
449
Wei Wange4a744b2015-06-11 17:50:29 -0700450 // Monitor change of BLE scan only mode settings.
451 private void registerForBleScanModeChange() {
452 ContentObserver contentObserver = new ContentObserver(null) {
453 @Override
454 public void onChange(boolean selfChange) {
455 if (!isBleScanAlwaysAvailable()) {
456 disableBleScanMode();
457 clearBleApps();
458 try {
459 if (mBluetooth != null) mBluetooth.onBrEdrDown();
460 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700461 Slog.e(TAG, "error when disabling bluetooth", e);
Wei Wange4a744b2015-06-11 17:50:29 -0700462 }
463 }
464 }
465 };
466
467 mContentResolver.registerContentObserver(
468 Settings.Global.getUriFor(Settings.Global.BLE_SCAN_ALWAYS_AVAILABLE),
469 false, contentObserver);
470 }
471
472 // Disable ble scan only mode.
473 private void disableBleScanMode() {
474 try {
475 if (mBluetooth != null && (mBluetooth.getState() != BluetoothAdapter.STATE_ON)) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700476 if (DBG) Slog.d(TAG, "Reseting the mEnable flag for clean disable");
Wei Wange4a744b2015-06-11 17:50:29 -0700477 mEnable = false;
478 }
479 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700480 Slog.e(TAG, "getState()", e);
Wei Wange4a744b2015-06-11 17:50:29 -0700481 }
482 }
483
Nitin Arorad055adb2015-03-02 15:03:51 -0800484 public int updateBleAppCount(IBinder token, boolean enable) {
485 if (enable) {
486 ClientDeathRecipient r = mBleApps.get(token);
487 if (r == null) {
488 ClientDeathRecipient deathRec = new ClientDeathRecipient();
489 try {
490 token.linkToDeath(deathRec, 0);
491 } catch (RemoteException ex) {
492 throw new IllegalArgumentException("Wake lock is already dead.");
493 }
494 mBleApps.put(token, deathRec);
495 synchronized (this) {
496 ++mBleAppCount;
497 }
Jeff Sharkey67609c72016-03-05 14:29:13 -0700498 if (DBG) Slog.d(TAG, "Registered for death Notification");
Nitin Arorad055adb2015-03-02 15:03:51 -0800499 }
500
501 } else {
502 ClientDeathRecipient r = mBleApps.get(token);
503 if (r != null) {
Wei Wange4a744b2015-06-11 17:50:29 -0700504 // Unregister death recipient as the app goes away.
505 token.unlinkToDeath(r, 0);
Nitin Arorad055adb2015-03-02 15:03:51 -0800506 mBleApps.remove(token);
507 synchronized (this) {
508 if (mBleAppCount > 0) --mBleAppCount;
509 }
Jeff Sharkey67609c72016-03-05 14:29:13 -0700510 if (DBG) Slog.d(TAG, "Unregistered for death Notification");
Nitin Arorad055adb2015-03-02 15:03:51 -0800511 }
512 }
Jeff Sharkey67609c72016-03-05 14:29:13 -0700513 if (DBG) Slog.d(TAG, "Updated BleAppCount" + mBleAppCount);
Nitin Arorad055adb2015-03-02 15:03:51 -0800514 if (mBleAppCount == 0 && mEnable) {
Wei Wange4a744b2015-06-11 17:50:29 -0700515 disableBleScanMode();
Nitin Arorad055adb2015-03-02 15:03:51 -0800516 }
517 return mBleAppCount;
518 }
519
Wei Wange4a744b2015-06-11 17:50:29 -0700520 // Clear all apps using BLE scan only mode.
521 private void clearBleApps() {
522 synchronized (this) {
523 mBleApps.clear();
524 mBleAppCount = 0;
525 }
526 }
527
Nitin Arorad055adb2015-03-02 15:03:51 -0800528 /** @hide*/
529 public boolean isBleAppPresent() {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700530 if (DBG) Slog.d(TAG, "isBleAppPresent() count: " + mBleAppCount);
Nitin Arorad055adb2015-03-02 15:03:51 -0800531 return (mBleAppCount > 0);
532 }
533
534 /**
535 * Action taken when GattService is turned off
536 */
537 private void onBluetoothGattServiceUp() {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700538 if (DBG) Slog.d(TAG,"BluetoothGatt Service is Up");
Nitin Arorad055adb2015-03-02 15:03:51 -0800539 try{
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700540 if (isBleAppPresent() == false && mBluetooth != null
541 && mBluetooth.getState() == BluetoothAdapter.STATE_BLE_ON) {
Nitin Arorad055adb2015-03-02 15:03:51 -0800542 mBluetooth.onLeServiceUp();
543
544 // waive WRITE_SECURE_SETTINGS permission check
545 long callingIdentity = Binder.clearCallingIdentity();
546 persistBluetoothSetting(BLUETOOTH_ON_BLUETOOTH);
547 Binder.restoreCallingIdentity(callingIdentity);
548 }
549 } catch(RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700550 Slog.e(TAG,"Unable to call onServiceUp", e);
Nitin Arorad055adb2015-03-02 15:03:51 -0800551 }
552 }
553
554 /**
555 * Inform BluetoothAdapter instances that BREDR part is down
556 * and turn off all service and stack if no LE app needs it
557 */
558 private void sendBrEdrDownCallback() {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700559 if (DBG) Slog.d(TAG,"Calling sendBrEdrDownCallback callbacks");
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700560
561 if(mBluetooth == null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700562 Slog.w(TAG, "Bluetooth handle is null");
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700563 return;
564 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800565
566 if (isBleAppPresent() == false) {
567 try {
568 mBluetooth.onBrEdrDown();
569 } catch(RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700570 Slog.e(TAG, "Call to onBrEdrDown() failed.", e);
Nitin Arorad055adb2015-03-02 15:03:51 -0800571 }
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700572 } else {
573 // Need to stay at BLE ON. Disconnect all Gatt connections
Nitin Arorad055adb2015-03-02 15:03:51 -0800574 try{
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700575 mBluetoothGatt.unregAll();
Nitin Arorad055adb2015-03-02 15:03:51 -0800576 } catch(RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700577 Slog.e(TAG, "Unable to disconnect all apps.", e);
Nitin Arorad055adb2015-03-02 15:03:51 -0800578 }
579 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800580 }
581
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700582 public boolean enableNoAutoConnect()
583 {
584 mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
585 "Need BLUETOOTH ADMIN permission");
Zhihai Xu40874a02012-10-08 17:57:03 -0700586
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700587 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700588 Slog.d(TAG,"enableNoAutoConnect(): mBluetooth =" + mBluetooth +
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700589 " mBinding = " + mBinding);
590 }
Martijn Coenen8385c5a2012-11-29 10:14:16 -0800591 int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
592
593 if (callingAppId != Process.NFC_UID) {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700594 throw new SecurityException("no permission to enable Bluetooth quietly");
595 }
Martijn Coenen8385c5a2012-11-29 10:14:16 -0800596
Zhihai Xu401202b2012-12-03 11:36:21 -0800597 synchronized(mReceiver) {
598 mQuietEnableExternal = true;
599 mEnableExternal = true;
600 sendEnableMsg(true);
601 }
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700602 return true;
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700603 }
Ajay Panicker4bb48302016-03-31 14:14:27 -0700604
fredc0f420372012-04-12 00:02:00 -0700605 public boolean enable() {
Zhihai Xu6eb76522012-11-29 15:41:04 -0800606 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
607 (!checkIfCallerIsForegroundUser())) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700608 Slog.w(TAG,"enable(): not allowed for non-active and non system user");
Zhihai Xu40874a02012-10-08 17:57:03 -0700609 return false;
fredcf2458862012-04-16 15:18:27 -0700610 }
611
Zhihai Xu401202b2012-12-03 11:36:21 -0800612 mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
613 "Need BLUETOOTH ADMIN permission");
614 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700615 Slog.d(TAG,"enable(): mBluetooth =" + mBluetooth +
Zhihai Xu401202b2012-12-03 11:36:21 -0800616 " mBinding = " + mBinding);
617 }
618
619 synchronized(mReceiver) {
620 mQuietEnableExternal = false;
621 mEnableExternal = true;
622 // waive WRITE_SECURE_SETTINGS permission check
Zhihai Xu401202b2012-12-03 11:36:21 -0800623 sendEnableMsg(false);
624 }
Jeff Sharkey67609c72016-03-05 14:29:13 -0700625 if (DBG) Slog.d(TAG, "enable returning");
Zhihai Xu401202b2012-12-03 11:36:21 -0800626 return true;
fredc0f420372012-04-12 00:02:00 -0700627 }
628
629 public boolean disable(boolean persist) {
630 mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
631 "Need BLUETOOTH ADMIN permissicacheNameAndAddresson");
Zhihai Xu40874a02012-10-08 17:57:03 -0700632
Zhihai Xu6eb76522012-11-29 15:41:04 -0800633 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
634 (!checkIfCallerIsForegroundUser())) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700635 Slog.w(TAG,"disable(): not allowed for non-active and non system user");
Zhihai Xu40874a02012-10-08 17:57:03 -0700636 return false;
637 }
638
fredcf2458862012-04-16 15:18:27 -0700639 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700640 Slog.d(TAG,"disable(): mBluetooth = " + mBluetooth +
Matthew Xiecdce0b92012-07-12 19:06:15 -0700641 " mBinding = " + mBinding);
642 }
fredcf2458862012-04-16 15:18:27 -0700643
Zhihai Xu401202b2012-12-03 11:36:21 -0800644 synchronized(mReceiver) {
645 if (persist) {
646 // waive WRITE_SECURE_SETTINGS permission check
647 long callingIdentity = Binder.clearCallingIdentity();
648 persistBluetoothSetting(BLUETOOTH_OFF);
649 Binder.restoreCallingIdentity(callingIdentity);
650 }
651 mEnableExternal = false;
652 sendDisableMsg();
653 }
fredc0f420372012-04-12 00:02:00 -0700654 return true;
655 }
656
fredc649fe492012-04-19 01:07:18 -0700657 public void unbindAndFinish() {
fredcf2458862012-04-16 15:18:27 -0700658 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700659 Slog.d(TAG,"unbindAndFinish(): " + mBluetooth +
Matthew Xiecdce0b92012-07-12 19:06:15 -0700660 " mBinding = " + mBinding);
fredcf2458862012-04-16 15:18:27 -0700661 }
662
fredc0f420372012-04-12 00:02:00 -0700663 synchronized (mConnection) {
664 if (mUnbinding) return;
665 mUnbinding = true;
Zhihai Xu40874a02012-10-08 17:57:03 -0700666 if (mBluetooth != null) {
Andre Eisenbach305fdab2015-11-11 21:43:26 -0800667 //Unregister callback object
668 try {
669 mBluetooth.unregisterCallback(mBluetoothCallback);
670 } catch (RemoteException re) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700671 Slog.e(TAG, "Unable to unregister BluetoothCallback",re);
fredcbf072a72012-05-09 16:52:50 -0700672 }
Andre Eisenbach305fdab2015-11-11 21:43:26 -0800673
Jeff Sharkey67609c72016-03-05 14:29:13 -0700674 if (DBG) Slog.d(TAG, "Sending unbind request.");
Marie Janssen9db28eb2016-01-12 16:05:15 -0800675 mBluetoothBinder = null;
fredcd6883532012-04-25 17:46:13 -0700676 mBluetooth = null;
677 //Unbind
fredc0f420372012-04-12 00:02:00 -0700678 mContext.unbindService(mConnection);
fredcd6883532012-04-25 17:46:13 -0700679 mUnbinding = false;
Zhihai Xu40874a02012-10-08 17:57:03 -0700680 mBinding = false;
fredcf2458862012-04-16 15:18:27 -0700681 } else {
682 mUnbinding=false;
fredc0f420372012-04-12 00:02:00 -0700683 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800684 mBluetoothGatt = null;
fredc0f420372012-04-12 00:02:00 -0700685 }
686 }
687
Matthew Xieddf7e472013-03-01 18:41:02 -0800688 public IBluetoothGatt getBluetoothGatt() {
689 // sync protection
690 return mBluetoothGatt;
691 }
692
Benjamin Franze8b98922014-11-12 15:57:54 +0000693 @Override
694 public boolean bindBluetoothProfileService(int bluetoothProfile,
695 IBluetoothProfileServiceConnection proxy) {
696 if (!mEnable) {
697 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700698 Slog.d(TAG, "Trying to bind to profile: " + bluetoothProfile +
Benjamin Franze8b98922014-11-12 15:57:54 +0000699 ", while Bluetooth was disabled");
700 }
701 return false;
702 }
703 synchronized (mProfileServices) {
704 ProfileServiceConnections psc = mProfileServices.get(new Integer(bluetoothProfile));
705 if (psc == null) {
706 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700707 Slog.d(TAG, "Creating new ProfileServiceConnections object for"
Benjamin Franze8b98922014-11-12 15:57:54 +0000708 + " profile: " + bluetoothProfile);
709 }
Benjamin Franz5b614592014-12-09 18:58:45 +0000710
711 if (bluetoothProfile != BluetoothProfile.HEADSET) return false;
712
713 Intent intent = new Intent(IBluetoothHeadset.class.getName());
Benjamin Franze8b98922014-11-12 15:57:54 +0000714 psc = new ProfileServiceConnections(intent);
Benjamin Franz5b614592014-12-09 18:58:45 +0000715 if (!psc.bindService()) return false;
716
Benjamin Franze8b98922014-11-12 15:57:54 +0000717 mProfileServices.put(new Integer(bluetoothProfile), psc);
Benjamin Franze8b98922014-11-12 15:57:54 +0000718 }
719 }
720
721 // Introducing a delay to give the client app time to prepare
722 Message addProxyMsg = mHandler.obtainMessage(MESSAGE_ADD_PROXY_DELAYED);
723 addProxyMsg.arg1 = bluetoothProfile;
724 addProxyMsg.obj = proxy;
725 mHandler.sendMessageDelayed(addProxyMsg, ADD_PROXY_DELAY_MS);
726 return true;
727 }
728
729 @Override
730 public void unbindBluetoothProfileService(int bluetoothProfile,
731 IBluetoothProfileServiceConnection proxy) {
732 synchronized (mProfileServices) {
733 ProfileServiceConnections psc = mProfileServices.get(new Integer(bluetoothProfile));
734 if (psc == null) {
735 return;
736 }
737 psc.removeProxy(proxy);
738 }
739 }
740
741 private void unbindAllBluetoothProfileServices() {
742 synchronized (mProfileServices) {
743 for (Integer i : mProfileServices.keySet()) {
744 ProfileServiceConnections psc = mProfileServices.get(i);
Benjamin Franz5b614592014-12-09 18:58:45 +0000745 try {
746 mContext.unbindService(psc);
747 } catch (IllegalArgumentException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700748 Slog.e(TAG, "Unable to unbind service with intent: " + psc.mIntent, e);
Benjamin Franz5b614592014-12-09 18:58:45 +0000749 }
Benjamin Franze8b98922014-11-12 15:57:54 +0000750 psc.removeAllProxies();
751 }
752 mProfileServices.clear();
753 }
754 }
755
756 /**
Miao Chou658bf2f2015-06-26 17:14:35 -0700757 * Send enable message and set adapter name and address. Called when the boot phase becomes
758 * PHASE_SYSTEM_SERVICES_READY.
759 */
760 public void handleOnBootPhase() {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700761 if (DBG) Slog.d(TAG, "Bluetooth boot completed");
Miao Chou658bf2f2015-06-26 17:14:35 -0700762 if (mEnableExternal && isBluetoothPersistedStateOnBluetooth()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -0700763 if (DBG) Slog.d(TAG, "Auto-enabling Bluetooth.");
Miao Chou658bf2f2015-06-26 17:14:35 -0700764 sendEnableMsg(mQuietEnableExternal);
Ajay Panickerbf796d82016-03-11 13:47:20 -0800765 } else if (!isNameAndAddressSet()) {
766 if (DBG) Slog.d(TAG, "Getting adapter name and address");
Ajay Panicker4bb48302016-03-31 14:14:27 -0700767 Message getMsg = mHandler.obtainMessage(MESSAGE_GET_NAME_AND_ADDRESS);
768 mHandler.sendMessage(getMsg);
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 {
Ajay Panicker4bb48302016-03-31 14:14:27 -07001079 boolean mGetNameAddressOnly = false;
1080
Zhihai Xu40874a02012-10-08 17:57:03 -07001081 public BluetoothHandler(Looper looper) {
1082 super(looper);
1083 }
1084
fredc0f420372012-04-12 00:02:00 -07001085 @Override
1086 public void handleMessage(Message msg) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001087 if (DBG) Slog.d (TAG, "Message: " + msg.what);
fredc0f420372012-04-12 00:02:00 -07001088 switch (msg.what) {
Ajay Panicker4bb48302016-03-31 14:14:27 -07001089 case MESSAGE_GET_NAME_AND_ADDRESS:
1090 if (DBG) Slog.d(TAG, "MESSAGE_GET_NAME_AND_ADDRESS");
1091 synchronized(mConnection) {
1092 if ((mBluetooth == null) && (!mBinding)) {
1093 if (DBG) Slog.d(TAG, "Binding to service to get name and address");
1094 mGetNameAddressOnly = true;
1095 Message timeoutMsg = mHandler.obtainMessage(MESSAGE_TIMEOUT_BIND);
1096 mHandler.sendMessageDelayed(timeoutMsg, TIMEOUT_BIND_MS);
1097 Intent i = new Intent(IBluetooth.class.getName());
1098 if (!doBind(i, mConnection,
1099 Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT,
1100 UserHandle.CURRENT)) {
1101 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
1102 } else {
1103 mBinding = true;
1104 }
1105 } else if (mBluetooth != null) {
1106 try {
1107 storeNameAndAddress(mBluetooth.getName(),
1108 mBluetooth.getAddress());
1109 } catch (RemoteException re) {
1110 Slog.e(TAG, "Unable to grab names", re);
1111 }
1112 if (mGetNameAddressOnly && !mEnable) {
1113 unbindAndFinish();
1114 }
1115 mGetNameAddressOnly = false;
1116 }
1117 }
1118 break;
1119
Matthew Xiecdce0b92012-07-12 19:06:15 -07001120 case MESSAGE_ENABLE:
fredcf2458862012-04-16 15:18:27 -07001121 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001122 Slog.d(TAG, "MESSAGE_ENABLE: mBluetooth = " + mBluetooth);
fredc649fe492012-04-19 01:07:18 -07001123 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001124 mHandler.removeMessages(MESSAGE_RESTART_BLUETOOTH_SERVICE);
1125 mEnable = true;
Zhihai Xu401202b2012-12-03 11:36:21 -08001126 handleEnable(msg.arg1 == 1);
fredc649fe492012-04-19 01:07:18 -07001127 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001128
fredc0f420372012-04-12 00:02:00 -07001129 case MESSAGE_DISABLE:
Zhihai Xu40874a02012-10-08 17:57:03 -07001130 mHandler.removeMessages(MESSAGE_RESTART_BLUETOOTH_SERVICE);
1131 if (mEnable && mBluetooth != null) {
1132 waitForOnOff(true, false);
1133 mEnable = false;
Zhihai Xu401202b2012-12-03 11:36:21 -08001134 handleDisable();
Zhihai Xu40874a02012-10-08 17:57:03 -07001135 waitForOnOff(false, false);
1136 } else {
1137 mEnable = false;
Zhihai Xu401202b2012-12-03 11:36:21 -08001138 handleDisable();
Zhihai Xu40874a02012-10-08 17:57:03 -07001139 }
fredc0f420372012-04-12 00:02:00 -07001140 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001141
fredc0f420372012-04-12 00:02:00 -07001142 case MESSAGE_REGISTER_ADAPTER:
1143 {
1144 IBluetoothManagerCallback callback = (IBluetoothManagerCallback) msg.obj;
fredcd6883532012-04-25 17:46:13 -07001145 boolean added = mCallbacks.register(callback);
Jeff Sharkey67609c72016-03-05 14:29:13 -07001146 Slog.d(TAG,"Added callback: " + (callback == null? "null": callback) +":" +added );
fredc0f420372012-04-12 00:02:00 -07001147 }
1148 break;
1149 case MESSAGE_UNREGISTER_ADAPTER:
1150 {
1151 IBluetoothManagerCallback callback = (IBluetoothManagerCallback) msg.obj;
fredcd6883532012-04-25 17:46:13 -07001152 boolean removed = mCallbacks.unregister(callback);
Jeff Sharkey67609c72016-03-05 14:29:13 -07001153 Slog.d(TAG,"Removed callback: " + (callback == null? "null": callback) +":" + removed);
fredc0f420372012-04-12 00:02:00 -07001154 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001155 }
fredc0f420372012-04-12 00:02:00 -07001156 case MESSAGE_REGISTER_STATE_CHANGE_CALLBACK:
1157 {
1158 IBluetoothStateChangeCallback callback = (IBluetoothStateChangeCallback) msg.obj;
Matthew Xie9b693992013-10-10 11:21:40 -07001159 if (callback != null) {
1160 mStateChangeCallbacks.register(callback);
1161 }
fredc0f420372012-04-12 00:02:00 -07001162 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001163 }
fredc0f420372012-04-12 00:02:00 -07001164 case MESSAGE_UNREGISTER_STATE_CHANGE_CALLBACK:
1165 {
1166 IBluetoothStateChangeCallback callback = (IBluetoothStateChangeCallback) msg.obj;
Matthew Xie9b693992013-10-10 11:21:40 -07001167 if (callback != null) {
1168 mStateChangeCallbacks.unregister(callback);
1169 }
fredc0f420372012-04-12 00:02:00 -07001170 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001171 }
Benjamin Franze8b98922014-11-12 15:57:54 +00001172 case MESSAGE_ADD_PROXY_DELAYED:
1173 {
1174 ProfileServiceConnections psc = mProfileServices.get(
1175 new Integer(msg.arg1));
1176 if (psc == null) {
1177 break;
1178 }
1179 IBluetoothProfileServiceConnection proxy =
1180 (IBluetoothProfileServiceConnection) msg.obj;
1181 psc.addProxy(proxy);
1182 break;
1183 }
1184 case MESSAGE_BIND_PROFILE_SERVICE:
1185 {
1186 ProfileServiceConnections psc = (ProfileServiceConnections) msg.obj;
1187 removeMessages(MESSAGE_BIND_PROFILE_SERVICE, msg.obj);
1188 if (psc == null) {
1189 break;
1190 }
1191 psc.bindService();
1192 break;
1193 }
fredc0f420372012-04-12 00:02:00 -07001194 case MESSAGE_BLUETOOTH_SERVICE_CONNECTED:
1195 {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001196 if (DBG) Slog.d(TAG,"MESSAGE_BLUETOOTH_SERVICE_CONNECTED: " + msg.arg1);
fredc0f420372012-04-12 00:02:00 -07001197
1198 IBinder service = (IBinder) msg.obj;
1199 synchronized(mConnection) {
Matthew Xieddf7e472013-03-01 18:41:02 -08001200 if (msg.arg1 == SERVICE_IBLUETOOTHGATT) {
1201 mBluetoothGatt = IBluetoothGatt.Stub.asInterface(service);
Nitin Arorad055adb2015-03-02 15:03:51 -08001202 onBluetoothGattServiceUp();
Matthew Xieddf7e472013-03-01 18:41:02 -08001203 break;
1204 } // else must be SERVICE_IBLUETOOTH
1205
1206 //Remove timeout
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001207 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
Matthew Xieddf7e472013-03-01 18:41:02 -08001208
fredc0f420372012-04-12 00:02:00 -07001209 mBinding = false;
Marie Janssen9db28eb2016-01-12 16:05:15 -08001210 mBluetoothBinder = service;
fredc0f420372012-04-12 00:02:00 -07001211 mBluetooth = IBluetooth.Stub.asInterface(service);
fredc0f420372012-04-12 00:02:00 -07001212
Ajay Panicker4bb48302016-03-31 14:14:27 -07001213 if (!isNameAndAddressSet()) {
1214 Message getMsg = mHandler.obtainMessage(MESSAGE_GET_NAME_AND_ADDRESS);
1215 mHandler.sendMessage(getMsg);
1216 if (mGetNameAddressOnly) return;
1217 }
1218
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001219 try {
1220 boolean enableHciSnoopLog = (Settings.Secure.getInt(mContentResolver,
1221 Settings.Secure.BLUETOOTH_HCI_LOG, 0) == 1);
1222 if (!mBluetooth.configHciSnoopLog(enableHciSnoopLog)) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001223 Slog.e(TAG,"IBluetooth.configHciSnoopLog return false");
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001224 }
1225 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001226 Slog.e(TAG,"Unable to call configHciSnoopLog", e);
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001227 }
1228
Matthew Xiecdce0b92012-07-12 19:06:15 -07001229 //Register callback object
fredcbf072a72012-05-09 16:52:50 -07001230 try {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001231 mBluetooth.registerCallback(mBluetoothCallback);
1232 } catch (RemoteException re) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001233 Slog.e(TAG, "Unable to register BluetoothCallback",re);
fredcbf072a72012-05-09 16:52:50 -07001234 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001235 //Inform BluetoothAdapter instances that service is up
Zhihai Xu40874a02012-10-08 17:57:03 -07001236 sendBluetoothServiceUpCallback();
1237
Matthew Xiecdce0b92012-07-12 19:06:15 -07001238 //Do enable request
1239 try {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001240 if (mQuietEnable == false) {
1241 if(!mBluetooth.enable()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001242 Slog.e(TAG,"IBluetooth.enable() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001243 }
1244 }
1245 else
1246 {
1247 if(!mBluetooth.enableNoAutoConnect()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001248 Slog.e(TAG,"IBluetooth.enableNoAutoConnect() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001249 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001250 }
1251 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001252 Slog.e(TAG,"Unable to call enable()",e);
Matthew Xiecdce0b92012-07-12 19:06:15 -07001253 }
Freda8c6df02012-07-11 10:25:23 -07001254 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001255
1256 if (!mEnable) {
1257 waitForOnOff(true, false);
Zhihai Xu401202b2012-12-03 11:36:21 -08001258 handleDisable();
Zhihai Xu40874a02012-10-08 17:57:03 -07001259 waitForOnOff(false, false);
1260 }
fredc649fe492012-04-19 01:07:18 -07001261 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001262 }
fredc649fe492012-04-19 01:07:18 -07001263 case MESSAGE_TIMEOUT_BIND: {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001264 Slog.e(TAG, "MESSAGE_TIMEOUT_BIND");
fredc0f420372012-04-12 00:02:00 -07001265 synchronized(mConnection) {
1266 mBinding = false;
1267 }
fredc649fe492012-04-19 01:07:18 -07001268 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001269 }
fredcbf072a72012-05-09 16:52:50 -07001270 case MESSAGE_BLUETOOTH_STATE_CHANGE:
fredc0f420372012-04-12 00:02:00 -07001271 {
fredcbf072a72012-05-09 16:52:50 -07001272 int prevState = msg.arg1;
1273 int newState = msg.arg2;
Jeff Sharkey67609c72016-03-05 14:29:13 -07001274 if (DBG) Slog.d(TAG, "MESSAGE_BLUETOOTH_STATE_CHANGE: prevState = " + prevState + ", newState=" + newState);
Zhihai Xu40874a02012-10-08 17:57:03 -07001275 mState = newState;
1276 bluetoothStateChangeHandler(prevState, newState);
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001277 // handle error state transition case from TURNING_ON to OFF
1278 // unbind and rebind bluetooth service and enable bluetooth
Nitin Arorad055adb2015-03-02 15:03:51 -08001279 if ((prevState == BluetoothAdapter.STATE_BLE_TURNING_ON) &&
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001280 (newState == BluetoothAdapter.STATE_OFF) &&
1281 (mBluetooth != null) && mEnable) {
1282 recoverBluetoothServiceFromError();
1283 }
Nitin Arorad055adb2015-03-02 15:03:51 -08001284 if ((prevState == BluetoothAdapter.STATE_TURNING_ON) &&
1285 (newState == BluetoothAdapter.STATE_BLE_ON) &&
1286 (mBluetooth != null) && mEnable) {
1287 recoverBluetoothServiceFromError();
1288 }
1289 if (newState == BluetoothAdapter.STATE_ON ||
1290 newState == BluetoothAdapter.STATE_BLE_ON) {
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001291 // bluetooth is working, reset the counter
1292 if (mErrorRecoveryRetryCounter != 0) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001293 Slog.w(TAG, "bluetooth is recovered from error");
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001294 mErrorRecoveryRetryCounter = 0;
1295 }
1296 }
fredc649fe492012-04-19 01:07:18 -07001297 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001298 }
fredc0f420372012-04-12 00:02:00 -07001299 case MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED:
1300 {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001301 Slog.e(TAG, "MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED: " + msg.arg1);
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301302 synchronized(mConnection) {
Matthew Xieddf7e472013-03-01 18:41:02 -08001303 if (msg.arg1 == SERVICE_IBLUETOOTH) {
1304 // if service is unbinded already, do nothing and return
1305 if (mBluetooth == null) break;
1306 mBluetooth = null;
1307 } else if (msg.arg1 == SERVICE_IBLUETOOTHGATT) {
1308 mBluetoothGatt = null;
1309 break;
1310 } else {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001311 Slog.e(TAG, "Bad msg.arg1: " + msg.arg1);
Matthew Xieddf7e472013-03-01 18:41:02 -08001312 break;
1313 }
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301314 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001315
1316 if (mEnable) {
1317 mEnable = false;
1318 // Send a Bluetooth Restart message
1319 Message restartMsg = mHandler.obtainMessage(
1320 MESSAGE_RESTART_BLUETOOTH_SERVICE);
1321 mHandler.sendMessageDelayed(restartMsg,
1322 SERVICE_RESTART_TIME_MS);
1323 }
1324
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001325 sendBluetoothServiceDownCallback();
Zhihai Xu40874a02012-10-08 17:57:03 -07001326
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001327 // Send BT state broadcast to update
1328 // the BT icon correctly
1329 if ((mState == BluetoothAdapter.STATE_TURNING_ON) ||
1330 (mState == BluetoothAdapter.STATE_ON)) {
1331 bluetoothStateChangeHandler(BluetoothAdapter.STATE_ON,
1332 BluetoothAdapter.STATE_TURNING_OFF);
1333 mState = BluetoothAdapter.STATE_TURNING_OFF;
Zhihai Xu40874a02012-10-08 17:57:03 -07001334 }
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001335 if (mState == BluetoothAdapter.STATE_TURNING_OFF) {
1336 bluetoothStateChangeHandler(BluetoothAdapter.STATE_TURNING_OFF,
1337 BluetoothAdapter.STATE_OFF);
1338 }
1339
1340 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
1341 mState = BluetoothAdapter.STATE_OFF;
fredc649fe492012-04-19 01:07:18 -07001342 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001343 }
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301344 case MESSAGE_RESTART_BLUETOOTH_SERVICE:
1345 {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001346 Slog.d(TAG, "MESSAGE_RESTART_BLUETOOTH_SERVICE:"
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301347 +" Restart IBluetooth service");
1348 /* Enable without persisting the setting as
1349 it doesnt change when IBluetooth
1350 service restarts */
Zhihai Xu40874a02012-10-08 17:57:03 -07001351 mEnable = true;
Zhihai Xu401202b2012-12-03 11:36:21 -08001352 handleEnable(mQuietEnable);
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301353 break;
1354 }
1355
fredc0f420372012-04-12 00:02:00 -07001356 case MESSAGE_TIMEOUT_UNBIND:
1357 {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001358 Slog.e(TAG, "MESSAGE_TIMEOUT_UNBIND");
fredc0f420372012-04-12 00:02:00 -07001359 synchronized(mConnection) {
1360 mUnbinding = false;
1361 }
fredc649fe492012-04-19 01:07:18 -07001362 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001363 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001364
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001365 case MESSAGE_USER_SWITCHED: {
1366 if (DBG) Slog.d(TAG, "MESSAGE_USER_SWITCHED");
Zhihai Xu40874a02012-10-08 17:57:03 -07001367 mHandler.removeMessages(MESSAGE_USER_SWITCHED);
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001368
Zhihai Xu40874a02012-10-08 17:57:03 -07001369 /* disable and enable BT when detect a user switch */
1370 if (mEnable && mBluetooth != null) {
1371 synchronized (mConnection) {
1372 if (mBluetooth != null) {
1373 //Unregister callback object
1374 try {
1375 mBluetooth.unregisterCallback(mBluetoothCallback);
1376 } catch (RemoteException re) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001377 Slog.e(TAG, "Unable to unregister",re);
Zhihai Xu40874a02012-10-08 17:57:03 -07001378 }
1379 }
1380 }
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001381
1382 if (mState == BluetoothAdapter.STATE_TURNING_OFF) {
1383 // MESSAGE_USER_SWITCHED happened right after MESSAGE_ENABLE
1384 bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_OFF);
1385 mState = BluetoothAdapter.STATE_OFF;
1386 }
1387 if (mState == BluetoothAdapter.STATE_OFF) {
1388 bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_TURNING_ON);
1389 mState = BluetoothAdapter.STATE_TURNING_ON;
1390 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001391
1392 waitForOnOff(true, false);
1393
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001394 if (mState == BluetoothAdapter.STATE_TURNING_ON) {
1395 bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_ON);
1396 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001397
Benjamin Franze8b98922014-11-12 15:57:54 +00001398 unbindAllBluetoothProfileServices();
Zhihai Xu40874a02012-10-08 17:57:03 -07001399 // disable
Zhihai Xu401202b2012-12-03 11:36:21 -08001400 handleDisable();
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001401 // Pbap service need receive STATE_TURNING_OFF intent to close
1402 bluetoothStateChangeHandler(BluetoothAdapter.STATE_ON,
1403 BluetoothAdapter.STATE_TURNING_OFF);
Zhihai Xu40874a02012-10-08 17:57:03 -07001404
1405 waitForOnOff(false, true);
1406
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001407 bluetoothStateChangeHandler(BluetoothAdapter.STATE_TURNING_OFF,
Zhihai Xu40874a02012-10-08 17:57:03 -07001408 BluetoothAdapter.STATE_OFF);
Zhihai Xu40874a02012-10-08 17:57:03 -07001409 sendBluetoothServiceDownCallback();
1410 synchronized (mConnection) {
1411 if (mBluetooth != null) {
1412 mBluetooth = null;
1413 //Unbind
1414 mContext.unbindService(mConnection);
1415 }
Pavlin Radoslavov29b8c4a2015-08-03 17:44:47 -07001416 mBluetoothGatt = null;
Zhihai Xu40874a02012-10-08 17:57:03 -07001417 }
1418 SystemClock.sleep(100);
1419
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001420 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
1421 mState = BluetoothAdapter.STATE_OFF;
Zhihai Xu40874a02012-10-08 17:57:03 -07001422 // enable
Zhihai Xu401202b2012-12-03 11:36:21 -08001423 handleEnable(mQuietEnable);
John Spurlock8a985d22014-02-25 09:40:05 -05001424 } else if (mBinding || mBluetooth != null) {
Zhihai Xu40874a02012-10-08 17:57:03 -07001425 Message userMsg = mHandler.obtainMessage(MESSAGE_USER_SWITCHED);
1426 userMsg.arg2 = 1 + msg.arg2;
1427 // if user is switched when service is being binding
1428 // delay sending MESSAGE_USER_SWITCHED
1429 mHandler.sendMessageDelayed(userMsg, USER_SWITCHED_TIME_MS);
1430 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001431 Slog.d(TAG, "delay MESSAGE_USER_SWITCHED " + userMsg.arg2);
Zhihai Xu40874a02012-10-08 17:57:03 -07001432 }
John Spurlock8a985d22014-02-25 09:40:05 -05001433 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001434 break;
1435 }
Jeff Sharkeyaacb89e2016-03-05 14:42:58 -07001436 case MESSAGE_USER_UNLOCKED: {
1437 if (DBG) Slog.d(TAG, "MESSAGE_USER_UNLOCKED");
1438 mHandler.removeMessages(MESSAGE_USER_SWITCHED);
1439
1440 synchronized (mConnection) {
1441 if (mEnable && !mBinding && (mBluetooth == null)) {
1442 // We should be connected, but we gave up for some
1443 // reason; maybe the Bluetooth service wasn't encryption
1444 // aware, so try binding again.
1445 if (DBG) Slog.d(TAG, "Enabled but not bound; retrying after unlock");
1446 handleEnable(mQuietEnable);
1447 }
1448 }
1449 }
fredc0f420372012-04-12 00:02:00 -07001450 }
1451 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001452 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001453
Zhihai Xu401202b2012-12-03 11:36:21 -08001454 private void handleEnable(boolean quietMode) {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001455 mQuietEnable = quietMode;
1456
Matthew Xiecdce0b92012-07-12 19:06:15 -07001457 synchronized(mConnection) {
Zhihai Xu40874a02012-10-08 17:57:03 -07001458 if ((mBluetooth == null) && (!mBinding)) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001459 //Start bind timeout and bind
1460 Message timeoutMsg=mHandler.obtainMessage(MESSAGE_TIMEOUT_BIND);
1461 mHandler.sendMessageDelayed(timeoutMsg,TIMEOUT_BIND_MS);
Matthew Xiecdce0b92012-07-12 19:06:15 -07001462 Intent i = new Intent(IBluetooth.class.getName());
Dianne Hackbornce09f5a2014-10-10 15:03:13 -07001463 if (!doBind(i, mConnection,Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT,
1464 UserHandle.CURRENT)) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001465 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
Zhihai Xu40874a02012-10-08 17:57:03 -07001466 } else {
1467 mBinding = true;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001468 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001469 } else if (mBluetooth != null) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001470 //Enable bluetooth
1471 try {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001472 if (!mQuietEnable) {
1473 if(!mBluetooth.enable()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001474 Slog.e(TAG,"IBluetooth.enable() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001475 }
1476 }
1477 else {
1478 if(!mBluetooth.enableNoAutoConnect()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001479 Slog.e(TAG,"IBluetooth.enableNoAutoConnect() returned false");
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001480 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001481 }
1482 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001483 Slog.e(TAG,"Unable to call enable()",e);
Matthew Xiecdce0b92012-07-12 19:06:15 -07001484 }
1485 }
1486 }
1487 }
1488
Dianne Hackborn221ea892013-08-04 16:50:16 -07001489 boolean doBind(Intent intent, ServiceConnection conn, int flags, UserHandle user) {
1490 ComponentName comp = intent.resolveSystemService(mContext.getPackageManager(), 0);
1491 intent.setComponent(comp);
1492 if (comp == null || !mContext.bindServiceAsUser(intent, conn, flags, user)) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001493 Slog.e(TAG, "Fail to bind to: " + intent);
Dianne Hackborn221ea892013-08-04 16:50:16 -07001494 return false;
1495 }
1496 return true;
1497 }
1498
Zhihai Xu401202b2012-12-03 11:36:21 -08001499 private void handleDisable() {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001500 synchronized(mConnection) {
Andre Eisenbach305fdab2015-11-11 21:43:26 -08001501 if (mBluetooth != null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001502 if (DBG) Slog.d(TAG,"Sending off request.");
Matthew Xiecdce0b92012-07-12 19:06:15 -07001503
1504 try {
1505 if(!mBluetooth.disable()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001506 Slog.e(TAG,"IBluetooth.disable() returned false");
Matthew Xiecdce0b92012-07-12 19:06:15 -07001507 }
1508 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001509 Slog.e(TAG,"Unable to call disable()",e);
Matthew Xiecdce0b92012-07-12 19:06:15 -07001510 }
1511 }
1512 }
1513 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001514
1515 private boolean checkIfCallerIsForegroundUser() {
1516 int foregroundUser;
1517 int callingUser = UserHandle.getCallingUserId();
Martijn Coenen8385c5a2012-11-29 10:14:16 -08001518 int callingUid = Binder.getCallingUid();
Zhihai Xu40874a02012-10-08 17:57:03 -07001519 long callingIdentity = Binder.clearCallingIdentity();
Benjamin Franze8b98922014-11-12 15:57:54 +00001520 UserManager um = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
1521 UserInfo ui = um.getProfileParent(callingUser);
1522 int parentUser = (ui != null) ? ui.id : UserHandle.USER_NULL;
Martijn Coenen8385c5a2012-11-29 10:14:16 -08001523 int callingAppId = UserHandle.getAppId(callingUid);
Zhihai Xu40874a02012-10-08 17:57:03 -07001524 boolean valid = false;
1525 try {
1526 foregroundUser = ActivityManager.getCurrentUser();
Martijn Coenen8385c5a2012-11-29 10:14:16 -08001527 valid = (callingUser == foregroundUser) ||
Benjamin Franze8b98922014-11-12 15:57:54 +00001528 parentUser == foregroundUser ||
Adrian Roosbd9a9a52014-08-18 15:31:57 +02001529 callingAppId == Process.NFC_UID ||
1530 callingAppId == mSystemUiUid;
Zhihai Xu40874a02012-10-08 17:57:03 -07001531 if (DBG) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001532 Slog.d(TAG, "checkIfCallerIsForegroundUser: valid=" + valid
Zhihai Xu40874a02012-10-08 17:57:03 -07001533 + " callingUser=" + callingUser
Benjamin Franze8b98922014-11-12 15:57:54 +00001534 + " parentUser=" + parentUser
Zhihai Xu40874a02012-10-08 17:57:03 -07001535 + " foregroundUser=" + foregroundUser);
1536 }
1537 } finally {
1538 Binder.restoreCallingIdentity(callingIdentity);
1539 }
1540 return valid;
1541 }
1542
Nitin Arorad055adb2015-03-02 15:03:51 -08001543 private void sendBleStateChanged(int prevState, int newState) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001544 if (DBG) Slog.d(TAG,"BLE State Change Intent: " + prevState + " -> " + newState);
Nitin Arorad055adb2015-03-02 15:03:51 -08001545 // Send broadcast message to everyone else
1546 Intent intent = new Intent(BluetoothAdapter.ACTION_BLE_STATE_CHANGED);
1547 intent.putExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE, prevState);
1548 intent.putExtra(BluetoothAdapter.EXTRA_STATE, newState);
1549 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1550 mContext.sendBroadcastAsUser(intent, UserHandle.ALL, BLUETOOTH_PERM);
1551 }
1552
Zhihai Xu40874a02012-10-08 17:57:03 -07001553 private void bluetoothStateChangeHandler(int prevState, int newState) {
Nitin Arorad055adb2015-03-02 15:03:51 -08001554 boolean isStandardBroadcast = true;
Zhihai Xu40874a02012-10-08 17:57:03 -07001555 if (prevState != newState) {
1556 //Notify all proxy objects first of adapter state change
Nitin Arorad055adb2015-03-02 15:03:51 -08001557 if (newState == BluetoothAdapter.STATE_BLE_ON
1558 || newState == BluetoothAdapter.STATE_OFF) {
1559 boolean intermediate_off = (prevState == BluetoothAdapter.STATE_TURNING_OFF
1560 && newState == BluetoothAdapter.STATE_BLE_ON);
Zhihai Xu40874a02012-10-08 17:57:03 -07001561
Nitin Arorad055adb2015-03-02 15:03:51 -08001562 if (newState == BluetoothAdapter.STATE_OFF) {
1563 // If Bluetooth is off, send service down event to proxy objects, and unbind
Jeff Sharkey67609c72016-03-05 14:29:13 -07001564 if (DBG) Slog.d(TAG, "Bluetooth is complete turn off");
Nitin Arorad055adb2015-03-02 15:03:51 -08001565 if (canUnbindBluetoothService()) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001566 if (DBG) Slog.d(TAG, "Good to unbind!");
Matthew Xieddf7e472013-03-01 18:41:02 -08001567 sendBluetoothServiceDownCallback();
1568 unbindAndFinish();
Nitin Arorad055adb2015-03-02 15:03:51 -08001569 sendBleStateChanged(prevState, newState);
1570 // Don't broadcast as it has already been broadcast before
1571 isStandardBroadcast = false;
Matthew Xieddf7e472013-03-01 18:41:02 -08001572 }
Nitin Arorad055adb2015-03-02 15:03:51 -08001573
1574 } else if (!intermediate_off) {
1575 // connect to GattService
Jeff Sharkey67609c72016-03-05 14:29:13 -07001576 if (DBG) Slog.d(TAG, "Bluetooth is in LE only mode");
Nitin Arorad055adb2015-03-02 15:03:51 -08001577 if (mBluetoothGatt != null) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001578 if (DBG) Slog.d(TAG, "Calling BluetoothGattServiceUp");
Nitin Arorad055adb2015-03-02 15:03:51 -08001579 onBluetoothGattServiceUp();
1580 } else {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001581 if (DBG) Slog.d(TAG, "Binding Bluetooth GATT service");
Nitin Arorad055adb2015-03-02 15:03:51 -08001582 if (mContext.getPackageManager().hasSystemFeature(
1583 PackageManager.FEATURE_BLUETOOTH_LE)) {
1584 Intent i = new Intent(IBluetoothGatt.class.getName());
1585 doBind(i, mConnection, Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT, UserHandle.CURRENT);
1586 }
1587 }
1588 sendBleStateChanged(prevState, newState);
1589 //Don't broadcase this as std intent
1590 isStandardBroadcast = false;
1591
1592 } else if (intermediate_off){
Jeff Sharkey67609c72016-03-05 14:29:13 -07001593 if (DBG) Slog.d(TAG, "Intermediate off, back to LE only mode");
Nitin Arorad055adb2015-03-02 15:03:51 -08001594 // For LE only mode, broadcast as is
1595 sendBleStateChanged(prevState, newState);
1596 sendBluetoothStateCallback(false); // BT is OFF for general users
1597 // Broadcast as STATE_OFF
1598 newState = BluetoothAdapter.STATE_OFF;
1599 sendBrEdrDownCallback();
Zhihai Xu40874a02012-10-08 17:57:03 -07001600 }
Nitin Arorad055adb2015-03-02 15:03:51 -08001601 } else if (newState == BluetoothAdapter.STATE_ON) {
1602 boolean isUp = (newState==BluetoothAdapter.STATE_ON);
1603 sendBluetoothStateCallback(isUp);
1604 sendBleStateChanged(prevState, newState);
1605
1606 } else if (newState == BluetoothAdapter.STATE_BLE_TURNING_ON
1607 || newState == BluetoothAdapter.STATE_BLE_TURNING_OFF ) {
1608 sendBleStateChanged(prevState, newState);
1609 isStandardBroadcast = false;
1610
1611 } else if (newState == BluetoothAdapter.STATE_TURNING_ON
1612 || newState == BluetoothAdapter.STATE_TURNING_OFF) {
1613 sendBleStateChanged(prevState, newState);
Zhihai Xu40874a02012-10-08 17:57:03 -07001614 }
1615
Nitin Arorad055adb2015-03-02 15:03:51 -08001616 if (isStandardBroadcast) {
1617 if (prevState == BluetoothAdapter.STATE_BLE_ON) {
1618 // Show prevState of BLE_ON as OFF to standard users
1619 prevState = BluetoothAdapter.STATE_OFF;
1620 }
1621 Intent intent = new Intent(BluetoothAdapter.ACTION_STATE_CHANGED);
1622 intent.putExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE, prevState);
1623 intent.putExtra(BluetoothAdapter.EXTRA_STATE, newState);
1624 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1625 mContext.sendBroadcastAsUser(intent, UserHandle.ALL, BLUETOOTH_PERM);
1626 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001627 }
1628 }
1629
1630 /**
1631 * if on is true, wait for state become ON
1632 * if off is true, wait for state become OFF
1633 * if both on and off are false, wait for state not ON
1634 */
1635 private boolean waitForOnOff(boolean on, boolean off) {
1636 int i = 0;
1637 while (i < 10) {
1638 synchronized(mConnection) {
1639 try {
1640 if (mBluetooth == null) break;
1641 if (on) {
1642 if (mBluetooth.getState() == BluetoothAdapter.STATE_ON) return true;
1643 } else if (off) {
1644 if (mBluetooth.getState() == BluetoothAdapter.STATE_OFF) return true;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07001645 } else {
Zhihai Xu40874a02012-10-08 17:57:03 -07001646 if (mBluetooth.getState() != BluetoothAdapter.STATE_ON) return true;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07001647 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001648 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001649 Slog.e(TAG, "getState()", e);
Zhihai Xu40874a02012-10-08 17:57:03 -07001650 break;
1651 }
1652 }
1653 if (on || off) {
1654 SystemClock.sleep(300);
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07001655 } else {
Zhihai Xu40874a02012-10-08 17:57:03 -07001656 SystemClock.sleep(50);
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07001657 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001658 i++;
1659 }
Jeff Sharkey67609c72016-03-05 14:29:13 -07001660 Slog.e(TAG,"waitForOnOff time out");
Zhihai Xu40874a02012-10-08 17:57:03 -07001661 return false;
1662 }
Zhihai Xu681ae7f2012-11-12 15:14:18 -08001663
Zhihai Xu401202b2012-12-03 11:36:21 -08001664 private void sendDisableMsg() {
1665 mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_DISABLE));
1666 }
1667
1668 private void sendEnableMsg(boolean quietMode) {
1669 mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_ENABLE,
1670 quietMode ? 1 : 0, 0));
1671 }
1672
Zhihai Xu681ae7f2012-11-12 15:14:18 -08001673 private boolean canUnbindBluetoothService() {
1674 synchronized(mConnection) {
1675 //Only unbind with mEnable flag not set
1676 //For race condition: disable and enable back-to-back
1677 //Avoid unbind right after enable due to callback from disable
1678 //Only unbind with Bluetooth at OFF state
1679 //Only unbind without any MESSAGE_BLUETOOTH_STATE_CHANGE message
1680 try {
1681 if (mEnable || (mBluetooth == null)) return false;
1682 if (mHandler.hasMessages(MESSAGE_BLUETOOTH_STATE_CHANGE)) return false;
1683 return (mBluetooth.getState() == BluetoothAdapter.STATE_OFF);
1684 } catch (RemoteException e) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001685 Slog.e(TAG, "getState()", e);
Zhihai Xu681ae7f2012-11-12 15:14:18 -08001686 }
1687 }
1688 return false;
1689 }
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001690
1691 private void recoverBluetoothServiceFromError() {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001692 Slog.e(TAG,"recoverBluetoothServiceFromError");
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001693 synchronized (mConnection) {
1694 if (mBluetooth != null) {
1695 //Unregister callback object
1696 try {
1697 mBluetooth.unregisterCallback(mBluetoothCallback);
1698 } catch (RemoteException re) {
Jeff Sharkey67609c72016-03-05 14:29:13 -07001699 Slog.e(TAG, "Unable to unregister",re);
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001700 }
1701 }
1702 }
1703
1704 SystemClock.sleep(500);
1705
1706 // disable
1707 handleDisable();
1708
1709 waitForOnOff(false, true);
1710
1711 sendBluetoothServiceDownCallback();
1712 synchronized (mConnection) {
1713 if (mBluetooth != null) {
1714 mBluetooth = null;
1715 //Unbind
1716 mContext.unbindService(mConnection);
1717 }
Pavlin Radoslavov29b8c4a2015-08-03 17:44:47 -07001718 mBluetoothGatt = null;
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001719 }
1720
1721 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
1722 mState = BluetoothAdapter.STATE_OFF;
1723
1724 mEnable = false;
1725
1726 if (mErrorRecoveryRetryCounter++ < MAX_ERROR_RESTART_RETRIES) {
1727 // Send a Bluetooth Restart message to reenable bluetooth
1728 Message restartMsg = mHandler.obtainMessage(
1729 MESSAGE_RESTART_BLUETOOTH_SERVICE);
1730 mHandler.sendMessageDelayed(restartMsg, ERROR_RESTART_TIME_MS);
1731 } else {
1732 // todo: notify user to power down and power up phone to make bluetooth work.
1733 }
1734 }
Mike Lockwood726d4de2014-10-28 14:06:28 -07001735
1736 @Override
Pavlin Radoslavov6e8faff2016-02-23 11:54:37 -08001737 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1738 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DUMP, TAG);
1739 String errorMsg = null;
1740 if (mBluetoothBinder == null) {
1741 errorMsg = "Bluetooth Service not connected";
1742 } else {
1743 try {
1744 mBluetoothBinder.dump(fd, args);
1745 } catch (RemoteException re) {
1746 errorMsg = "RemoteException while calling Bluetooth Service";
1747 }
Mike Lockwood726d4de2014-10-28 14:06:28 -07001748 }
Pavlin Radoslavov6e8faff2016-02-23 11:54:37 -08001749 if (errorMsg != null) {
1750 // Silently return if we are extracting metrics in Protobuf format
1751 if ((args.length > 0) && args[0].startsWith("--proto"))
1752 return;
1753 writer.println(errorMsg);
1754 }
Mike Lockwood726d4de2014-10-28 14:06:28 -07001755 }
fredc0f420372012-04-12 00:02:00 -07001756}