blob: fd67b4148b8907d8cb0739cc132dab60d0a82788 [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;
Sharvil Nanavati7c250052015-06-20 12:05:52 -070022import android.bluetooth.BluetoothDevice;
Benjamin Franze8b98922014-11-12 15:57:54 +000023import android.bluetooth.BluetoothProfile;
fredc0f420372012-04-12 00:02:00 -070024import android.bluetooth.IBluetooth;
fredcbf072a72012-05-09 16:52:50 -070025import android.bluetooth.IBluetoothCallback;
Wei Wange4a744b2015-06-11 17:50:29 -070026import android.bluetooth.IBluetoothGatt;
Benjamin Franze8b98922014-11-12 15:57:54 +000027import android.bluetooth.IBluetoothHeadset;
fredc0f420372012-04-12 00:02:00 -070028import android.bluetooth.IBluetoothManager;
29import android.bluetooth.IBluetoothManagerCallback;
Benjamin Franze8b98922014-11-12 15:57:54 +000030import android.bluetooth.IBluetoothProfileServiceConnection;
fredc0f420372012-04-12 00:02:00 -070031import android.bluetooth.IBluetoothStateChangeCallback;
fredc0f420372012-04-12 00:02:00 -070032import android.content.BroadcastReceiver;
33import android.content.ComponentName;
34import android.content.ContentResolver;
35import android.content.Context;
36import android.content.Intent;
37import android.content.IntentFilter;
38import android.content.ServiceConnection;
Matthew Xie32ab77b2013-05-08 19:26:57 -070039import android.content.pm.PackageManager;
Benjamin Franze8b98922014-11-12 15:57:54 +000040import android.content.pm.UserInfo;
Wei Wange4a744b2015-06-11 17:50:29 -070041import android.database.ContentObserver;
Zhihai Xu40874a02012-10-08 17:57:03 -070042import android.os.Binder;
fredc0f420372012-04-12 00:02:00 -070043import android.os.Handler;
fredc0f420372012-04-12 00:02:00 -070044import android.os.IBinder;
Zhihai Xu40874a02012-10-08 17:57:03 -070045import android.os.Looper;
fredc0f420372012-04-12 00:02:00 -070046import android.os.Message;
Andre Eisenbach14dcb5f2014-12-05 09:31:30 -080047import android.os.ParcelFileDescriptor;
Zhihai Xu40874a02012-10-08 17:57:03 -070048import android.os.Process;
fredcd6883532012-04-25 17:46:13 -070049import android.os.RemoteCallbackList;
fredc0f420372012-04-12 00:02:00 -070050import android.os.RemoteException;
Zhihai Xu40874a02012-10-08 17:57:03 -070051import android.os.SystemClock;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070052import android.os.UserHandle;
Benjamin Franze8b98922014-11-12 15:57:54 +000053import android.os.UserManager;
fredc0f420372012-04-12 00:02:00 -070054import android.provider.Settings;
Wei Wang67d84162015-04-26 17:04:29 -070055import android.provider.Settings.SettingNotFoundException;
fredc0f420372012-04-12 00:02:00 -070056import android.util.Log;
Mike Lockwood726d4de2014-10-28 14:06:28 -070057
58import java.io.FileDescriptor;
Andre Eisenbach14dcb5f2014-12-05 09:31:30 -080059import java.io.IOException;
Mike Lockwood726d4de2014-10-28 14:06:28 -070060import java.io.PrintWriter;
Benjamin Franze8b98922014-11-12 15:57:54 +000061import java.util.HashMap;
62import java.util.Map;
Miao Chou658bf2f2015-06-26 17:14:35 -070063
fredc0f420372012-04-12 00:02:00 -070064class BluetoothManagerService extends IBluetoothManager.Stub {
65 private static final String TAG = "BluetoothManagerService";
Pavlin Radoslavovb5a479c2015-06-20 22:55:04 -070066 private static final boolean DBG = false;
fredc0f420372012-04-12 00:02:00 -070067
fredc0f420372012-04-12 00:02:00 -070068 private static final String BLUETOOTH_ADMIN_PERM = android.Manifest.permission.BLUETOOTH_ADMIN;
69 private static final String BLUETOOTH_PERM = android.Manifest.permission.BLUETOOTH;
fredc0f420372012-04-12 00:02:00 -070070 private static final String ACTION_SERVICE_STATE_CHANGED="com.android.bluetooth.btservice.action.STATE_CHANGED";
71 private static final String EXTRA_ACTION="action";
Zhihai Xud31c3222012-10-31 16:08:57 -070072 private static final String SECURE_SETTINGS_BLUETOOTH_ADDR_VALID="bluetooth_addr_valid";
fredc0f420372012-04-12 00:02:00 -070073 private static final String SECURE_SETTINGS_BLUETOOTH_ADDRESS="bluetooth_address";
74 private static final String SECURE_SETTINGS_BLUETOOTH_NAME="bluetooth_name";
fredc0f420372012-04-12 00:02:00 -070075 private static final int TIMEOUT_BIND_MS = 3000; //Maximum msec to wait for a bind
76 private static final int TIMEOUT_SAVE_MS = 500; //Maximum msec to wait for a save
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +053077 //Maximum msec to wait for service restart
78 private static final int SERVICE_RESTART_TIME_MS = 200;
Zhihai Xudd9d17d2013-01-08 17:05:58 -080079 //Maximum msec to wait for restart due to error
80 private static final int ERROR_RESTART_TIME_MS = 3000;
Zhihai Xu40874a02012-10-08 17:57:03 -070081 //Maximum msec to delay MESSAGE_USER_SWITCHED
82 private static final int USER_SWITCHED_TIME_MS = 200;
Benjamin Franze8b98922014-11-12 15:57:54 +000083 // Delay for the addProxy function in msec
84 private static final int ADD_PROXY_DELAY_MS = 100;
fredc0f420372012-04-12 00:02:00 -070085
86 private static final int MESSAGE_ENABLE = 1;
87 private static final int MESSAGE_DISABLE = 2;
fredc649fe492012-04-19 01:07:18 -070088 private static final int MESSAGE_REGISTER_ADAPTER = 20;
89 private static final int MESSAGE_UNREGISTER_ADAPTER = 21;
90 private static final int MESSAGE_REGISTER_STATE_CHANGE_CALLBACK = 30;
91 private static final int MESSAGE_UNREGISTER_STATE_CHANGE_CALLBACK = 31;
92 private static final int MESSAGE_BLUETOOTH_SERVICE_CONNECTED = 40;
93 private static final int MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED = 41;
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +053094 private static final int MESSAGE_RESTART_BLUETOOTH_SERVICE = 42;
fredcbf072a72012-05-09 16:52:50 -070095 private static final int MESSAGE_BLUETOOTH_STATE_CHANGE=60;
fredc0f420372012-04-12 00:02:00 -070096 private static final int MESSAGE_TIMEOUT_BIND =100;
97 private static final int MESSAGE_TIMEOUT_UNBIND =101;
98 private static final int MESSAGE_GET_NAME_AND_ADDRESS=200;
99 private static final int MESSAGE_SAVE_NAME_AND_ADDRESS=201;
Zhihai Xu40874a02012-10-08 17:57:03 -0700100 private static final int MESSAGE_USER_SWITCHED = 300;
Benjamin Franze8b98922014-11-12 15:57:54 +0000101 private static final int MESSAGE_ADD_PROXY_DELAYED = 400;
102 private static final int MESSAGE_BIND_PROFILE_SERVICE = 401;
fredc0f420372012-04-12 00:02:00 -0700103 private static final int MAX_SAVE_RETRIES=3;
Zhihai Xudd9d17d2013-01-08 17:05:58 -0800104 private static final int MAX_ERROR_RESTART_RETRIES=6;
105
Zhihai Xu401202b2012-12-03 11:36:21 -0800106 // Bluetooth persisted setting is off
107 private static final int BLUETOOTH_OFF=0;
108 // Bluetooth persisted setting is on
109 // and Airplane mode won't affect Bluetooth state at start up
110 private static final int BLUETOOTH_ON_BLUETOOTH=1;
111 // Bluetooth persisted setting is on
112 // but Airplane mode will affect Bluetooth state at start up
113 // and Airplane mode will have higher priority.
114 private static final int BLUETOOTH_ON_AIRPLANE=2;
fredc0f420372012-04-12 00:02:00 -0700115
Matthew Xieddf7e472013-03-01 18:41:02 -0800116 private static final int SERVICE_IBLUETOOTH = 1;
117 private static final int SERVICE_IBLUETOOTHGATT = 2;
118
Sharvil Nanavati7c250052015-06-20 12:05:52 -0700119 private static final String[] DEVICE_TYPE_NAMES = new String[] {
120 "???",
121 "BR/EDR",
122 "LE",
123 "DUAL"
124 };
125
fredc0f420372012-04-12 00:02:00 -0700126 private final Context mContext;
Nitin Arorad055adb2015-03-02 15:03:51 -0800127 private static int mBleAppCount = 0;
Matthew Xiecdce0b92012-07-12 19:06:15 -0700128
129 // Locks are not provided for mName and mAddress.
130 // They are accessed in handler or broadcast receiver, same thread context.
fredc0f420372012-04-12 00:02:00 -0700131 private String mAddress;
132 private String mName;
Matthew Xie6fde3092012-07-11 17:10:07 -0700133 private final ContentResolver mContentResolver;
134 private final RemoteCallbackList<IBluetoothManagerCallback> mCallbacks;
135 private final RemoteCallbackList<IBluetoothStateChangeCallback> mStateChangeCallbacks;
fredc649fe492012-04-19 01:07:18 -0700136 private IBluetooth mBluetooth;
Matthew Xieddf7e472013-03-01 18:41:02 -0800137 private IBluetoothGatt mBluetoothGatt;
fredc649fe492012-04-19 01:07:18 -0700138 private boolean mBinding;
139 private boolean mUnbinding;
Zhihai Xu401202b2012-12-03 11:36:21 -0800140 // used inside handler thread
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700141 private boolean mQuietEnable = false;
Zhihai Xu401202b2012-12-03 11:36:21 -0800142 // configuarion from external IBinder call which is used to
143 // synchronize with broadcast receiver.
144 private boolean mQuietEnableExternal;
145 // configuarion from external IBinder call which is used to
146 // synchronize with broadcast receiver.
147 private boolean mEnableExternal;
148 // used inside handler thread
Zhihai Xu40874a02012-10-08 17:57:03 -0700149 private boolean mEnable;
150 private int mState;
Zhihai Xu40874a02012-10-08 17:57:03 -0700151 private final BluetoothHandler mHandler;
Zhihai Xudd9d17d2013-01-08 17:05:58 -0800152 private int mErrorRecoveryRetryCounter;
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200153 private final int mSystemUiUid;
fredc0f420372012-04-12 00:02:00 -0700154
Benjamin Franze8b98922014-11-12 15:57:54 +0000155 // Save a ProfileServiceConnections object for each of the bound
156 // bluetooth profile services
157 private final Map <Integer, ProfileServiceConnections> mProfileServices =
158 new HashMap <Integer, ProfileServiceConnections>();
159
fredc649fe492012-04-19 01:07:18 -0700160 private void registerForAirplaneMode(IntentFilter filter) {
161 final ContentResolver resolver = mContext.getContentResolver();
Christopher Tatec09cdce2012-09-10 16:50:14 -0700162 final String airplaneModeRadios = Settings.Global.getString(resolver,
163 Settings.Global.AIRPLANE_MODE_RADIOS);
164 final String toggleableRadios = Settings.Global.getString(resolver,
165 Settings.Global.AIRPLANE_MODE_TOGGLEABLE_RADIOS);
fredc649fe492012-04-19 01:07:18 -0700166 boolean mIsAirplaneSensitive = airplaneModeRadios == null ? true :
Christopher Tatec09cdce2012-09-10 16:50:14 -0700167 airplaneModeRadios.contains(Settings.Global.RADIO_BLUETOOTH);
fredc649fe492012-04-19 01:07:18 -0700168 if (mIsAirplaneSensitive) {
169 filter.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED);
170 }
171 }
172
fredcbf072a72012-05-09 16:52:50 -0700173 private final IBluetoothCallback mBluetoothCallback = new IBluetoothCallback.Stub() {
174 @Override
175 public void onBluetoothStateChange(int prevState, int newState) throws RemoteException {
176 Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_STATE_CHANGE,prevState,newState);
177 mHandler.sendMessage(msg);
178 }
179 };
180
181 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
fredc0f420372012-04-12 00:02:00 -0700182 @Override
183 public void onReceive(Context context, Intent intent) {
184 String action = intent.getAction();
fredcbf072a72012-05-09 16:52:50 -0700185 if (BluetoothAdapter.ACTION_LOCAL_NAME_CHANGED.equals(action)) {
fredc0f420372012-04-12 00:02:00 -0700186 String newName = intent.getStringExtra(BluetoothAdapter.EXTRA_LOCAL_NAME);
Freda8c6df02012-07-11 10:25:23 -0700187 if (DBG) Log.d(TAG, "Bluetooth Adapter name changed to " + newName);
fredc0f420372012-04-12 00:02:00 -0700188 if (newName != null) {
189 storeNameAndAddress(newName, null);
190 }
fredc649fe492012-04-19 01:07:18 -0700191 } else if (Intent.ACTION_AIRPLANE_MODE_CHANGED.equals(action)) {
Zhihai Xu401202b2012-12-03 11:36:21 -0800192 synchronized(mReceiver) {
193 if (isBluetoothPersistedStateOn()) {
194 if (isAirplaneModeOn()) {
195 persistBluetoothSetting(BLUETOOTH_ON_AIRPLANE);
196 } else {
197 persistBluetoothSetting(BLUETOOTH_ON_BLUETOOTH);
198 }
199 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800200
201 int st = BluetoothAdapter.STATE_OFF;
202 if (mBluetooth != null) {
203 try {
204 st = mBluetooth.getState();
205 } catch (RemoteException e) {
206 Log.e(TAG,"Unable to call getState", e);
207 }
208 }
209 Log.d(TAG, "state" + st);
210
Zhihai Xu401202b2012-12-03 11:36:21 -0800211 if (isAirplaneModeOn()) {
Nitin Arorad055adb2015-03-02 15:03:51 -0800212 // Clear registered LE apps to force shut-off
213 synchronized (this) {
214 mBleAppCount = 0;
Nitin Arora11f83882015-05-07 18:45:44 -0700215 mBleApps.clear();
Nitin Arorad055adb2015-03-02 15:03:51 -0800216 }
217 if (st == BluetoothAdapter.STATE_BLE_ON) {
218 //if state is BLE_ON make sure you trigger disableBLE part
219 try {
220 if (mBluetooth != null) {
221 mBluetooth.onBrEdrDown();
222 mEnableExternal = false;
223 }
224 } catch(RemoteException e) {
225 Log.e(TAG,"Unable to call onBrEdrDown", e);
226 }
227 } else if (st == BluetoothAdapter.STATE_ON){
228 // disable without persisting the setting
229 Log.d(TAG, "Calling disable");
230 sendDisableMsg();
231 }
Zhihai Xu401202b2012-12-03 11:36:21 -0800232 } else if (mEnableExternal) {
233 // enable without persisting the setting
Nitin Arorad055adb2015-03-02 15:03:51 -0800234 Log.d(TAG, "Calling enable");
Zhihai Xu401202b2012-12-03 11:36:21 -0800235 sendEnableMsg(mQuietEnableExternal);
236 }
fredc649fe492012-04-19 01:07:18 -0700237 }
fredc0f420372012-04-12 00:02:00 -0700238 }
239 }
240 };
241
242 BluetoothManagerService(Context context) {
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700243 mHandler = new BluetoothHandler(IoThread.get().getLooper());
Zhihai Xu40874a02012-10-08 17:57:03 -0700244
fredc0f420372012-04-12 00:02:00 -0700245 mContext = context;
246 mBluetooth = null;
Nitin Arorad055adb2015-03-02 15:03:51 -0800247 mBluetoothGatt = null;
fredc0f420372012-04-12 00:02:00 -0700248 mBinding = false;
249 mUnbinding = false;
Zhihai Xu40874a02012-10-08 17:57:03 -0700250 mEnable = false;
251 mState = BluetoothAdapter.STATE_OFF;
Zhihai Xu401202b2012-12-03 11:36:21 -0800252 mQuietEnableExternal = false;
253 mEnableExternal = false;
fredc0f420372012-04-12 00:02:00 -0700254 mAddress = null;
255 mName = null;
Zhihai Xudd9d17d2013-01-08 17:05:58 -0800256 mErrorRecoveryRetryCounter = 0;
fredc0f420372012-04-12 00:02:00 -0700257 mContentResolver = context.getContentResolver();
Wei Wange4a744b2015-06-11 17:50:29 -0700258 // Observe BLE scan only mode settings change.
259 registerForBleScanModeChange();
fredcd6883532012-04-25 17:46:13 -0700260 mCallbacks = new RemoteCallbackList<IBluetoothManagerCallback>();
261 mStateChangeCallbacks = new RemoteCallbackList<IBluetoothStateChangeCallback>();
Miao Chou658bf2f2015-06-26 17:14:35 -0700262 IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_LOCAL_NAME_CHANGED);
Matthew Xie6fde3092012-07-11 17:10:07 -0700263 registerForAirplaneMode(filter);
Dianne Hackbornd83a0962014-05-02 16:28:33 -0700264 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
Matthew Xie6fde3092012-07-11 17:10:07 -0700265 mContext.registerReceiver(mReceiver, filter);
fredc0f420372012-04-12 00:02:00 -0700266 loadStoredNameAndAddress();
Zhihai Xu401202b2012-12-03 11:36:21 -0800267 if (isBluetoothPersistedStateOn()) {
268 mEnableExternal = true;
fredc0f420372012-04-12 00:02:00 -0700269 }
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200270
271 int sysUiUid = -1;
272 try {
273 sysUiUid = mContext.getPackageManager().getPackageUid("com.android.systemui",
Xiaohui Chen7c696362015-09-16 09:56:14 -0700274 UserHandle.USER_SYSTEM);
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200275 } catch (PackageManager.NameNotFoundException e) {
Joe LaPennaacddf2b2015-09-04 12:52:42 -0700276 // Some platforms, such as wearables do not have a system ui.
277 Log.w(TAG, "Unable to resolve SystemUI's UID.", e);
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200278 }
279 mSystemUiUid = sysUiUid;
fredc0f420372012-04-12 00:02:00 -0700280 }
281
fredc649fe492012-04-19 01:07:18 -0700282 /**
283 * Returns true if airplane mode is currently on
284 */
285 private final boolean isAirplaneModeOn() {
Christopher Tatec09cdce2012-09-10 16:50:14 -0700286 return Settings.Global.getInt(mContext.getContentResolver(),
287 Settings.Global.AIRPLANE_MODE_ON, 0) == 1;
fredc649fe492012-04-19 01:07:18 -0700288 }
289
290 /**
291 * Returns true if the Bluetooth saved state is "on"
292 */
293 private final boolean isBluetoothPersistedStateOn() {
Jeff Brownbf6f6f92012-09-25 15:03:20 -0700294 return Settings.Global.getInt(mContentResolver,
Zhihai Xu401202b2012-12-03 11:36:21 -0800295 Settings.Global.BLUETOOTH_ON, 0) != BLUETOOTH_OFF;
296 }
297
298 /**
299 * Returns true if the Bluetooth saved state is BLUETOOTH_ON_BLUETOOTH
300 */
301 private final boolean isBluetoothPersistedStateOnBluetooth() {
302 return Settings.Global.getInt(mContentResolver,
303 Settings.Global.BLUETOOTH_ON, 0) == BLUETOOTH_ON_BLUETOOTH;
fredc649fe492012-04-19 01:07:18 -0700304 }
305
306 /**
307 * Save the Bluetooth on/off state
308 *
309 */
Zhihai Xu401202b2012-12-03 11:36:21 -0800310 private void persistBluetoothSetting(int value) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -0700311 Settings.Global.putInt(mContext.getContentResolver(),
312 Settings.Global.BLUETOOTH_ON,
Zhihai Xu401202b2012-12-03 11:36:21 -0800313 value);
fredc649fe492012-04-19 01:07:18 -0700314 }
315
316 /**
317 * Returns true if the Bluetooth Adapter's name and address is
318 * locally cached
319 * @return
320 */
fredc0f420372012-04-12 00:02:00 -0700321 private boolean isNameAndAddressSet() {
322 return mName !=null && mAddress!= null && mName.length()>0 && mAddress.length()>0;
323 }
324
fredc649fe492012-04-19 01:07:18 -0700325 /**
326 * Retrieve the Bluetooth Adapter's name and address and save it in
327 * in the local cache
328 */
fredc0f420372012-04-12 00:02:00 -0700329 private void loadStoredNameAndAddress() {
330 if (DBG) Log.d(TAG, "Loading stored name and address");
Zhihai Xud31c3222012-10-31 16:08:57 -0700331 if (mContext.getResources().getBoolean
332 (com.android.internal.R.bool.config_bluetooth_address_validation) &&
333 Settings.Secure.getInt(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDR_VALID, 0) == 0) {
334 // if the valid flag is not set, don't load the address and name
335 if (DBG) Log.d(TAG, "invalid bluetooth name and address stored");
336 return;
337 }
fredc0f420372012-04-12 00:02:00 -0700338 mName = Settings.Secure.getString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_NAME);
339 mAddress = Settings.Secure.getString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDRESS);
Zhihai Xud31c3222012-10-31 16:08:57 -0700340 if (DBG) Log.d(TAG, "Stored bluetooth Name=" + mName + ",Address=" + mAddress);
fredc0f420372012-04-12 00:02:00 -0700341 }
342
fredc649fe492012-04-19 01:07:18 -0700343 /**
344 * Save the Bluetooth name and address in the persistent store.
345 * Only non-null values will be saved.
346 * @param name
347 * @param address
348 */
fredc0f420372012-04-12 00:02:00 -0700349 private void storeNameAndAddress(String name, String address) {
350 if (name != null) {
351 Settings.Secure.putString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_NAME, name);
fredc0f420372012-04-12 00:02:00 -0700352 mName = name;
fredc649fe492012-04-19 01:07:18 -0700353 if (DBG) Log.d(TAG,"Stored Bluetooth name: " +
354 Settings.Secure.getString(mContentResolver,SECURE_SETTINGS_BLUETOOTH_NAME));
fredc0f420372012-04-12 00:02:00 -0700355 }
356
357 if (address != null) {
358 Settings.Secure.putString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDRESS, address);
fredc0f420372012-04-12 00:02:00 -0700359 mAddress=address;
fredc649fe492012-04-19 01:07:18 -0700360 if (DBG) Log.d(TAG,"Stored Bluetoothaddress: " +
361 Settings.Secure.getString(mContentResolver,SECURE_SETTINGS_BLUETOOTH_ADDRESS));
fredc0f420372012-04-12 00:02:00 -0700362 }
Zhihai Xud31c3222012-10-31 16:08:57 -0700363
364 if ((name != null) && (address != null)) {
365 Settings.Secure.putInt(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDR_VALID, 1);
366 }
fredc0f420372012-04-12 00:02:00 -0700367 }
368
369 public IBluetooth registerAdapter(IBluetoothManagerCallback callback){
Natalie Silvanovich55db6462014-05-01 16:12:23 -0700370 if (callback == null) {
371 Log.w(TAG, "Callback is null in registerAdapter");
372 return null;
373 }
fredc0f420372012-04-12 00:02:00 -0700374 Message msg = mHandler.obtainMessage(MESSAGE_REGISTER_ADAPTER);
375 msg.obj = callback;
376 mHandler.sendMessage(msg);
377 synchronized(mConnection) {
378 return mBluetooth;
379 }
380 }
381
382 public void unregisterAdapter(IBluetoothManagerCallback callback) {
Natalie Silvanovich55db6462014-05-01 16:12:23 -0700383 if (callback == null) {
384 Log.w(TAG, "Callback is null in unregisterAdapter");
385 return;
386 }
fredc0f420372012-04-12 00:02:00 -0700387 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
388 "Need BLUETOOTH permission");
389 Message msg = mHandler.obtainMessage(MESSAGE_UNREGISTER_ADAPTER);
390 msg.obj = callback;
391 mHandler.sendMessage(msg);
392 }
393
394 public void registerStateChangeCallback(IBluetoothStateChangeCallback callback) {
395 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
396 "Need BLUETOOTH permission");
397 Message msg = mHandler.obtainMessage(MESSAGE_REGISTER_STATE_CHANGE_CALLBACK);
398 msg.obj = callback;
399 mHandler.sendMessage(msg);
400 }
401
402 public void unregisterStateChangeCallback(IBluetoothStateChangeCallback callback) {
403 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
404 "Need BLUETOOTH permission");
405 Message msg = mHandler.obtainMessage(MESSAGE_UNREGISTER_STATE_CHANGE_CALLBACK);
406 msg.obj = callback;
407 mHandler.sendMessage(msg);
408 }
409
410 public boolean isEnabled() {
Zhihai Xu6eb76522012-11-29 15:41:04 -0800411 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
412 (!checkIfCallerIsForegroundUser())) {
413 Log.w(TAG,"isEnabled(): not allowed for non-active and non system user");
Zhihai Xu40874a02012-10-08 17:57:03 -0700414 return false;
415 }
416
fredc0f420372012-04-12 00:02:00 -0700417 synchronized(mConnection) {
418 try {
419 return (mBluetooth != null && mBluetooth.isEnabled());
420 } catch (RemoteException e) {
421 Log.e(TAG, "isEnabled()", e);
422 }
423 }
424 return false;
425 }
426
Nitin Arorad055adb2015-03-02 15:03:51 -0800427 class ClientDeathRecipient implements IBinder.DeathRecipient {
428 public void binderDied() {
429 if (DBG) Log.d(TAG, "Binder is dead - unregister Ble App");
430 if (mBleAppCount > 0) --mBleAppCount;
431
432 if (mBleAppCount == 0) {
433 if (DBG) Log.d(TAG, "Disabling LE only mode after application crash");
434 try {
435 if (mBluetooth != null) {
436 mBluetooth.onBrEdrDown();
437 }
438 } catch(RemoteException e) {
439 Log.e(TAG,"Unable to call onBrEdrDown", e);
440 }
441 }
442 }
443 }
444
445 /** Internal death rec list */
446 Map<IBinder, ClientDeathRecipient> mBleApps = new HashMap<IBinder, ClientDeathRecipient>();
447
Wei Wang67d84162015-04-26 17:04:29 -0700448 @Override
449 public boolean isBleScanAlwaysAvailable() {
450 try {
451 return (Settings.Global.getInt(mContentResolver,
452 Settings.Global.BLE_SCAN_ALWAYS_AVAILABLE)) != 0;
453 } catch (SettingNotFoundException e) {
454 }
455 return false;
456 }
457
Wei Wange4a744b2015-06-11 17:50:29 -0700458 // Monitor change of BLE scan only mode settings.
459 private void registerForBleScanModeChange() {
460 ContentObserver contentObserver = new ContentObserver(null) {
461 @Override
462 public void onChange(boolean selfChange) {
463 if (!isBleScanAlwaysAvailable()) {
464 disableBleScanMode();
465 clearBleApps();
466 try {
467 if (mBluetooth != null) mBluetooth.onBrEdrDown();
468 } catch (RemoteException e) {
469 Log.e(TAG, "error when disabling bluetooth", e);
470 }
471 }
472 }
473 };
474
475 mContentResolver.registerContentObserver(
476 Settings.Global.getUriFor(Settings.Global.BLE_SCAN_ALWAYS_AVAILABLE),
477 false, contentObserver);
478 }
479
480 // Disable ble scan only mode.
481 private void disableBleScanMode() {
482 try {
483 if (mBluetooth != null && (mBluetooth.getState() != BluetoothAdapter.STATE_ON)) {
484 if (DBG) Log.d(TAG, "Reseting the mEnable flag for clean disable");
485 mEnable = false;
486 }
487 } catch (RemoteException e) {
488 Log.e(TAG, "getState()", e);
489 }
490 }
491
Nitin Arorad055adb2015-03-02 15:03:51 -0800492 public int updateBleAppCount(IBinder token, boolean enable) {
493 if (enable) {
494 ClientDeathRecipient r = mBleApps.get(token);
495 if (r == null) {
496 ClientDeathRecipient deathRec = new ClientDeathRecipient();
497 try {
498 token.linkToDeath(deathRec, 0);
499 } catch (RemoteException ex) {
500 throw new IllegalArgumentException("Wake lock is already dead.");
501 }
502 mBleApps.put(token, deathRec);
503 synchronized (this) {
504 ++mBleAppCount;
505 }
506 if (DBG) Log.d(TAG, "Registered for death Notification");
507 }
508
509 } else {
510 ClientDeathRecipient r = mBleApps.get(token);
511 if (r != null) {
Wei Wange4a744b2015-06-11 17:50:29 -0700512 // Unregister death recipient as the app goes away.
513 token.unlinkToDeath(r, 0);
Nitin Arorad055adb2015-03-02 15:03:51 -0800514 mBleApps.remove(token);
515 synchronized (this) {
516 if (mBleAppCount > 0) --mBleAppCount;
517 }
518 if (DBG) Log.d(TAG, "Unregistered for death Notification");
519 }
520 }
521 if (DBG) Log.d(TAG, "Updated BleAppCount" + mBleAppCount);
522 if (mBleAppCount == 0 && mEnable) {
Wei Wange4a744b2015-06-11 17:50:29 -0700523 disableBleScanMode();
Nitin Arorad055adb2015-03-02 15:03:51 -0800524 }
525 return mBleAppCount;
526 }
527
Wei Wange4a744b2015-06-11 17:50:29 -0700528 // Clear all apps using BLE scan only mode.
529 private void clearBleApps() {
530 synchronized (this) {
531 mBleApps.clear();
532 mBleAppCount = 0;
533 }
534 }
535
Nitin Arorad055adb2015-03-02 15:03:51 -0800536 /** @hide*/
537 public boolean isBleAppPresent() {
538 if (DBG) Log.d(TAG, "isBleAppPresent() count: " + mBleAppCount);
539 return (mBleAppCount > 0);
540 }
541
542 /**
543 * Action taken when GattService is turned off
544 */
545 private void onBluetoothGattServiceUp() {
546 if (DBG) Log.d(TAG,"BluetoothGatt Service is Up");
547 try{
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700548 if (isBleAppPresent() == false && mBluetooth != null
549 && mBluetooth.getState() == BluetoothAdapter.STATE_BLE_ON) {
Nitin Arorad055adb2015-03-02 15:03:51 -0800550 mBluetooth.onLeServiceUp();
551
552 // waive WRITE_SECURE_SETTINGS permission check
553 long callingIdentity = Binder.clearCallingIdentity();
554 persistBluetoothSetting(BLUETOOTH_ON_BLUETOOTH);
555 Binder.restoreCallingIdentity(callingIdentity);
556 }
557 } catch(RemoteException e) {
558 Log.e(TAG,"Unable to call onServiceUp", e);
559 }
560 }
561
562 /**
563 * Inform BluetoothAdapter instances that BREDR part is down
564 * and turn off all service and stack if no LE app needs it
565 */
566 private void sendBrEdrDownCallback() {
567 if (DBG) Log.d(TAG,"Calling sendBrEdrDownCallback callbacks");
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700568
569 if(mBluetooth == null) {
570 Log.w(TAG, "Bluetooth handle is null");
571 return;
572 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800573
574 if (isBleAppPresent() == false) {
575 try {
576 mBluetooth.onBrEdrDown();
577 } catch(RemoteException e) {
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700578 Log.e(TAG, "Call to onBrEdrDown() failed.", e);
Nitin Arorad055adb2015-03-02 15:03:51 -0800579 }
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700580 } else {
581 // Need to stay at BLE ON. Disconnect all Gatt connections
Nitin Arorad055adb2015-03-02 15:03:51 -0800582 try{
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700583 mBluetoothGatt.unregAll();
Nitin Arorad055adb2015-03-02 15:03:51 -0800584 } catch(RemoteException e) {
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700585 Log.e(TAG, "Unable to disconnect all apps.", e);
Nitin Arorad055adb2015-03-02 15:03:51 -0800586 }
587 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800588 }
589
590 /** @hide*/
fredc0f420372012-04-12 00:02:00 -0700591 public void getNameAndAddress() {
fredcf2458862012-04-16 15:18:27 -0700592 if (DBG) {
Matthew Xiecdce0b92012-07-12 19:06:15 -0700593 Log.d(TAG,"getNameAndAddress(): mBluetooth = " + mBluetooth +
594 " mBinding = " + mBinding);
fredcf2458862012-04-16 15:18:27 -0700595 }
fredc0f420372012-04-12 00:02:00 -0700596 Message msg = mHandler.obtainMessage(MESSAGE_GET_NAME_AND_ADDRESS);
597 mHandler.sendMessage(msg);
598 }
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700599 public boolean enableNoAutoConnect()
600 {
601 mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
602 "Need BLUETOOTH ADMIN permission");
Zhihai Xu40874a02012-10-08 17:57:03 -0700603
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700604 if (DBG) {
605 Log.d(TAG,"enableNoAutoConnect(): mBluetooth =" + mBluetooth +
606 " mBinding = " + mBinding);
607 }
Martijn Coenen8385c5a2012-11-29 10:14:16 -0800608 int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
609
610 if (callingAppId != Process.NFC_UID) {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700611 throw new SecurityException("no permission to enable Bluetooth quietly");
612 }
Martijn Coenen8385c5a2012-11-29 10:14:16 -0800613
Zhihai Xu401202b2012-12-03 11:36:21 -0800614 synchronized(mReceiver) {
615 mQuietEnableExternal = true;
616 mEnableExternal = true;
617 sendEnableMsg(true);
618 }
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700619 return true;
620
621 }
fredc0f420372012-04-12 00:02:00 -0700622 public boolean enable() {
Zhihai Xu6eb76522012-11-29 15:41:04 -0800623 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
624 (!checkIfCallerIsForegroundUser())) {
625 Log.w(TAG,"enable(): not allowed for non-active and non system user");
Zhihai Xu40874a02012-10-08 17:57:03 -0700626 return false;
fredcf2458862012-04-16 15:18:27 -0700627 }
628
Zhihai Xu401202b2012-12-03 11:36:21 -0800629 mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
630 "Need BLUETOOTH ADMIN permission");
631 if (DBG) {
632 Log.d(TAG,"enable(): mBluetooth =" + mBluetooth +
633 " mBinding = " + mBinding);
634 }
635
636 synchronized(mReceiver) {
637 mQuietEnableExternal = false;
638 mEnableExternal = true;
639 // waive WRITE_SECURE_SETTINGS permission check
Zhihai Xu401202b2012-12-03 11:36:21 -0800640 sendEnableMsg(false);
641 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800642 if (DBG) Log.d(TAG, "enable returning");
Zhihai Xu401202b2012-12-03 11:36:21 -0800643 return true;
fredc0f420372012-04-12 00:02:00 -0700644 }
645
646 public boolean disable(boolean persist) {
647 mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
648 "Need BLUETOOTH ADMIN permissicacheNameAndAddresson");
Zhihai Xu40874a02012-10-08 17:57:03 -0700649
Zhihai Xu6eb76522012-11-29 15:41:04 -0800650 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
651 (!checkIfCallerIsForegroundUser())) {
652 Log.w(TAG,"disable(): not allowed for non-active and non system user");
Zhihai Xu40874a02012-10-08 17:57:03 -0700653 return false;
654 }
655
fredcf2458862012-04-16 15:18:27 -0700656 if (DBG) {
Matthew Xiecdce0b92012-07-12 19:06:15 -0700657 Log.d(TAG,"disable(): mBluetooth = " + mBluetooth +
658 " mBinding = " + mBinding);
659 }
fredcf2458862012-04-16 15:18:27 -0700660
Zhihai Xu401202b2012-12-03 11:36:21 -0800661 synchronized(mReceiver) {
662 if (persist) {
663 // waive WRITE_SECURE_SETTINGS permission check
664 long callingIdentity = Binder.clearCallingIdentity();
665 persistBluetoothSetting(BLUETOOTH_OFF);
666 Binder.restoreCallingIdentity(callingIdentity);
667 }
668 mEnableExternal = false;
669 sendDisableMsg();
670 }
fredc0f420372012-04-12 00:02:00 -0700671 return true;
672 }
673
fredc649fe492012-04-19 01:07:18 -0700674 public void unbindAndFinish() {
fredcf2458862012-04-16 15:18:27 -0700675 if (DBG) {
Matthew Xiecdce0b92012-07-12 19:06:15 -0700676 Log.d(TAG,"unbindAndFinish(): " + mBluetooth +
677 " mBinding = " + mBinding);
fredcf2458862012-04-16 15:18:27 -0700678 }
679
fredc0f420372012-04-12 00:02:00 -0700680 synchronized (mConnection) {
681 if (mUnbinding) return;
682 mUnbinding = true;
Zhihai Xu40874a02012-10-08 17:57:03 -0700683 if (mBluetooth != null) {
fredcbf072a72012-05-09 16:52:50 -0700684 if (!mConnection.isGetNameAddressOnly()) {
685 //Unregister callback object
686 try {
687 mBluetooth.unregisterCallback(mBluetoothCallback);
688 } catch (RemoteException re) {
Zhihai Xu40874a02012-10-08 17:57:03 -0700689 Log.e(TAG, "Unable to unregister BluetoothCallback",re);
fredcbf072a72012-05-09 16:52:50 -0700690 }
691 }
fredc0f420372012-04-12 00:02:00 -0700692 if (DBG) Log.d(TAG, "Sending unbind request.");
fredcd6883532012-04-25 17:46:13 -0700693 mBluetooth = null;
694 //Unbind
fredc0f420372012-04-12 00:02:00 -0700695 mContext.unbindService(mConnection);
fredcd6883532012-04-25 17:46:13 -0700696 mUnbinding = false;
Zhihai Xu40874a02012-10-08 17:57:03 -0700697 mBinding = false;
fredcf2458862012-04-16 15:18:27 -0700698 } else {
699 mUnbinding=false;
fredc0f420372012-04-12 00:02:00 -0700700 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800701 mBluetoothGatt = null;
fredc0f420372012-04-12 00:02:00 -0700702 }
703 }
704
Matthew Xieddf7e472013-03-01 18:41:02 -0800705 public IBluetoothGatt getBluetoothGatt() {
706 // sync protection
707 return mBluetoothGatt;
708 }
709
Benjamin Franze8b98922014-11-12 15:57:54 +0000710 @Override
711 public boolean bindBluetoothProfileService(int bluetoothProfile,
712 IBluetoothProfileServiceConnection proxy) {
713 if (!mEnable) {
714 if (DBG) {
715 Log.d(TAG, "Trying to bind to profile: " + bluetoothProfile +
716 ", while Bluetooth was disabled");
717 }
718 return false;
719 }
720 synchronized (mProfileServices) {
721 ProfileServiceConnections psc = mProfileServices.get(new Integer(bluetoothProfile));
722 if (psc == null) {
723 if (DBG) {
724 Log.d(TAG, "Creating new ProfileServiceConnections object for"
725 + " profile: " + bluetoothProfile);
726 }
Benjamin Franz5b614592014-12-09 18:58:45 +0000727
728 if (bluetoothProfile != BluetoothProfile.HEADSET) return false;
729
730 Intent intent = new Intent(IBluetoothHeadset.class.getName());
Benjamin Franze8b98922014-11-12 15:57:54 +0000731 psc = new ProfileServiceConnections(intent);
Benjamin Franz5b614592014-12-09 18:58:45 +0000732 if (!psc.bindService()) return false;
733
Benjamin Franze8b98922014-11-12 15:57:54 +0000734 mProfileServices.put(new Integer(bluetoothProfile), psc);
Benjamin Franze8b98922014-11-12 15:57:54 +0000735 }
736 }
737
738 // Introducing a delay to give the client app time to prepare
739 Message addProxyMsg = mHandler.obtainMessage(MESSAGE_ADD_PROXY_DELAYED);
740 addProxyMsg.arg1 = bluetoothProfile;
741 addProxyMsg.obj = proxy;
742 mHandler.sendMessageDelayed(addProxyMsg, ADD_PROXY_DELAY_MS);
743 return true;
744 }
745
746 @Override
747 public void unbindBluetoothProfileService(int bluetoothProfile,
748 IBluetoothProfileServiceConnection proxy) {
749 synchronized (mProfileServices) {
750 ProfileServiceConnections psc = mProfileServices.get(new Integer(bluetoothProfile));
751 if (psc == null) {
752 return;
753 }
754 psc.removeProxy(proxy);
755 }
756 }
757
758 private void unbindAllBluetoothProfileServices() {
759 synchronized (mProfileServices) {
760 for (Integer i : mProfileServices.keySet()) {
761 ProfileServiceConnections psc = mProfileServices.get(i);
Benjamin Franz5b614592014-12-09 18:58:45 +0000762 try {
763 mContext.unbindService(psc);
764 } catch (IllegalArgumentException e) {
765 Log.e(TAG, "Unable to unbind service with intent: " + psc.mIntent, e);
766 }
Benjamin Franze8b98922014-11-12 15:57:54 +0000767 psc.removeAllProxies();
768 }
769 mProfileServices.clear();
770 }
771 }
772
773 /**
Miao Chou658bf2f2015-06-26 17:14:35 -0700774 * Send enable message and set adapter name and address. Called when the boot phase becomes
775 * PHASE_SYSTEM_SERVICES_READY.
776 */
777 public void handleOnBootPhase() {
778 if (DBG) Log.d(TAG, "Bluetooth boot completed");
779 if (mEnableExternal && isBluetoothPersistedStateOnBluetooth()) {
780 if (DBG) Log.d(TAG, "Auto-enabling Bluetooth.");
781 sendEnableMsg(mQuietEnableExternal);
782 }
783 if (!isNameAndAddressSet()) {
784 // Sync the Bluetooth name and address from the Bluetooth Adapter
785 if (DBG) Log.d(TAG, "Retrieving Bluetooth Adapter name and address...");
786 getNameAndAddress();
787 }
788 }
789
790 /**
791 * Called when switching to a different foreground user.
792 */
793 public void handleOnSwitchUser(int userHandle) {
794 if (DBG) Log.d(TAG, "Bluetooth user switched");
795 mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_USER_SWITCHED, userHandle, 0));
796 }
797
798 /**
Benjamin Franze8b98922014-11-12 15:57:54 +0000799 * This class manages the clients connected to a given ProfileService
800 * and maintains the connection with that service.
801 */
802 final private class ProfileServiceConnections implements ServiceConnection,
803 IBinder.DeathRecipient {
804 final RemoteCallbackList<IBluetoothProfileServiceConnection> mProxies =
805 new RemoteCallbackList <IBluetoothProfileServiceConnection>();
806 IBinder mService;
807 ComponentName mClassName;
808 Intent mIntent;
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700809 boolean mInvokingProxyCallbacks = false;
Benjamin Franze8b98922014-11-12 15:57:54 +0000810
811 ProfileServiceConnections(Intent intent) {
812 mService = null;
813 mClassName = null;
814 mIntent = intent;
815 }
816
Benjamin Franz5b614592014-12-09 18:58:45 +0000817 private boolean bindService() {
818 if (mIntent != null && mService == null &&
819 doBind(mIntent, this, 0, UserHandle.CURRENT_OR_SELF)) {
Benjamin Franze8b98922014-11-12 15:57:54 +0000820 Message msg = mHandler.obtainMessage(MESSAGE_BIND_PROFILE_SERVICE);
821 msg.obj = this;
822 mHandler.sendMessageDelayed(msg, TIMEOUT_BIND_MS);
Benjamin Franz5b614592014-12-09 18:58:45 +0000823 return true;
Benjamin Franze8b98922014-11-12 15:57:54 +0000824 }
Benjamin Franz5b614592014-12-09 18:58:45 +0000825 Log.w(TAG, "Unable to bind with intent: " + mIntent);
826 return false;
Benjamin Franze8b98922014-11-12 15:57:54 +0000827 }
828
829 private void addProxy(IBluetoothProfileServiceConnection proxy) {
830 mProxies.register(proxy);
831 if (mService != null) {
832 try{
833 proxy.onServiceConnected(mClassName, mService);
834 } catch (RemoteException e) {
835 Log.e(TAG, "Unable to connect to proxy", e);
836 }
837 } else {
838 if (!mHandler.hasMessages(MESSAGE_BIND_PROFILE_SERVICE, this)) {
839 Message msg = mHandler.obtainMessage(MESSAGE_BIND_PROFILE_SERVICE);
840 msg.obj = this;
841 mHandler.sendMessage(msg);
842 }
843 }
844 }
845
846 private void removeProxy(IBluetoothProfileServiceConnection proxy) {
847 if (proxy != null) {
848 if (mProxies.unregister(proxy)) {
849 try {
850 proxy.onServiceDisconnected(mClassName);
851 } catch (RemoteException e) {
852 Log.e(TAG, "Unable to disconnect proxy", e);
853 }
854 }
855 } else {
856 Log.w(TAG, "Trying to remove a null proxy");
857 }
858 }
859
860 private void removeAllProxies() {
861 onServiceDisconnected(mClassName);
862 mProxies.kill();
863 }
864
865 @Override
866 public void onServiceConnected(ComponentName className, IBinder service) {
867 // remove timeout message
868 mHandler.removeMessages(MESSAGE_BIND_PROFILE_SERVICE, this);
869 mService = service;
870 mClassName = className;
871 try {
872 mService.linkToDeath(this, 0);
873 } catch (RemoteException e) {
874 Log.e(TAG, "Unable to linkToDeath", e);
875 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700876
877 if (mInvokingProxyCallbacks) {
878 Log.e(TAG, "Proxy callbacks already in progress.");
879 return;
Benjamin Franze8b98922014-11-12 15:57:54 +0000880 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700881 mInvokingProxyCallbacks = true;
882
883 final int n = mProxies.beginBroadcast();
884 try {
885 for (int i = 0; i < n; i++) {
886 try {
887 mProxies.getBroadcastItem(i).onServiceConnected(className, service);
888 } catch (RemoteException e) {
889 Log.e(TAG, "Unable to connect to proxy", e);
890 }
891 }
892 } finally {
893 mProxies.finishBroadcast();
894 mInvokingProxyCallbacks = false;
895 }
Benjamin Franze8b98922014-11-12 15:57:54 +0000896 }
897
898 @Override
899 public void onServiceDisconnected(ComponentName className) {
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700900 if (mService == null) return;
Benjamin Franze8b98922014-11-12 15:57:54 +0000901 mService.unlinkToDeath(this, 0);
902 mService = null;
903 mClassName = null;
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700904
905 if (mInvokingProxyCallbacks) {
906 Log.e(TAG, "Proxy callbacks already in progress.");
907 return;
Benjamin Franze8b98922014-11-12 15:57:54 +0000908 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700909 mInvokingProxyCallbacks = true;
910
911 final int n = mProxies.beginBroadcast();
912 try {
913 for (int i = 0; i < n; i++) {
914 try {
915 mProxies.getBroadcastItem(i).onServiceDisconnected(className);
916 } catch (RemoteException e) {
917 Log.e(TAG, "Unable to disconnect from proxy", e);
918 }
919 }
920 } finally {
921 mProxies.finishBroadcast();
922 mInvokingProxyCallbacks = false;
923 }
Benjamin Franze8b98922014-11-12 15:57:54 +0000924 }
925
926 @Override
927 public void binderDied() {
928 if (DBG) {
929 Log.w(TAG, "Profile service for profile: " + mClassName
930 + " died.");
931 }
932 onServiceDisconnected(mClassName);
933 // Trigger rebind
934 Message msg = mHandler.obtainMessage(MESSAGE_BIND_PROFILE_SERVICE);
935 msg.obj = this;
936 mHandler.sendMessageDelayed(msg, TIMEOUT_BIND_MS);
937 }
938 }
939
fredcbf072a72012-05-09 16:52:50 -0700940 private void sendBluetoothStateCallback(boolean isUp) {
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700941 try {
942 int n = mStateChangeCallbacks.beginBroadcast();
943 if (DBG) Log.d(TAG,"Broadcasting onBluetoothStateChange("+isUp+") to " + n + " receivers.");
944 for (int i=0; i <n;i++) {
945 try {
946 mStateChangeCallbacks.getBroadcastItem(i).onBluetoothStateChange(isUp);
947 } catch (RemoteException e) {
948 Log.e(TAG, "Unable to call onBluetoothStateChange() on callback #" + i , e);
949 }
fredcbf072a72012-05-09 16:52:50 -0700950 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700951 } finally {
952 mStateChangeCallbacks.finishBroadcast();
fredcbf072a72012-05-09 16:52:50 -0700953 }
fredcbf072a72012-05-09 16:52:50 -0700954 }
955
956 /**
Zhihai Xu40874a02012-10-08 17:57:03 -0700957 * Inform BluetoothAdapter instances that Adapter service is up
958 */
959 private void sendBluetoothServiceUpCallback() {
960 if (!mConnection.isGetNameAddressOnly()) {
961 if (DBG) Log.d(TAG,"Calling onBluetoothServiceUp callbacks");
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700962 try {
963 int n = mCallbacks.beginBroadcast();
964 Log.d(TAG,"Broadcasting onBluetoothServiceUp() to " + n + " receivers.");
965 for (int i=0; i <n;i++) {
966 try {
967 mCallbacks.getBroadcastItem(i).onBluetoothServiceUp(mBluetooth);
968 } catch (RemoteException e) {
969 Log.e(TAG, "Unable to call onBluetoothServiceUp() on callback #" + i, e);
970 }
Zhihai Xu40874a02012-10-08 17:57:03 -0700971 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700972 } finally {
973 mCallbacks.finishBroadcast();
Zhihai Xu40874a02012-10-08 17:57:03 -0700974 }
Zhihai Xu40874a02012-10-08 17:57:03 -0700975 }
976 }
977 /**
fredcbf072a72012-05-09 16:52:50 -0700978 * Inform BluetoothAdapter instances that Adapter service is down
979 */
980 private void sendBluetoothServiceDownCallback() {
fredcd6883532012-04-25 17:46:13 -0700981 if (!mConnection.isGetNameAddressOnly()) {
982 if (DBG) Log.d(TAG,"Calling onBluetoothServiceDown callbacks");
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700983 try {
984 int n = mCallbacks.beginBroadcast();
985 Log.d(TAG,"Broadcasting onBluetoothServiceDown() to " + n + " receivers.");
986 for (int i=0; i <n;i++) {
987 try {
988 mCallbacks.getBroadcastItem(i).onBluetoothServiceDown();
989 } catch (RemoteException e) {
990 Log.e(TAG, "Unable to call onBluetoothServiceDown() on callback #" + i, e);
991 }
fredcd6883532012-04-25 17:46:13 -0700992 }
Andre Eisenbach3bf1ac52015-07-30 08:59:32 -0700993 } finally {
994 mCallbacks.finishBroadcast();
fredcd6883532012-04-25 17:46:13 -0700995 }
fredcd6883532012-04-25 17:46:13 -0700996 }
997 }
Svet Ganov408abf72015-05-12 19:13:36 -0700998
fredc0f420372012-04-12 00:02:00 -0700999 public String getAddress() {
Matthew Xieaf5ddbf2012-12-04 10:47:43 -08001000 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
Svet Ganov408abf72015-05-12 19:13:36 -07001001 "Need BLUETOOTH permission");
Zhihai Xu40874a02012-10-08 17:57:03 -07001002
Zhihai Xu6eb76522012-11-29 15:41:04 -08001003 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
Svet Ganov408abf72015-05-12 19:13:36 -07001004 (!checkIfCallerIsForegroundUser())) {
Zhihai Xu6eb76522012-11-29 15:41:04 -08001005 Log.w(TAG,"getAddress(): not allowed for non-active and non system user");
1006 return null;
Zhihai Xu40874a02012-10-08 17:57:03 -07001007 }
1008
Svet Ganov408abf72015-05-12 19:13:36 -07001009 if (mContext.checkCallingOrSelfPermission(Manifest.permission.LOCAL_MAC_ADDRESS)
1010 != PackageManager.PERMISSION_GRANTED) {
1011 return BluetoothAdapter.DEFAULT_MAC_ADDRESS;
1012 }
1013
fredc116d1d462012-04-20 14:47:08 -07001014 synchronized(mConnection) {
1015 if (mBluetooth != null) {
1016 try {
1017 return mBluetooth.getAddress();
1018 } catch (RemoteException e) {
1019 Log.e(TAG, "getAddress(): Unable to retrieve address remotely..Returning cached address",e);
1020 }
1021 }
1022 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001023 // mAddress is accessed from outside.
1024 // It is alright without a lock. Here, bluetooth is off, no other thread is
1025 // changing mAddress
fredc0f420372012-04-12 00:02:00 -07001026 return mAddress;
1027 }
fredc649fe492012-04-19 01:07:18 -07001028
fredc0f420372012-04-12 00:02:00 -07001029 public String getName() {
Matthew Xieaf5ddbf2012-12-04 10:47:43 -08001030 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
1031 "Need BLUETOOTH permission");
Zhihai Xu40874a02012-10-08 17:57:03 -07001032
Zhihai Xu6eb76522012-11-29 15:41:04 -08001033 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
1034 (!checkIfCallerIsForegroundUser())) {
1035 Log.w(TAG,"getName(): not allowed for non-active and non system user");
1036 return null;
Zhihai Xu40874a02012-10-08 17:57:03 -07001037 }
1038
fredc116d1d462012-04-20 14:47:08 -07001039 synchronized(mConnection) {
1040 if (mBluetooth != null) {
1041 try {
1042 return mBluetooth.getName();
1043 } catch (RemoteException e) {
1044 Log.e(TAG, "getName(): Unable to retrieve name remotely..Returning cached name",e);
1045 }
1046 }
1047 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001048 // mName is accessed from outside.
1049 // It alright without a lock. Here, bluetooth is off, no other thread is
1050 // changing mName
fredc0f420372012-04-12 00:02:00 -07001051 return mName;
1052 }
1053
fredc0f420372012-04-12 00:02:00 -07001054 private class BluetoothServiceConnection implements ServiceConnection {
1055
1056 private boolean mGetNameAddressOnly;
1057
1058 public void setGetNameAddressOnly(boolean getOnly) {
1059 mGetNameAddressOnly = getOnly;
1060 }
1061
1062 public boolean isGetNameAddressOnly() {
1063 return mGetNameAddressOnly;
1064 }
1065
1066 public void onServiceConnected(ComponentName className, IBinder service) {
Matthew Xieddf7e472013-03-01 18:41:02 -08001067 if (DBG) Log.d(TAG, "BluetoothServiceConnection: " + className.getClassName());
fredc0f420372012-04-12 00:02:00 -07001068 Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_SERVICE_CONNECTED);
Matthew Xieddf7e472013-03-01 18:41:02 -08001069 // TBD if (className.getClassName().equals(IBluetooth.class.getName())) {
1070 if (className.getClassName().equals("com.android.bluetooth.btservice.AdapterService")) {
1071 msg.arg1 = SERVICE_IBLUETOOTH;
1072 // } else if (className.getClassName().equals(IBluetoothGatt.class.getName())) {
1073 } else if (className.getClassName().equals("com.android.bluetooth.gatt.GattService")) {
1074 msg.arg1 = SERVICE_IBLUETOOTHGATT;
1075 } else {
1076 Log.e(TAG, "Unknown service connected: " + className.getClassName());
1077 return;
1078 }
fredc0f420372012-04-12 00:02:00 -07001079 msg.obj = service;
1080 mHandler.sendMessage(msg);
1081 }
1082
1083 public void onServiceDisconnected(ComponentName className) {
fredc0f420372012-04-12 00:02:00 -07001084 // Called if we unexpected disconnected.
Matthew Xieddf7e472013-03-01 18:41:02 -08001085 if (DBG) Log.d(TAG, "BluetoothServiceConnection, disconnected: " +
1086 className.getClassName());
fredc0f420372012-04-12 00:02:00 -07001087 Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED);
Matthew Xieddf7e472013-03-01 18:41:02 -08001088 if (className.getClassName().equals("com.android.bluetooth.btservice.AdapterService")) {
1089 msg.arg1 = SERVICE_IBLUETOOTH;
1090 } else if (className.getClassName().equals("com.android.bluetooth.gatt.GattService")) {
1091 msg.arg1 = SERVICE_IBLUETOOTHGATT;
1092 } else {
1093 Log.e(TAG, "Unknown service disconnected: " + className.getClassName());
1094 return;
1095 }
fredc0f420372012-04-12 00:02:00 -07001096 mHandler.sendMessage(msg);
1097 }
1098 }
1099
1100 private BluetoothServiceConnection mConnection = new BluetoothServiceConnection();
1101
Zhihai Xu40874a02012-10-08 17:57:03 -07001102 private class BluetoothHandler extends Handler {
1103 public BluetoothHandler(Looper looper) {
1104 super(looper);
1105 }
1106
fredc0f420372012-04-12 00:02:00 -07001107 @Override
1108 public void handleMessage(Message msg) {
1109 if (DBG) Log.d (TAG, "Message: " + msg.what);
fredc0f420372012-04-12 00:02:00 -07001110 switch (msg.what) {
1111 case MESSAGE_GET_NAME_AND_ADDRESS: {
fredc649fe492012-04-19 01:07:18 -07001112 if (DBG) Log.d(TAG,"MESSAGE_GET_NAME_AND_ADDRESS");
Matthew Xiecdce0b92012-07-12 19:06:15 -07001113 synchronized(mConnection) {
fredc0f420372012-04-12 00:02:00 -07001114 //Start bind request
Zhihai Xu40874a02012-10-08 17:57:03 -07001115 if ((mBluetooth == null) && (!mBinding)) {
fredc0f420372012-04-12 00:02:00 -07001116 if (DBG) Log.d(TAG, "Binding to service to get name and address");
1117 mConnection.setGetNameAddressOnly(true);
1118 //Start bind timeout and bind
1119 Message timeoutMsg = mHandler.obtainMessage(MESSAGE_TIMEOUT_BIND);
1120 mHandler.sendMessageDelayed(timeoutMsg,TIMEOUT_BIND_MS);
1121 Intent i = new Intent(IBluetooth.class.getName());
Dianne Hackborn221ea892013-08-04 16:50:16 -07001122 if (!doBind(i, mConnection,
Dianne Hackbornce09f5a2014-10-10 15:03:13 -07001123 Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT,
1124 UserHandle.CURRENT)) {
fredc0f420372012-04-12 00:02:00 -07001125 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
Zhihai Xu40874a02012-10-08 17:57:03 -07001126 } else {
1127 mBinding = true;
fredc0f420372012-04-12 00:02:00 -07001128 }
1129 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001130 else {
1131 Message saveMsg= mHandler.obtainMessage(MESSAGE_SAVE_NAME_AND_ADDRESS);
Zhihai Xu40874a02012-10-08 17:57:03 -07001132 saveMsg.arg1 = 0;
1133 if (mBluetooth != null) {
1134 mHandler.sendMessage(saveMsg);
1135 } else {
1136 // if enable is also called to bind the service
1137 // wait for MESSAGE_BLUETOOTH_SERVICE_CONNECTED
1138 mHandler.sendMessageDelayed(saveMsg, TIMEOUT_SAVE_MS);
1139 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001140 }
fredc0f420372012-04-12 00:02:00 -07001141 }
fredc649fe492012-04-19 01:07:18 -07001142 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001143 }
fredc0f420372012-04-12 00:02:00 -07001144 case MESSAGE_SAVE_NAME_AND_ADDRESS: {
Zhihai Xud31c3222012-10-31 16:08:57 -07001145 boolean unbind = false;
fredc649fe492012-04-19 01:07:18 -07001146 if (DBG) Log.d(TAG,"MESSAGE_SAVE_NAME_AND_ADDRESS");
Matthew Xiecdce0b92012-07-12 19:06:15 -07001147 synchronized(mConnection) {
Pavlin Radoslavovb5a479c2015-06-20 22:55:04 -07001148 if (!mEnable && mBluetooth != null && !mConnection.isGetNameAddressOnly()) {
Zhihai Xud31c3222012-10-31 16:08:57 -07001149 try {
1150 mBluetooth.enable();
1151 } catch (RemoteException e) {
1152 Log.e(TAG,"Unable to call enable()",e);
1153 }
1154 }
1155 }
Pavlin Radoslavovb5a479c2015-06-20 22:55:04 -07001156 if (mBluetooth != null && !mConnection.isGetNameAddressOnly()) waitForOnOff(true, false);
Zhihai Xud31c3222012-10-31 16:08:57 -07001157 synchronized(mConnection) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001158 if (mBluetooth != null) {
1159 String name = null;
1160 String address = null;
1161 try {
1162 name = mBluetooth.getName();
1163 address = mBluetooth.getAddress();
1164 } catch (RemoteException re) {
1165 Log.e(TAG,"",re);
1166 }
fredc0f420372012-04-12 00:02:00 -07001167
Matthew Xiecdce0b92012-07-12 19:06:15 -07001168 if (name != null && address != null) {
1169 storeNameAndAddress(name,address);
Zhihai Xu40874a02012-10-08 17:57:03 -07001170 if (mConnection.isGetNameAddressOnly()) {
Zhihai Xud31c3222012-10-31 16:08:57 -07001171 unbind = true;
Zhihai Xu40874a02012-10-08 17:57:03 -07001172 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001173 } else {
1174 if (msg.arg1 < MAX_SAVE_RETRIES) {
1175 Message retryMsg = mHandler.obtainMessage(MESSAGE_SAVE_NAME_AND_ADDRESS);
1176 retryMsg.arg1= 1+msg.arg1;
1177 if (DBG) Log.d(TAG,"Retrying name/address remote retrieval and save.....Retry count =" + retryMsg.arg1);
1178 mHandler.sendMessageDelayed(retryMsg, TIMEOUT_SAVE_MS);
1179 } else {
1180 Log.w(TAG,"Maximum name/address remote retrieval retry exceeded");
Zhihai Xu40874a02012-10-08 17:57:03 -07001181 if (mConnection.isGetNameAddressOnly()) {
Zhihai Xud31c3222012-10-31 16:08:57 -07001182 unbind = true;
Zhihai Xu40874a02012-10-08 17:57:03 -07001183 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001184 }
fredc0f420372012-04-12 00:02:00 -07001185 }
Pavlin Radoslavovb5a479c2015-06-20 22:55:04 -07001186 if (!mEnable && !mConnection.isGetNameAddressOnly()) {
Zhihai Xud31c3222012-10-31 16:08:57 -07001187 try {
1188 mBluetooth.disable();
1189 } catch (RemoteException e) {
1190 Log.e(TAG,"Unable to call disable()",e);
1191 }
1192 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001193 } else {
1194 // rebind service by Request GET NAME AND ADDRESS
1195 // if service is unbinded by disable or
1196 // MESSAGE_BLUETOOTH_SERVICE_CONNECTED is not received
1197 Message getMsg = mHandler.obtainMessage(MESSAGE_GET_NAME_AND_ADDRESS);
1198 mHandler.sendMessage(getMsg);
fredc0f420372012-04-12 00:02:00 -07001199 }
1200 }
Pavlin Radoslavovb5a479c2015-06-20 22:55:04 -07001201 if (!mEnable && mBluetooth != null && !mConnection.isGetNameAddressOnly()) {
1202 waitForOnOff(false, true);
1203 }
Zhihai Xud31c3222012-10-31 16:08:57 -07001204 if (unbind) {
1205 unbindAndFinish();
1206 }
fredc649fe492012-04-19 01:07:18 -07001207 break;
fredc649fe492012-04-19 01:07:18 -07001208 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001209 case MESSAGE_ENABLE:
fredcf2458862012-04-16 15:18:27 -07001210 if (DBG) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001211 Log.d(TAG, "MESSAGE_ENABLE: mBluetooth = " + mBluetooth);
fredc649fe492012-04-19 01:07:18 -07001212 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001213 mHandler.removeMessages(MESSAGE_RESTART_BLUETOOTH_SERVICE);
1214 mEnable = true;
Zhihai Xu401202b2012-12-03 11:36:21 -08001215 handleEnable(msg.arg1 == 1);
fredc649fe492012-04-19 01:07:18 -07001216 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001217
fredc0f420372012-04-12 00:02:00 -07001218 case MESSAGE_DISABLE:
Zhihai Xu40874a02012-10-08 17:57:03 -07001219 mHandler.removeMessages(MESSAGE_RESTART_BLUETOOTH_SERVICE);
1220 if (mEnable && mBluetooth != null) {
1221 waitForOnOff(true, false);
1222 mEnable = false;
Zhihai Xu401202b2012-12-03 11:36:21 -08001223 handleDisable();
Zhihai Xu40874a02012-10-08 17:57:03 -07001224 waitForOnOff(false, false);
1225 } else {
1226 mEnable = false;
Zhihai Xu401202b2012-12-03 11:36:21 -08001227 handleDisable();
Zhihai Xu40874a02012-10-08 17:57:03 -07001228 }
fredc0f420372012-04-12 00:02:00 -07001229 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001230
fredc0f420372012-04-12 00:02:00 -07001231 case MESSAGE_REGISTER_ADAPTER:
1232 {
1233 IBluetoothManagerCallback callback = (IBluetoothManagerCallback) msg.obj;
fredcd6883532012-04-25 17:46:13 -07001234 boolean added = mCallbacks.register(callback);
1235 Log.d(TAG,"Added callback: " + (callback == null? "null": callback) +":" +added );
fredc0f420372012-04-12 00:02:00 -07001236 }
1237 break;
1238 case MESSAGE_UNREGISTER_ADAPTER:
1239 {
1240 IBluetoothManagerCallback callback = (IBluetoothManagerCallback) msg.obj;
fredcd6883532012-04-25 17:46:13 -07001241 boolean removed = mCallbacks.unregister(callback);
1242 Log.d(TAG,"Removed callback: " + (callback == null? "null": callback) +":" + removed);
fredc0f420372012-04-12 00:02:00 -07001243 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001244 }
fredc0f420372012-04-12 00:02:00 -07001245 case MESSAGE_REGISTER_STATE_CHANGE_CALLBACK:
1246 {
1247 IBluetoothStateChangeCallback callback = (IBluetoothStateChangeCallback) msg.obj;
Matthew Xie9b693992013-10-10 11:21:40 -07001248 if (callback != null) {
1249 mStateChangeCallbacks.register(callback);
1250 }
fredc0f420372012-04-12 00:02:00 -07001251 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001252 }
fredc0f420372012-04-12 00:02:00 -07001253 case MESSAGE_UNREGISTER_STATE_CHANGE_CALLBACK:
1254 {
1255 IBluetoothStateChangeCallback callback = (IBluetoothStateChangeCallback) msg.obj;
Matthew Xie9b693992013-10-10 11:21:40 -07001256 if (callback != null) {
1257 mStateChangeCallbacks.unregister(callback);
1258 }
fredc0f420372012-04-12 00:02:00 -07001259 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001260 }
Benjamin Franze8b98922014-11-12 15:57:54 +00001261 case MESSAGE_ADD_PROXY_DELAYED:
1262 {
1263 ProfileServiceConnections psc = mProfileServices.get(
1264 new Integer(msg.arg1));
1265 if (psc == null) {
1266 break;
1267 }
1268 IBluetoothProfileServiceConnection proxy =
1269 (IBluetoothProfileServiceConnection) msg.obj;
1270 psc.addProxy(proxy);
1271 break;
1272 }
1273 case MESSAGE_BIND_PROFILE_SERVICE:
1274 {
1275 ProfileServiceConnections psc = (ProfileServiceConnections) msg.obj;
1276 removeMessages(MESSAGE_BIND_PROFILE_SERVICE, msg.obj);
1277 if (psc == null) {
1278 break;
1279 }
1280 psc.bindService();
1281 break;
1282 }
fredc0f420372012-04-12 00:02:00 -07001283 case MESSAGE_BLUETOOTH_SERVICE_CONNECTED:
1284 {
Matthew Xieddf7e472013-03-01 18:41:02 -08001285 if (DBG) Log.d(TAG,"MESSAGE_BLUETOOTH_SERVICE_CONNECTED: " + msg.arg1);
fredc0f420372012-04-12 00:02:00 -07001286
1287 IBinder service = (IBinder) msg.obj;
1288 synchronized(mConnection) {
Matthew Xieddf7e472013-03-01 18:41:02 -08001289 if (msg.arg1 == SERVICE_IBLUETOOTHGATT) {
1290 mBluetoothGatt = IBluetoothGatt.Stub.asInterface(service);
Nitin Arorad055adb2015-03-02 15:03:51 -08001291 onBluetoothGattServiceUp();
Matthew Xieddf7e472013-03-01 18:41:02 -08001292 break;
1293 } // else must be SERVICE_IBLUETOOTH
1294
1295 //Remove timeout
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001296 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
Matthew Xieddf7e472013-03-01 18:41:02 -08001297
fredc0f420372012-04-12 00:02:00 -07001298 mBinding = false;
1299 mBluetooth = IBluetooth.Stub.asInterface(service);
fredc0f420372012-04-12 00:02:00 -07001300
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001301 try {
1302 boolean enableHciSnoopLog = (Settings.Secure.getInt(mContentResolver,
1303 Settings.Secure.BLUETOOTH_HCI_LOG, 0) == 1);
1304 if (!mBluetooth.configHciSnoopLog(enableHciSnoopLog)) {
1305 Log.e(TAG,"IBluetooth.configHciSnoopLog return false");
1306 }
1307 } catch (RemoteException e) {
1308 Log.e(TAG,"Unable to call configHciSnoopLog", e);
1309 }
1310
Matthew Xiecdce0b92012-07-12 19:06:15 -07001311 if (mConnection.isGetNameAddressOnly()) {
1312 //Request GET NAME AND ADDRESS
1313 Message getMsg = mHandler.obtainMessage(MESSAGE_GET_NAME_AND_ADDRESS);
1314 mHandler.sendMessage(getMsg);
Zhihai Xu40874a02012-10-08 17:57:03 -07001315 if (!mEnable) return;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001316 }
fredc0f420372012-04-12 00:02:00 -07001317
Zhihai Xu40874a02012-10-08 17:57:03 -07001318 mConnection.setGetNameAddressOnly(false);
Matthew Xiecdce0b92012-07-12 19:06:15 -07001319 //Register callback object
fredcbf072a72012-05-09 16:52:50 -07001320 try {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001321 mBluetooth.registerCallback(mBluetoothCallback);
1322 } catch (RemoteException re) {
1323 Log.e(TAG, "Unable to register BluetoothCallback",re);
fredcbf072a72012-05-09 16:52:50 -07001324 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001325 //Inform BluetoothAdapter instances that service is up
Zhihai Xu40874a02012-10-08 17:57:03 -07001326 sendBluetoothServiceUpCallback();
1327
Matthew Xiecdce0b92012-07-12 19:06:15 -07001328 //Do enable request
1329 try {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001330 if (mQuietEnable == false) {
1331 if(!mBluetooth.enable()) {
1332 Log.e(TAG,"IBluetooth.enable() returned false");
1333 }
1334 }
1335 else
1336 {
1337 if(!mBluetooth.enableNoAutoConnect()) {
1338 Log.e(TAG,"IBluetooth.enableNoAutoConnect() returned false");
1339 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001340 }
1341 } catch (RemoteException e) {
1342 Log.e(TAG,"Unable to call enable()",e);
1343 }
Freda8c6df02012-07-11 10:25:23 -07001344 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001345
1346 if (!mEnable) {
1347 waitForOnOff(true, false);
Zhihai Xu401202b2012-12-03 11:36:21 -08001348 handleDisable();
Zhihai Xu40874a02012-10-08 17:57:03 -07001349 waitForOnOff(false, false);
1350 }
fredc649fe492012-04-19 01:07:18 -07001351 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001352 }
fredc649fe492012-04-19 01:07:18 -07001353 case MESSAGE_TIMEOUT_BIND: {
1354 Log.e(TAG, "MESSAGE_TIMEOUT_BIND");
fredc0f420372012-04-12 00:02:00 -07001355 synchronized(mConnection) {
1356 mBinding = false;
1357 }
fredc649fe492012-04-19 01:07:18 -07001358 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001359 }
fredcbf072a72012-05-09 16:52:50 -07001360 case MESSAGE_BLUETOOTH_STATE_CHANGE:
fredc0f420372012-04-12 00:02:00 -07001361 {
fredcbf072a72012-05-09 16:52:50 -07001362 int prevState = msg.arg1;
1363 int newState = msg.arg2;
1364 if (DBG) Log.d(TAG, "MESSAGE_BLUETOOTH_STATE_CHANGE: prevState = " + prevState + ", newState=" + newState);
Zhihai Xu40874a02012-10-08 17:57:03 -07001365 mState = newState;
1366 bluetoothStateChangeHandler(prevState, newState);
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001367 // handle error state transition case from TURNING_ON to OFF
1368 // unbind and rebind bluetooth service and enable bluetooth
Nitin Arorad055adb2015-03-02 15:03:51 -08001369 if ((prevState == BluetoothAdapter.STATE_BLE_TURNING_ON) &&
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001370 (newState == BluetoothAdapter.STATE_OFF) &&
1371 (mBluetooth != null) && mEnable) {
1372 recoverBluetoothServiceFromError();
1373 }
Nitin Arorad055adb2015-03-02 15:03:51 -08001374 if ((prevState == BluetoothAdapter.STATE_TURNING_ON) &&
1375 (newState == BluetoothAdapter.STATE_BLE_ON) &&
1376 (mBluetooth != null) && mEnable) {
1377 recoverBluetoothServiceFromError();
1378 }
1379 if (newState == BluetoothAdapter.STATE_ON ||
1380 newState == BluetoothAdapter.STATE_BLE_ON) {
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001381 // bluetooth is working, reset the counter
1382 if (mErrorRecoveryRetryCounter != 0) {
1383 Log.w(TAG, "bluetooth is recovered from error");
1384 mErrorRecoveryRetryCounter = 0;
1385 }
1386 }
fredc649fe492012-04-19 01:07:18 -07001387 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001388 }
fredc0f420372012-04-12 00:02:00 -07001389 case MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED:
1390 {
Matthew Xieddf7e472013-03-01 18:41:02 -08001391 Log.e(TAG, "MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED: " + msg.arg1);
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301392 synchronized(mConnection) {
Matthew Xieddf7e472013-03-01 18:41:02 -08001393 if (msg.arg1 == SERVICE_IBLUETOOTH) {
1394 // if service is unbinded already, do nothing and return
1395 if (mBluetooth == null) break;
1396 mBluetooth = null;
1397 } else if (msg.arg1 == SERVICE_IBLUETOOTHGATT) {
1398 mBluetoothGatt = null;
1399 break;
1400 } else {
1401 Log.e(TAG, "Bad msg.arg1: " + msg.arg1);
1402 break;
1403 }
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301404 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001405
1406 if (mEnable) {
1407 mEnable = false;
1408 // Send a Bluetooth Restart message
1409 Message restartMsg = mHandler.obtainMessage(
1410 MESSAGE_RESTART_BLUETOOTH_SERVICE);
1411 mHandler.sendMessageDelayed(restartMsg,
1412 SERVICE_RESTART_TIME_MS);
1413 }
1414
1415 if (!mConnection.isGetNameAddressOnly()) {
1416 sendBluetoothServiceDownCallback();
1417
1418 // Send BT state broadcast to update
1419 // the BT icon correctly
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001420 if ((mState == BluetoothAdapter.STATE_TURNING_ON) ||
1421 (mState == BluetoothAdapter.STATE_ON)) {
1422 bluetoothStateChangeHandler(BluetoothAdapter.STATE_ON,
1423 BluetoothAdapter.STATE_TURNING_OFF);
1424 mState = BluetoothAdapter.STATE_TURNING_OFF;
1425 }
1426 if (mState == BluetoothAdapter.STATE_TURNING_OFF) {
1427 bluetoothStateChangeHandler(BluetoothAdapter.STATE_TURNING_OFF,
1428 BluetoothAdapter.STATE_OFF);
1429 }
1430
1431 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
Zhihai Xu40874a02012-10-08 17:57:03 -07001432 mState = BluetoothAdapter.STATE_OFF;
1433 }
fredc649fe492012-04-19 01:07:18 -07001434 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001435 }
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301436 case MESSAGE_RESTART_BLUETOOTH_SERVICE:
1437 {
1438 Log.d(TAG, "MESSAGE_RESTART_BLUETOOTH_SERVICE:"
1439 +" Restart IBluetooth service");
1440 /* Enable without persisting the setting as
1441 it doesnt change when IBluetooth
1442 service restarts */
Zhihai Xu40874a02012-10-08 17:57:03 -07001443 mEnable = true;
Zhihai Xu401202b2012-12-03 11:36:21 -08001444 handleEnable(mQuietEnable);
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301445 break;
1446 }
1447
fredc0f420372012-04-12 00:02:00 -07001448 case MESSAGE_TIMEOUT_UNBIND:
1449 {
fredc649fe492012-04-19 01:07:18 -07001450 Log.e(TAG, "MESSAGE_TIMEOUT_UNBIND");
fredc0f420372012-04-12 00:02:00 -07001451 synchronized(mConnection) {
1452 mUnbinding = false;
1453 }
fredc649fe492012-04-19 01:07:18 -07001454 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001455 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001456
1457 case MESSAGE_USER_SWITCHED:
1458 {
1459 if (DBG) {
1460 Log.d(TAG, "MESSAGE_USER_SWITCHED");
1461 }
1462 mHandler.removeMessages(MESSAGE_USER_SWITCHED);
1463 /* disable and enable BT when detect a user switch */
1464 if (mEnable && mBluetooth != null) {
1465 synchronized (mConnection) {
1466 if (mBluetooth != null) {
1467 //Unregister callback object
1468 try {
1469 mBluetooth.unregisterCallback(mBluetoothCallback);
1470 } catch (RemoteException re) {
1471 Log.e(TAG, "Unable to unregister",re);
1472 }
1473 }
1474 }
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001475
1476 if (mState == BluetoothAdapter.STATE_TURNING_OFF) {
1477 // MESSAGE_USER_SWITCHED happened right after MESSAGE_ENABLE
1478 bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_OFF);
1479 mState = BluetoothAdapter.STATE_OFF;
1480 }
1481 if (mState == BluetoothAdapter.STATE_OFF) {
1482 bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_TURNING_ON);
1483 mState = BluetoothAdapter.STATE_TURNING_ON;
1484 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001485
1486 waitForOnOff(true, false);
1487
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001488 if (mState == BluetoothAdapter.STATE_TURNING_ON) {
1489 bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_ON);
1490 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001491
Benjamin Franze8b98922014-11-12 15:57:54 +00001492 unbindAllBluetoothProfileServices();
Zhihai Xu40874a02012-10-08 17:57:03 -07001493 // disable
Zhihai Xu401202b2012-12-03 11:36:21 -08001494 handleDisable();
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001495 // Pbap service need receive STATE_TURNING_OFF intent to close
1496 bluetoothStateChangeHandler(BluetoothAdapter.STATE_ON,
1497 BluetoothAdapter.STATE_TURNING_OFF);
Zhihai Xu40874a02012-10-08 17:57:03 -07001498
1499 waitForOnOff(false, true);
1500
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001501 bluetoothStateChangeHandler(BluetoothAdapter.STATE_TURNING_OFF,
Zhihai Xu40874a02012-10-08 17:57:03 -07001502 BluetoothAdapter.STATE_OFF);
Zhihai Xu40874a02012-10-08 17:57:03 -07001503 sendBluetoothServiceDownCallback();
1504 synchronized (mConnection) {
1505 if (mBluetooth != null) {
1506 mBluetooth = null;
1507 //Unbind
1508 mContext.unbindService(mConnection);
1509 }
Pavlin Radoslavov29b8c4a2015-08-03 17:44:47 -07001510 mBluetoothGatt = null;
Zhihai Xu40874a02012-10-08 17:57:03 -07001511 }
1512 SystemClock.sleep(100);
1513
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001514 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
1515 mState = BluetoothAdapter.STATE_OFF;
Zhihai Xu40874a02012-10-08 17:57:03 -07001516 // enable
Zhihai Xu401202b2012-12-03 11:36:21 -08001517 handleEnable(mQuietEnable);
John Spurlock8a985d22014-02-25 09:40:05 -05001518 } else if (mBinding || mBluetooth != null) {
Zhihai Xu40874a02012-10-08 17:57:03 -07001519 Message userMsg = mHandler.obtainMessage(MESSAGE_USER_SWITCHED);
1520 userMsg.arg2 = 1 + msg.arg2;
1521 // if user is switched when service is being binding
1522 // delay sending MESSAGE_USER_SWITCHED
1523 mHandler.sendMessageDelayed(userMsg, USER_SWITCHED_TIME_MS);
1524 if (DBG) {
1525 Log.d(TAG, "delay MESSAGE_USER_SWITCHED " + userMsg.arg2);
1526 }
John Spurlock8a985d22014-02-25 09:40:05 -05001527 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001528 break;
1529 }
fredc0f420372012-04-12 00:02:00 -07001530 }
1531 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001532 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001533
Zhihai Xu401202b2012-12-03 11:36:21 -08001534 private void handleEnable(boolean quietMode) {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001535 mQuietEnable = quietMode;
1536
Matthew Xiecdce0b92012-07-12 19:06:15 -07001537 synchronized(mConnection) {
Zhihai Xu40874a02012-10-08 17:57:03 -07001538 if ((mBluetooth == null) && (!mBinding)) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001539 //Start bind timeout and bind
1540 Message timeoutMsg=mHandler.obtainMessage(MESSAGE_TIMEOUT_BIND);
1541 mHandler.sendMessageDelayed(timeoutMsg,TIMEOUT_BIND_MS);
1542 mConnection.setGetNameAddressOnly(false);
1543 Intent i = new Intent(IBluetooth.class.getName());
Dianne Hackbornce09f5a2014-10-10 15:03:13 -07001544 if (!doBind(i, mConnection,Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT,
1545 UserHandle.CURRENT)) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001546 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
Zhihai Xu40874a02012-10-08 17:57:03 -07001547 } else {
1548 mBinding = true;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001549 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001550 } else if (mBluetooth != null) {
1551 if (mConnection.isGetNameAddressOnly()) {
1552 // if GetNameAddressOnly is set, we can clear this flag,
1553 // so the service won't be unbind
1554 // after name and address are saved
1555 mConnection.setGetNameAddressOnly(false);
1556 //Register callback object
1557 try {
1558 mBluetooth.registerCallback(mBluetoothCallback);
1559 } catch (RemoteException re) {
1560 Log.e(TAG, "Unable to register BluetoothCallback",re);
1561 }
1562 //Inform BluetoothAdapter instances that service is up
1563 sendBluetoothServiceUpCallback();
1564 }
1565
Matthew Xiecdce0b92012-07-12 19:06:15 -07001566 //Enable bluetooth
1567 try {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001568 if (!mQuietEnable) {
1569 if(!mBluetooth.enable()) {
1570 Log.e(TAG,"IBluetooth.enable() returned false");
1571 }
1572 }
1573 else {
1574 if(!mBluetooth.enableNoAutoConnect()) {
1575 Log.e(TAG,"IBluetooth.enableNoAutoConnect() returned false");
1576 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001577 }
1578 } catch (RemoteException e) {
1579 Log.e(TAG,"Unable to call enable()",e);
1580 }
1581 }
1582 }
1583 }
1584
Dianne Hackborn221ea892013-08-04 16:50:16 -07001585 boolean doBind(Intent intent, ServiceConnection conn, int flags, UserHandle user) {
1586 ComponentName comp = intent.resolveSystemService(mContext.getPackageManager(), 0);
1587 intent.setComponent(comp);
1588 if (comp == null || !mContext.bindServiceAsUser(intent, conn, flags, user)) {
1589 Log.e(TAG, "Fail to bind to: " + intent);
1590 return false;
1591 }
1592 return true;
1593 }
1594
Zhihai Xu401202b2012-12-03 11:36:21 -08001595 private void handleDisable() {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001596 synchronized(mConnection) {
Zhihai Xu40874a02012-10-08 17:57:03 -07001597 // don't need to disable if GetNameAddressOnly is set,
1598 // service will be unbinded after Name and Address are saved
1599 if ((mBluetooth != null) && (!mConnection.isGetNameAddressOnly())) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001600 if (DBG) Log.d(TAG,"Sending off request.");
1601
1602 try {
1603 if(!mBluetooth.disable()) {
1604 Log.e(TAG,"IBluetooth.disable() returned false");
1605 }
1606 } catch (RemoteException e) {
1607 Log.e(TAG,"Unable to call disable()",e);
1608 }
1609 }
1610 }
1611 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001612
1613 private boolean checkIfCallerIsForegroundUser() {
1614 int foregroundUser;
1615 int callingUser = UserHandle.getCallingUserId();
Martijn Coenen8385c5a2012-11-29 10:14:16 -08001616 int callingUid = Binder.getCallingUid();
Zhihai Xu40874a02012-10-08 17:57:03 -07001617 long callingIdentity = Binder.clearCallingIdentity();
Benjamin Franze8b98922014-11-12 15:57:54 +00001618 UserManager um = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
1619 UserInfo ui = um.getProfileParent(callingUser);
1620 int parentUser = (ui != null) ? ui.id : UserHandle.USER_NULL;
Martijn Coenen8385c5a2012-11-29 10:14:16 -08001621 int callingAppId = UserHandle.getAppId(callingUid);
Zhihai Xu40874a02012-10-08 17:57:03 -07001622 boolean valid = false;
1623 try {
1624 foregroundUser = ActivityManager.getCurrentUser();
Martijn Coenen8385c5a2012-11-29 10:14:16 -08001625 valid = (callingUser == foregroundUser) ||
Benjamin Franze8b98922014-11-12 15:57:54 +00001626 parentUser == foregroundUser ||
Adrian Roosbd9a9a52014-08-18 15:31:57 +02001627 callingAppId == Process.NFC_UID ||
1628 callingAppId == mSystemUiUid;
Zhihai Xu40874a02012-10-08 17:57:03 -07001629 if (DBG) {
1630 Log.d(TAG, "checkIfCallerIsForegroundUser: valid=" + valid
1631 + " callingUser=" + callingUser
Benjamin Franze8b98922014-11-12 15:57:54 +00001632 + " parentUser=" + parentUser
Zhihai Xu40874a02012-10-08 17:57:03 -07001633 + " foregroundUser=" + foregroundUser);
1634 }
1635 } finally {
1636 Binder.restoreCallingIdentity(callingIdentity);
1637 }
1638 return valid;
1639 }
1640
Nitin Arorad055adb2015-03-02 15:03:51 -08001641 private void sendBleStateChanged(int prevState, int newState) {
1642 if (DBG) Log.d(TAG,"BLE State Change Intent: " + prevState + " -> " + newState);
1643 // Send broadcast message to everyone else
1644 Intent intent = new Intent(BluetoothAdapter.ACTION_BLE_STATE_CHANGED);
1645 intent.putExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE, prevState);
1646 intent.putExtra(BluetoothAdapter.EXTRA_STATE, newState);
1647 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1648 mContext.sendBroadcastAsUser(intent, UserHandle.ALL, BLUETOOTH_PERM);
1649 }
1650
Zhihai Xu40874a02012-10-08 17:57:03 -07001651 private void bluetoothStateChangeHandler(int prevState, int newState) {
Nitin Arorad055adb2015-03-02 15:03:51 -08001652 boolean isStandardBroadcast = true;
Zhihai Xu40874a02012-10-08 17:57:03 -07001653 if (prevState != newState) {
1654 //Notify all proxy objects first of adapter state change
Nitin Arorad055adb2015-03-02 15:03:51 -08001655 if (newState == BluetoothAdapter.STATE_BLE_ON
1656 || newState == BluetoothAdapter.STATE_OFF) {
1657 boolean intermediate_off = (prevState == BluetoothAdapter.STATE_TURNING_OFF
1658 && newState == BluetoothAdapter.STATE_BLE_ON);
Zhihai Xu40874a02012-10-08 17:57:03 -07001659
Nitin Arorad055adb2015-03-02 15:03:51 -08001660 if (newState == BluetoothAdapter.STATE_OFF) {
1661 // If Bluetooth is off, send service down event to proxy objects, and unbind
1662 if (DBG) Log.d(TAG, "Bluetooth is complete turn off");
1663 if (canUnbindBluetoothService()) {
1664 if (DBG) Log.d(TAG, "Good to unbind!");
Matthew Xieddf7e472013-03-01 18:41:02 -08001665 sendBluetoothServiceDownCallback();
1666 unbindAndFinish();
Nitin Arorad055adb2015-03-02 15:03:51 -08001667 sendBleStateChanged(prevState, newState);
1668 // Don't broadcast as it has already been broadcast before
1669 isStandardBroadcast = false;
Matthew Xieddf7e472013-03-01 18:41:02 -08001670 }
Nitin Arorad055adb2015-03-02 15:03:51 -08001671
1672 } else if (!intermediate_off) {
1673 // connect to GattService
1674 if (DBG) Log.d(TAG, "Bluetooth is in LE only mode");
1675 if (mBluetoothGatt != null) {
1676 if (DBG) Log.d(TAG, "Calling BluetoothGattServiceUp");
1677 onBluetoothGattServiceUp();
1678 } else {
1679 if (DBG) Log.d(TAG, "Binding Bluetooth GATT service");
1680 if (mContext.getPackageManager().hasSystemFeature(
1681 PackageManager.FEATURE_BLUETOOTH_LE)) {
1682 Intent i = new Intent(IBluetoothGatt.class.getName());
1683 doBind(i, mConnection, Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT, UserHandle.CURRENT);
1684 }
1685 }
1686 sendBleStateChanged(prevState, newState);
1687 //Don't broadcase this as std intent
1688 isStandardBroadcast = false;
1689
1690 } else if (intermediate_off){
1691 if (DBG) Log.d(TAG, "Intermediate off, back to LE only mode");
1692 // For LE only mode, broadcast as is
1693 sendBleStateChanged(prevState, newState);
1694 sendBluetoothStateCallback(false); // BT is OFF for general users
1695 // Broadcast as STATE_OFF
1696 newState = BluetoothAdapter.STATE_OFF;
1697 sendBrEdrDownCallback();
Zhihai Xu40874a02012-10-08 17:57:03 -07001698 }
Nitin Arorad055adb2015-03-02 15:03:51 -08001699 } else if (newState == BluetoothAdapter.STATE_ON) {
1700 boolean isUp = (newState==BluetoothAdapter.STATE_ON);
1701 sendBluetoothStateCallback(isUp);
1702 sendBleStateChanged(prevState, newState);
1703
1704 } else if (newState == BluetoothAdapter.STATE_BLE_TURNING_ON
1705 || newState == BluetoothAdapter.STATE_BLE_TURNING_OFF ) {
1706 sendBleStateChanged(prevState, newState);
1707 isStandardBroadcast = false;
1708
1709 } else if (newState == BluetoothAdapter.STATE_TURNING_ON
1710 || newState == BluetoothAdapter.STATE_TURNING_OFF) {
1711 sendBleStateChanged(prevState, newState);
Zhihai Xu40874a02012-10-08 17:57:03 -07001712 }
1713
Nitin Arorad055adb2015-03-02 15:03:51 -08001714 if (isStandardBroadcast) {
1715 if (prevState == BluetoothAdapter.STATE_BLE_ON) {
1716 // Show prevState of BLE_ON as OFF to standard users
1717 prevState = BluetoothAdapter.STATE_OFF;
1718 }
1719 Intent intent = new Intent(BluetoothAdapter.ACTION_STATE_CHANGED);
1720 intent.putExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE, prevState);
1721 intent.putExtra(BluetoothAdapter.EXTRA_STATE, newState);
1722 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1723 mContext.sendBroadcastAsUser(intent, UserHandle.ALL, BLUETOOTH_PERM);
1724 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001725 }
1726 }
1727
1728 /**
1729 * if on is true, wait for state become ON
1730 * if off is true, wait for state become OFF
1731 * if both on and off are false, wait for state not ON
1732 */
1733 private boolean waitForOnOff(boolean on, boolean off) {
1734 int i = 0;
1735 while (i < 10) {
1736 synchronized(mConnection) {
1737 try {
1738 if (mBluetooth == null) break;
1739 if (on) {
1740 if (mBluetooth.getState() == BluetoothAdapter.STATE_ON) return true;
1741 } else if (off) {
1742 if (mBluetooth.getState() == BluetoothAdapter.STATE_OFF) return true;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07001743 } else {
Zhihai Xu40874a02012-10-08 17:57:03 -07001744 if (mBluetooth.getState() != BluetoothAdapter.STATE_ON) return true;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07001745 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001746 } catch (RemoteException e) {
1747 Log.e(TAG, "getState()", e);
1748 break;
1749 }
1750 }
1751 if (on || off) {
1752 SystemClock.sleep(300);
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07001753 } else {
Zhihai Xu40874a02012-10-08 17:57:03 -07001754 SystemClock.sleep(50);
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07001755 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001756 i++;
1757 }
1758 Log.e(TAG,"waitForOnOff time out");
1759 return false;
1760 }
Zhihai Xu681ae7f2012-11-12 15:14:18 -08001761
Zhihai Xu401202b2012-12-03 11:36:21 -08001762 private void sendDisableMsg() {
1763 mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_DISABLE));
1764 }
1765
1766 private void sendEnableMsg(boolean quietMode) {
1767 mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_ENABLE,
1768 quietMode ? 1 : 0, 0));
1769 }
1770
Zhihai Xu681ae7f2012-11-12 15:14:18 -08001771 private boolean canUnbindBluetoothService() {
1772 synchronized(mConnection) {
1773 //Only unbind with mEnable flag not set
1774 //For race condition: disable and enable back-to-back
1775 //Avoid unbind right after enable due to callback from disable
1776 //Only unbind with Bluetooth at OFF state
1777 //Only unbind without any MESSAGE_BLUETOOTH_STATE_CHANGE message
1778 try {
1779 if (mEnable || (mBluetooth == null)) return false;
1780 if (mHandler.hasMessages(MESSAGE_BLUETOOTH_STATE_CHANGE)) return false;
1781 return (mBluetooth.getState() == BluetoothAdapter.STATE_OFF);
1782 } catch (RemoteException e) {
1783 Log.e(TAG, "getState()", e);
1784 }
1785 }
1786 return false;
1787 }
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001788
1789 private void recoverBluetoothServiceFromError() {
1790 Log.e(TAG,"recoverBluetoothServiceFromError");
1791 synchronized (mConnection) {
1792 if (mBluetooth != null) {
1793 //Unregister callback object
1794 try {
1795 mBluetooth.unregisterCallback(mBluetoothCallback);
1796 } catch (RemoteException re) {
1797 Log.e(TAG, "Unable to unregister",re);
1798 }
1799 }
1800 }
1801
1802 SystemClock.sleep(500);
1803
1804 // disable
1805 handleDisable();
1806
1807 waitForOnOff(false, true);
1808
1809 sendBluetoothServiceDownCallback();
1810 synchronized (mConnection) {
1811 if (mBluetooth != null) {
1812 mBluetooth = null;
1813 //Unbind
1814 mContext.unbindService(mConnection);
1815 }
Pavlin Radoslavov29b8c4a2015-08-03 17:44:47 -07001816 mBluetoothGatt = null;
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001817 }
1818
1819 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
1820 mState = BluetoothAdapter.STATE_OFF;
1821
1822 mEnable = false;
1823
1824 if (mErrorRecoveryRetryCounter++ < MAX_ERROR_RESTART_RETRIES) {
1825 // Send a Bluetooth Restart message to reenable bluetooth
1826 Message restartMsg = mHandler.obtainMessage(
1827 MESSAGE_RESTART_BLUETOOTH_SERVICE);
1828 mHandler.sendMessageDelayed(restartMsg, ERROR_RESTART_TIME_MS);
1829 } else {
1830 // todo: notify user to power down and power up phone to make bluetooth work.
1831 }
1832 }
Mike Lockwood726d4de2014-10-28 14:06:28 -07001833
1834 @Override
1835 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Mike Lockwood75b52bb2014-12-18 14:16:36 -08001836 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DUMP, TAG);
1837
Andre Eisenbach14dcb5f2014-12-05 09:31:30 -08001838 writer.println("Bluetooth Status");
1839 writer.println(" enabled: " + mEnable);
1840 writer.println(" state: " + mState);
1841 writer.println(" address: " + mAddress);
1842 writer.println(" name: " + mName + "\n");
1843 writer.flush();
1844
Mike Lockwood726d4de2014-10-28 14:06:28 -07001845 if (mBluetooth == null) {
1846 writer.println("Bluetooth Service not connected");
1847 } else {
Andre Eisenbach14dcb5f2014-12-05 09:31:30 -08001848 ParcelFileDescriptor pfd = null;
Mike Lockwood726d4de2014-10-28 14:06:28 -07001849 try {
Sharvil Nanavati7c250052015-06-20 12:05:52 -07001850 writer.println("Bonded devices:");
1851 for (BluetoothDevice device : mBluetooth.getBondedDevices()) {
1852 writer.println(" " + device.getAddress() +
1853 " [" + DEVICE_TYPE_NAMES[device.getType()] + "] " +
1854 device.getName());
1855 }
1856 writer.flush();
1857
Andre Eisenbach14dcb5f2014-12-05 09:31:30 -08001858 pfd = ParcelFileDescriptor.dup(fd);
1859 mBluetooth.dump(pfd);
Mike Lockwood726d4de2014-10-28 14:06:28 -07001860 } catch (RemoteException re) {
1861 writer.println("RemoteException while calling Bluetooth Service");
Andre Eisenbach14dcb5f2014-12-05 09:31:30 -08001862 } catch (IOException ioe) {
1863 writer.println("IOException attempting to dup() fd");
1864 } finally {
1865 if (pfd != null) {
1866 try {
1867 pfd.close();
1868 } catch (IOException ioe) {
1869 writer.println("IOException attempting to close() fd");
1870 }
1871 }
Mike Lockwood726d4de2014-10-28 14:06:28 -07001872 }
1873 }
1874 }
fredc0f420372012-04-12 00:02:00 -07001875}