blob: b9f62e678562298f6abcce163ad725bd93a93b0f [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",
274 UserHandle.USER_OWNER);
275 } catch (PackageManager.NameNotFoundException e) {
276 Log.wtf(TAG, "Unable to resolve SystemUI's UID.", e);
277 }
278 mSystemUiUid = sysUiUid;
fredc0f420372012-04-12 00:02:00 -0700279 }
280
fredc649fe492012-04-19 01:07:18 -0700281 /**
282 * Returns true if airplane mode is currently on
283 */
284 private final boolean isAirplaneModeOn() {
Christopher Tatec09cdce2012-09-10 16:50:14 -0700285 return Settings.Global.getInt(mContext.getContentResolver(),
286 Settings.Global.AIRPLANE_MODE_ON, 0) == 1;
fredc649fe492012-04-19 01:07:18 -0700287 }
288
289 /**
290 * Returns true if the Bluetooth saved state is "on"
291 */
292 private final boolean isBluetoothPersistedStateOn() {
Jeff Brownbf6f6f92012-09-25 15:03:20 -0700293 return Settings.Global.getInt(mContentResolver,
Zhihai Xu401202b2012-12-03 11:36:21 -0800294 Settings.Global.BLUETOOTH_ON, 0) != BLUETOOTH_OFF;
295 }
296
297 /**
298 * Returns true if the Bluetooth saved state is BLUETOOTH_ON_BLUETOOTH
299 */
300 private final boolean isBluetoothPersistedStateOnBluetooth() {
301 return Settings.Global.getInt(mContentResolver,
302 Settings.Global.BLUETOOTH_ON, 0) == BLUETOOTH_ON_BLUETOOTH;
fredc649fe492012-04-19 01:07:18 -0700303 }
304
305 /**
306 * Save the Bluetooth on/off state
307 *
308 */
Zhihai Xu401202b2012-12-03 11:36:21 -0800309 private void persistBluetoothSetting(int value) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -0700310 Settings.Global.putInt(mContext.getContentResolver(),
311 Settings.Global.BLUETOOTH_ON,
Zhihai Xu401202b2012-12-03 11:36:21 -0800312 value);
fredc649fe492012-04-19 01:07:18 -0700313 }
314
315 /**
316 * Returns true if the Bluetooth Adapter's name and address is
317 * locally cached
318 * @return
319 */
fredc0f420372012-04-12 00:02:00 -0700320 private boolean isNameAndAddressSet() {
321 return mName !=null && mAddress!= null && mName.length()>0 && mAddress.length()>0;
322 }
323
fredc649fe492012-04-19 01:07:18 -0700324 /**
325 * Retrieve the Bluetooth Adapter's name and address and save it in
326 * in the local cache
327 */
fredc0f420372012-04-12 00:02:00 -0700328 private void loadStoredNameAndAddress() {
329 if (DBG) Log.d(TAG, "Loading stored name and address");
Zhihai Xud31c3222012-10-31 16:08:57 -0700330 if (mContext.getResources().getBoolean
331 (com.android.internal.R.bool.config_bluetooth_address_validation) &&
332 Settings.Secure.getInt(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDR_VALID, 0) == 0) {
333 // if the valid flag is not set, don't load the address and name
334 if (DBG) Log.d(TAG, "invalid bluetooth name and address stored");
335 return;
336 }
fredc0f420372012-04-12 00:02:00 -0700337 mName = Settings.Secure.getString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_NAME);
338 mAddress = Settings.Secure.getString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDRESS);
Zhihai Xud31c3222012-10-31 16:08:57 -0700339 if (DBG) Log.d(TAG, "Stored bluetooth Name=" + mName + ",Address=" + mAddress);
fredc0f420372012-04-12 00:02:00 -0700340 }
341
fredc649fe492012-04-19 01:07:18 -0700342 /**
343 * Save the Bluetooth name and address in the persistent store.
344 * Only non-null values will be saved.
345 * @param name
346 * @param address
347 */
fredc0f420372012-04-12 00:02:00 -0700348 private void storeNameAndAddress(String name, String address) {
349 if (name != null) {
350 Settings.Secure.putString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_NAME, name);
fredc0f420372012-04-12 00:02:00 -0700351 mName = name;
fredc649fe492012-04-19 01:07:18 -0700352 if (DBG) Log.d(TAG,"Stored Bluetooth name: " +
353 Settings.Secure.getString(mContentResolver,SECURE_SETTINGS_BLUETOOTH_NAME));
fredc0f420372012-04-12 00:02:00 -0700354 }
355
356 if (address != null) {
357 Settings.Secure.putString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDRESS, address);
fredc0f420372012-04-12 00:02:00 -0700358 mAddress=address;
fredc649fe492012-04-19 01:07:18 -0700359 if (DBG) Log.d(TAG,"Stored Bluetoothaddress: " +
360 Settings.Secure.getString(mContentResolver,SECURE_SETTINGS_BLUETOOTH_ADDRESS));
fredc0f420372012-04-12 00:02:00 -0700361 }
Zhihai Xud31c3222012-10-31 16:08:57 -0700362
363 if ((name != null) && (address != null)) {
364 Settings.Secure.putInt(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDR_VALID, 1);
365 }
fredc0f420372012-04-12 00:02:00 -0700366 }
367
368 public IBluetooth registerAdapter(IBluetoothManagerCallback callback){
Natalie Silvanovich55db6462014-05-01 16:12:23 -0700369 if (callback == null) {
370 Log.w(TAG, "Callback is null in registerAdapter");
371 return null;
372 }
fredc0f420372012-04-12 00:02:00 -0700373 Message msg = mHandler.obtainMessage(MESSAGE_REGISTER_ADAPTER);
374 msg.obj = callback;
375 mHandler.sendMessage(msg);
376 synchronized(mConnection) {
377 return mBluetooth;
378 }
379 }
380
381 public void unregisterAdapter(IBluetoothManagerCallback callback) {
Natalie Silvanovich55db6462014-05-01 16:12:23 -0700382 if (callback == null) {
383 Log.w(TAG, "Callback is null in unregisterAdapter");
384 return;
385 }
fredc0f420372012-04-12 00:02:00 -0700386 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
387 "Need BLUETOOTH permission");
388 Message msg = mHandler.obtainMessage(MESSAGE_UNREGISTER_ADAPTER);
389 msg.obj = callback;
390 mHandler.sendMessage(msg);
391 }
392
393 public void registerStateChangeCallback(IBluetoothStateChangeCallback callback) {
394 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
395 "Need BLUETOOTH permission");
396 Message msg = mHandler.obtainMessage(MESSAGE_REGISTER_STATE_CHANGE_CALLBACK);
397 msg.obj = callback;
398 mHandler.sendMessage(msg);
399 }
400
401 public void unregisterStateChangeCallback(IBluetoothStateChangeCallback callback) {
402 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
403 "Need BLUETOOTH permission");
404 Message msg = mHandler.obtainMessage(MESSAGE_UNREGISTER_STATE_CHANGE_CALLBACK);
405 msg.obj = callback;
406 mHandler.sendMessage(msg);
407 }
408
409 public boolean isEnabled() {
Zhihai Xu6eb76522012-11-29 15:41:04 -0800410 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
411 (!checkIfCallerIsForegroundUser())) {
412 Log.w(TAG,"isEnabled(): not allowed for non-active and non system user");
Zhihai Xu40874a02012-10-08 17:57:03 -0700413 return false;
414 }
415
fredc0f420372012-04-12 00:02:00 -0700416 synchronized(mConnection) {
417 try {
418 return (mBluetooth != null && mBluetooth.isEnabled());
419 } catch (RemoteException e) {
420 Log.e(TAG, "isEnabled()", e);
421 }
422 }
423 return false;
424 }
425
Nitin Arorad055adb2015-03-02 15:03:51 -0800426 class ClientDeathRecipient implements IBinder.DeathRecipient {
427 public void binderDied() {
428 if (DBG) Log.d(TAG, "Binder is dead - unregister Ble App");
429 if (mBleAppCount > 0) --mBleAppCount;
430
431 if (mBleAppCount == 0) {
432 if (DBG) Log.d(TAG, "Disabling LE only mode after application crash");
433 try {
434 if (mBluetooth != null) {
435 mBluetooth.onBrEdrDown();
436 }
437 } catch(RemoteException e) {
438 Log.e(TAG,"Unable to call onBrEdrDown", e);
439 }
440 }
441 }
442 }
443
444 /** Internal death rec list */
445 Map<IBinder, ClientDeathRecipient> mBleApps = new HashMap<IBinder, ClientDeathRecipient>();
446
Wei Wang67d84162015-04-26 17:04:29 -0700447 @Override
448 public boolean isBleScanAlwaysAvailable() {
449 try {
450 return (Settings.Global.getInt(mContentResolver,
451 Settings.Global.BLE_SCAN_ALWAYS_AVAILABLE)) != 0;
452 } catch (SettingNotFoundException e) {
453 }
454 return false;
455 }
456
Wei Wange4a744b2015-06-11 17:50:29 -0700457 // Monitor change of BLE scan only mode settings.
458 private void registerForBleScanModeChange() {
459 ContentObserver contentObserver = new ContentObserver(null) {
460 @Override
461 public void onChange(boolean selfChange) {
462 if (!isBleScanAlwaysAvailable()) {
463 disableBleScanMode();
464 clearBleApps();
465 try {
466 if (mBluetooth != null) mBluetooth.onBrEdrDown();
467 } catch (RemoteException e) {
468 Log.e(TAG, "error when disabling bluetooth", e);
469 }
470 }
471 }
472 };
473
474 mContentResolver.registerContentObserver(
475 Settings.Global.getUriFor(Settings.Global.BLE_SCAN_ALWAYS_AVAILABLE),
476 false, contentObserver);
477 }
478
479 // Disable ble scan only mode.
480 private void disableBleScanMode() {
481 try {
482 if (mBluetooth != null && (mBluetooth.getState() != BluetoothAdapter.STATE_ON)) {
483 if (DBG) Log.d(TAG, "Reseting the mEnable flag for clean disable");
484 mEnable = false;
485 }
486 } catch (RemoteException e) {
487 Log.e(TAG, "getState()", e);
488 }
489 }
490
Nitin Arorad055adb2015-03-02 15:03:51 -0800491 public int updateBleAppCount(IBinder token, boolean enable) {
492 if (enable) {
493 ClientDeathRecipient r = mBleApps.get(token);
494 if (r == null) {
495 ClientDeathRecipient deathRec = new ClientDeathRecipient();
496 try {
497 token.linkToDeath(deathRec, 0);
498 } catch (RemoteException ex) {
499 throw new IllegalArgumentException("Wake lock is already dead.");
500 }
501 mBleApps.put(token, deathRec);
502 synchronized (this) {
503 ++mBleAppCount;
504 }
505 if (DBG) Log.d(TAG, "Registered for death Notification");
506 }
507
508 } else {
509 ClientDeathRecipient r = mBleApps.get(token);
510 if (r != null) {
Wei Wange4a744b2015-06-11 17:50:29 -0700511 // Unregister death recipient as the app goes away.
512 token.unlinkToDeath(r, 0);
Nitin Arorad055adb2015-03-02 15:03:51 -0800513 mBleApps.remove(token);
514 synchronized (this) {
515 if (mBleAppCount > 0) --mBleAppCount;
516 }
517 if (DBG) Log.d(TAG, "Unregistered for death Notification");
518 }
519 }
520 if (DBG) Log.d(TAG, "Updated BleAppCount" + mBleAppCount);
521 if (mBleAppCount == 0 && mEnable) {
Wei Wange4a744b2015-06-11 17:50:29 -0700522 disableBleScanMode();
Nitin Arorad055adb2015-03-02 15:03:51 -0800523 }
524 return mBleAppCount;
525 }
526
Wei Wange4a744b2015-06-11 17:50:29 -0700527 // Clear all apps using BLE scan only mode.
528 private void clearBleApps() {
529 synchronized (this) {
530 mBleApps.clear();
531 mBleAppCount = 0;
532 }
533 }
534
Nitin Arorad055adb2015-03-02 15:03:51 -0800535 /** @hide*/
536 public boolean isBleAppPresent() {
537 if (DBG) Log.d(TAG, "isBleAppPresent() count: " + mBleAppCount);
538 return (mBleAppCount > 0);
539 }
540
541 /**
542 * Action taken when GattService is turned off
543 */
544 private void onBluetoothGattServiceUp() {
545 if (DBG) Log.d(TAG,"BluetoothGatt Service is Up");
546 try{
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700547 if (isBleAppPresent() == false && mBluetooth != null
548 && mBluetooth.getState() == BluetoothAdapter.STATE_BLE_ON) {
Nitin Arorad055adb2015-03-02 15:03:51 -0800549 mBluetooth.onLeServiceUp();
550
551 // waive WRITE_SECURE_SETTINGS permission check
552 long callingIdentity = Binder.clearCallingIdentity();
553 persistBluetoothSetting(BLUETOOTH_ON_BLUETOOTH);
554 Binder.restoreCallingIdentity(callingIdentity);
555 }
556 } catch(RemoteException e) {
557 Log.e(TAG,"Unable to call onServiceUp", e);
558 }
559 }
560
561 /**
562 * Inform BluetoothAdapter instances that BREDR part is down
563 * and turn off all service and stack if no LE app needs it
564 */
565 private void sendBrEdrDownCallback() {
566 if (DBG) Log.d(TAG,"Calling sendBrEdrDownCallback callbacks");
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700567
568 if(mBluetooth == null) {
569 Log.w(TAG, "Bluetooth handle is null");
570 return;
571 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800572
573 if (isBleAppPresent() == false) {
574 try {
575 mBluetooth.onBrEdrDown();
576 } catch(RemoteException e) {
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700577 Log.e(TAG, "Call to onBrEdrDown() failed.", e);
Nitin Arorad055adb2015-03-02 15:03:51 -0800578 }
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700579 } else {
580 // Need to stay at BLE ON. Disconnect all Gatt connections
Nitin Arorad055adb2015-03-02 15:03:51 -0800581 try{
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700582 mBluetoothGatt.unregAll();
Nitin Arorad055adb2015-03-02 15:03:51 -0800583 } catch(RemoteException e) {
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700584 Log.e(TAG, "Unable to disconnect all apps.", e);
Nitin Arorad055adb2015-03-02 15:03:51 -0800585 }
586 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800587 }
588
589 /** @hide*/
fredc0f420372012-04-12 00:02:00 -0700590 public void getNameAndAddress() {
fredcf2458862012-04-16 15:18:27 -0700591 if (DBG) {
Matthew Xiecdce0b92012-07-12 19:06:15 -0700592 Log.d(TAG,"getNameAndAddress(): mBluetooth = " + mBluetooth +
593 " mBinding = " + mBinding);
fredcf2458862012-04-16 15:18:27 -0700594 }
fredc0f420372012-04-12 00:02:00 -0700595 Message msg = mHandler.obtainMessage(MESSAGE_GET_NAME_AND_ADDRESS);
596 mHandler.sendMessage(msg);
597 }
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700598 public boolean enableNoAutoConnect()
599 {
600 mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
601 "Need BLUETOOTH ADMIN permission");
Zhihai Xu40874a02012-10-08 17:57:03 -0700602
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700603 if (DBG) {
604 Log.d(TAG,"enableNoAutoConnect(): mBluetooth =" + mBluetooth +
605 " mBinding = " + mBinding);
606 }
Martijn Coenen8385c5a2012-11-29 10:14:16 -0800607 int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
608
609 if (callingAppId != Process.NFC_UID) {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700610 throw new SecurityException("no permission to enable Bluetooth quietly");
611 }
Martijn Coenen8385c5a2012-11-29 10:14:16 -0800612
Zhihai Xu401202b2012-12-03 11:36:21 -0800613 synchronized(mReceiver) {
614 mQuietEnableExternal = true;
615 mEnableExternal = true;
616 sendEnableMsg(true);
617 }
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700618 return true;
619
620 }
fredc0f420372012-04-12 00:02:00 -0700621 public boolean enable() {
Zhihai Xu6eb76522012-11-29 15:41:04 -0800622 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
623 (!checkIfCallerIsForegroundUser())) {
624 Log.w(TAG,"enable(): not allowed for non-active and non system user");
Zhihai Xu40874a02012-10-08 17:57:03 -0700625 return false;
fredcf2458862012-04-16 15:18:27 -0700626 }
627
Zhihai Xu401202b2012-12-03 11:36:21 -0800628 mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
629 "Need BLUETOOTH ADMIN permission");
630 if (DBG) {
631 Log.d(TAG,"enable(): mBluetooth =" + mBluetooth +
632 " mBinding = " + mBinding);
633 }
634
635 synchronized(mReceiver) {
636 mQuietEnableExternal = false;
637 mEnableExternal = true;
638 // waive WRITE_SECURE_SETTINGS permission check
Zhihai Xu401202b2012-12-03 11:36:21 -0800639 sendEnableMsg(false);
640 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800641 if (DBG) Log.d(TAG, "enable returning");
Zhihai Xu401202b2012-12-03 11:36:21 -0800642 return true;
fredc0f420372012-04-12 00:02:00 -0700643 }
644
645 public boolean disable(boolean persist) {
646 mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
647 "Need BLUETOOTH ADMIN permissicacheNameAndAddresson");
Zhihai Xu40874a02012-10-08 17:57:03 -0700648
Zhihai Xu6eb76522012-11-29 15:41:04 -0800649 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
650 (!checkIfCallerIsForegroundUser())) {
651 Log.w(TAG,"disable(): not allowed for non-active and non system user");
Zhihai Xu40874a02012-10-08 17:57:03 -0700652 return false;
653 }
654
fredcf2458862012-04-16 15:18:27 -0700655 if (DBG) {
Matthew Xiecdce0b92012-07-12 19:06:15 -0700656 Log.d(TAG,"disable(): mBluetooth = " + mBluetooth +
657 " mBinding = " + mBinding);
658 }
fredcf2458862012-04-16 15:18:27 -0700659
Zhihai Xu401202b2012-12-03 11:36:21 -0800660 synchronized(mReceiver) {
661 if (persist) {
662 // waive WRITE_SECURE_SETTINGS permission check
663 long callingIdentity = Binder.clearCallingIdentity();
664 persistBluetoothSetting(BLUETOOTH_OFF);
665 Binder.restoreCallingIdentity(callingIdentity);
666 }
667 mEnableExternal = false;
668 sendDisableMsg();
669 }
fredc0f420372012-04-12 00:02:00 -0700670 return true;
671 }
672
fredc649fe492012-04-19 01:07:18 -0700673 public void unbindAndFinish() {
fredcf2458862012-04-16 15:18:27 -0700674 if (DBG) {
Matthew Xiecdce0b92012-07-12 19:06:15 -0700675 Log.d(TAG,"unbindAndFinish(): " + mBluetooth +
676 " mBinding = " + mBinding);
fredcf2458862012-04-16 15:18:27 -0700677 }
678
fredc0f420372012-04-12 00:02:00 -0700679 synchronized (mConnection) {
680 if (mUnbinding) return;
681 mUnbinding = true;
Zhihai Xu40874a02012-10-08 17:57:03 -0700682 if (mBluetooth != null) {
fredcbf072a72012-05-09 16:52:50 -0700683 if (!mConnection.isGetNameAddressOnly()) {
684 //Unregister callback object
685 try {
686 mBluetooth.unregisterCallback(mBluetoothCallback);
687 } catch (RemoteException re) {
Zhihai Xu40874a02012-10-08 17:57:03 -0700688 Log.e(TAG, "Unable to unregister BluetoothCallback",re);
fredcbf072a72012-05-09 16:52:50 -0700689 }
690 }
fredc0f420372012-04-12 00:02:00 -0700691 if (DBG) Log.d(TAG, "Sending unbind request.");
fredcd6883532012-04-25 17:46:13 -0700692 mBluetooth = null;
693 //Unbind
fredc0f420372012-04-12 00:02:00 -0700694 mContext.unbindService(mConnection);
fredcd6883532012-04-25 17:46:13 -0700695 mUnbinding = false;
Zhihai Xu40874a02012-10-08 17:57:03 -0700696 mBinding = false;
fredcf2458862012-04-16 15:18:27 -0700697 } else {
698 mUnbinding=false;
fredc0f420372012-04-12 00:02:00 -0700699 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800700 mBluetoothGatt = null;
fredc0f420372012-04-12 00:02:00 -0700701 }
702 }
703
Matthew Xieddf7e472013-03-01 18:41:02 -0800704 public IBluetoothGatt getBluetoothGatt() {
705 // sync protection
706 return mBluetoothGatt;
707 }
708
Benjamin Franze8b98922014-11-12 15:57:54 +0000709 @Override
710 public boolean bindBluetoothProfileService(int bluetoothProfile,
711 IBluetoothProfileServiceConnection proxy) {
712 if (!mEnable) {
713 if (DBG) {
714 Log.d(TAG, "Trying to bind to profile: " + bluetoothProfile +
715 ", while Bluetooth was disabled");
716 }
717 return false;
718 }
719 synchronized (mProfileServices) {
720 ProfileServiceConnections psc = mProfileServices.get(new Integer(bluetoothProfile));
721 if (psc == null) {
722 if (DBG) {
723 Log.d(TAG, "Creating new ProfileServiceConnections object for"
724 + " profile: " + bluetoothProfile);
725 }
Benjamin Franz5b614592014-12-09 18:58:45 +0000726
727 if (bluetoothProfile != BluetoothProfile.HEADSET) return false;
728
729 Intent intent = new Intent(IBluetoothHeadset.class.getName());
Benjamin Franze8b98922014-11-12 15:57:54 +0000730 psc = new ProfileServiceConnections(intent);
Benjamin Franz5b614592014-12-09 18:58:45 +0000731 if (!psc.bindService()) return false;
732
Benjamin Franze8b98922014-11-12 15:57:54 +0000733 mProfileServices.put(new Integer(bluetoothProfile), psc);
Benjamin Franze8b98922014-11-12 15:57:54 +0000734 }
735 }
736
737 // Introducing a delay to give the client app time to prepare
738 Message addProxyMsg = mHandler.obtainMessage(MESSAGE_ADD_PROXY_DELAYED);
739 addProxyMsg.arg1 = bluetoothProfile;
740 addProxyMsg.obj = proxy;
741 mHandler.sendMessageDelayed(addProxyMsg, ADD_PROXY_DELAY_MS);
742 return true;
743 }
744
745 @Override
746 public void unbindBluetoothProfileService(int bluetoothProfile,
747 IBluetoothProfileServiceConnection proxy) {
748 synchronized (mProfileServices) {
749 ProfileServiceConnections psc = mProfileServices.get(new Integer(bluetoothProfile));
750 if (psc == null) {
751 return;
752 }
753 psc.removeProxy(proxy);
754 }
755 }
756
757 private void unbindAllBluetoothProfileServices() {
758 synchronized (mProfileServices) {
759 for (Integer i : mProfileServices.keySet()) {
760 ProfileServiceConnections psc = mProfileServices.get(i);
Benjamin Franz5b614592014-12-09 18:58:45 +0000761 try {
762 mContext.unbindService(psc);
763 } catch (IllegalArgumentException e) {
764 Log.e(TAG, "Unable to unbind service with intent: " + psc.mIntent, e);
765 }
Benjamin Franze8b98922014-11-12 15:57:54 +0000766 psc.removeAllProxies();
767 }
768 mProfileServices.clear();
769 }
770 }
771
772 /**
Miao Chou658bf2f2015-06-26 17:14:35 -0700773 * Send enable message and set adapter name and address. Called when the boot phase becomes
774 * PHASE_SYSTEM_SERVICES_READY.
775 */
776 public void handleOnBootPhase() {
777 if (DBG) Log.d(TAG, "Bluetooth boot completed");
778 if (mEnableExternal && isBluetoothPersistedStateOnBluetooth()) {
779 if (DBG) Log.d(TAG, "Auto-enabling Bluetooth.");
780 sendEnableMsg(mQuietEnableExternal);
781 }
782 if (!isNameAndAddressSet()) {
783 // Sync the Bluetooth name and address from the Bluetooth Adapter
784 if (DBG) Log.d(TAG, "Retrieving Bluetooth Adapter name and address...");
785 getNameAndAddress();
786 }
787 }
788
789 /**
790 * Called when switching to a different foreground user.
791 */
792 public void handleOnSwitchUser(int userHandle) {
793 if (DBG) Log.d(TAG, "Bluetooth user switched");
794 mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_USER_SWITCHED, userHandle, 0));
795 }
796
797 /**
Benjamin Franze8b98922014-11-12 15:57:54 +0000798 * This class manages the clients connected to a given ProfileService
799 * and maintains the connection with that service.
800 */
801 final private class ProfileServiceConnections implements ServiceConnection,
802 IBinder.DeathRecipient {
803 final RemoteCallbackList<IBluetoothProfileServiceConnection> mProxies =
804 new RemoteCallbackList <IBluetoothProfileServiceConnection>();
805 IBinder mService;
806 ComponentName mClassName;
807 Intent mIntent;
808
809 ProfileServiceConnections(Intent intent) {
810 mService = null;
811 mClassName = null;
812 mIntent = intent;
813 }
814
Benjamin Franz5b614592014-12-09 18:58:45 +0000815 private boolean bindService() {
816 if (mIntent != null && mService == null &&
817 doBind(mIntent, this, 0, UserHandle.CURRENT_OR_SELF)) {
Benjamin Franze8b98922014-11-12 15:57:54 +0000818 Message msg = mHandler.obtainMessage(MESSAGE_BIND_PROFILE_SERVICE);
819 msg.obj = this;
820 mHandler.sendMessageDelayed(msg, TIMEOUT_BIND_MS);
Benjamin Franz5b614592014-12-09 18:58:45 +0000821 return true;
Benjamin Franze8b98922014-11-12 15:57:54 +0000822 }
Benjamin Franz5b614592014-12-09 18:58:45 +0000823 Log.w(TAG, "Unable to bind with intent: " + mIntent);
824 return false;
Benjamin Franze8b98922014-11-12 15:57:54 +0000825 }
826
827 private void addProxy(IBluetoothProfileServiceConnection proxy) {
828 mProxies.register(proxy);
829 if (mService != null) {
830 try{
831 proxy.onServiceConnected(mClassName, mService);
832 } catch (RemoteException e) {
833 Log.e(TAG, "Unable to connect to proxy", e);
834 }
835 } else {
836 if (!mHandler.hasMessages(MESSAGE_BIND_PROFILE_SERVICE, this)) {
837 Message msg = mHandler.obtainMessage(MESSAGE_BIND_PROFILE_SERVICE);
838 msg.obj = this;
839 mHandler.sendMessage(msg);
840 }
841 }
842 }
843
844 private void removeProxy(IBluetoothProfileServiceConnection proxy) {
845 if (proxy != null) {
846 if (mProxies.unregister(proxy)) {
847 try {
848 proxy.onServiceDisconnected(mClassName);
849 } catch (RemoteException e) {
850 Log.e(TAG, "Unable to disconnect proxy", e);
851 }
852 }
853 } else {
854 Log.w(TAG, "Trying to remove a null proxy");
855 }
856 }
857
858 private void removeAllProxies() {
859 onServiceDisconnected(mClassName);
860 mProxies.kill();
861 }
862
863 @Override
864 public void onServiceConnected(ComponentName className, IBinder service) {
865 // remove timeout message
866 mHandler.removeMessages(MESSAGE_BIND_PROFILE_SERVICE, this);
867 mService = service;
868 mClassName = className;
869 try {
870 mService.linkToDeath(this, 0);
871 } catch (RemoteException e) {
872 Log.e(TAG, "Unable to linkToDeath", e);
873 }
874 int n = mProxies.beginBroadcast();
875 for (int i = 0; i < n; i++) {
876 try {
877 mProxies.getBroadcastItem(i).onServiceConnected(className, service);
878 } catch (RemoteException e) {
879 Log.e(TAG, "Unable to connect to proxy", e);
880 }
881 }
882 mProxies.finishBroadcast();
883 }
884
885 @Override
886 public void onServiceDisconnected(ComponentName className) {
887 if (mService == null) {
888 return;
889 }
890 mService.unlinkToDeath(this, 0);
891 mService = null;
892 mClassName = null;
893 int n = mProxies.beginBroadcast();
894 for (int i = 0; i < n; i++) {
895 try {
896 mProxies.getBroadcastItem(i).onServiceDisconnected(className);
897 } catch (RemoteException e) {
898 Log.e(TAG, "Unable to disconnect from proxy", e);
899 }
900 }
901 mProxies.finishBroadcast();
902 }
903
904 @Override
905 public void binderDied() {
906 if (DBG) {
907 Log.w(TAG, "Profile service for profile: " + mClassName
908 + " died.");
909 }
910 onServiceDisconnected(mClassName);
911 // Trigger rebind
912 Message msg = mHandler.obtainMessage(MESSAGE_BIND_PROFILE_SERVICE);
913 msg.obj = this;
914 mHandler.sendMessageDelayed(msg, TIMEOUT_BIND_MS);
915 }
916 }
917
fredcbf072a72012-05-09 16:52:50 -0700918 private void sendBluetoothStateCallback(boolean isUp) {
919 int n = mStateChangeCallbacks.beginBroadcast();
Freda8c6df02012-07-11 10:25:23 -0700920 if (DBG) Log.d(TAG,"Broadcasting onBluetoothStateChange("+isUp+") to " + n + " receivers.");
fredcbf072a72012-05-09 16:52:50 -0700921 for (int i=0; i <n;i++) {
922 try {
923 mStateChangeCallbacks.getBroadcastItem(i).onBluetoothStateChange(isUp);
924 } catch (RemoteException e) {
925 Log.e(TAG, "Unable to call onBluetoothStateChange() on callback #" + i , e);
926 }
927 }
928 mStateChangeCallbacks.finishBroadcast();
929 }
930
931 /**
Zhihai Xu40874a02012-10-08 17:57:03 -0700932 * Inform BluetoothAdapter instances that Adapter service is up
933 */
934 private void sendBluetoothServiceUpCallback() {
935 if (!mConnection.isGetNameAddressOnly()) {
936 if (DBG) Log.d(TAG,"Calling onBluetoothServiceUp callbacks");
937 int n = mCallbacks.beginBroadcast();
938 Log.d(TAG,"Broadcasting onBluetoothServiceUp() to " + n + " receivers.");
939 for (int i=0; i <n;i++) {
940 try {
941 mCallbacks.getBroadcastItem(i).onBluetoothServiceUp(mBluetooth);
942 } catch (RemoteException e) {
943 Log.e(TAG, "Unable to call onBluetoothServiceUp() on callback #" + i, e);
944 }
945 }
946 mCallbacks.finishBroadcast();
947 }
948 }
949 /**
fredcbf072a72012-05-09 16:52:50 -0700950 * Inform BluetoothAdapter instances that Adapter service is down
951 */
952 private void sendBluetoothServiceDownCallback() {
fredcd6883532012-04-25 17:46:13 -0700953 if (!mConnection.isGetNameAddressOnly()) {
954 if (DBG) Log.d(TAG,"Calling onBluetoothServiceDown callbacks");
955 int n = mCallbacks.beginBroadcast();
956 Log.d(TAG,"Broadcasting onBluetoothServiceDown() to " + n + " receivers.");
957 for (int i=0; i <n;i++) {
958 try {
959 mCallbacks.getBroadcastItem(i).onBluetoothServiceDown();
960 } catch (RemoteException e) {
961 Log.e(TAG, "Unable to call onBluetoothServiceDown() on callback #" + i, e);
962 }
963 }
964 mCallbacks.finishBroadcast();
965 }
966 }
Svet Ganov408abf72015-05-12 19:13:36 -0700967
fredc0f420372012-04-12 00:02:00 -0700968 public String getAddress() {
Matthew Xieaf5ddbf2012-12-04 10:47:43 -0800969 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
Svet Ganov408abf72015-05-12 19:13:36 -0700970 "Need BLUETOOTH permission");
Zhihai Xu40874a02012-10-08 17:57:03 -0700971
Zhihai Xu6eb76522012-11-29 15:41:04 -0800972 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
Svet Ganov408abf72015-05-12 19:13:36 -0700973 (!checkIfCallerIsForegroundUser())) {
Zhihai Xu6eb76522012-11-29 15:41:04 -0800974 Log.w(TAG,"getAddress(): not allowed for non-active and non system user");
975 return null;
Zhihai Xu40874a02012-10-08 17:57:03 -0700976 }
977
Svet Ganov408abf72015-05-12 19:13:36 -0700978 if (mContext.checkCallingOrSelfPermission(Manifest.permission.LOCAL_MAC_ADDRESS)
979 != PackageManager.PERMISSION_GRANTED) {
980 return BluetoothAdapter.DEFAULT_MAC_ADDRESS;
981 }
982
fredc116d1d462012-04-20 14:47:08 -0700983 synchronized(mConnection) {
984 if (mBluetooth != null) {
985 try {
986 return mBluetooth.getAddress();
987 } catch (RemoteException e) {
988 Log.e(TAG, "getAddress(): Unable to retrieve address remotely..Returning cached address",e);
989 }
990 }
991 }
Matthew Xiecdce0b92012-07-12 19:06:15 -0700992 // mAddress is accessed from outside.
993 // It is alright without a lock. Here, bluetooth is off, no other thread is
994 // changing mAddress
fredc0f420372012-04-12 00:02:00 -0700995 return mAddress;
996 }
fredc649fe492012-04-19 01:07:18 -0700997
fredc0f420372012-04-12 00:02:00 -0700998 public String getName() {
Matthew Xieaf5ddbf2012-12-04 10:47:43 -0800999 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
1000 "Need BLUETOOTH permission");
Zhihai Xu40874a02012-10-08 17:57:03 -07001001
Zhihai Xu6eb76522012-11-29 15:41:04 -08001002 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
1003 (!checkIfCallerIsForegroundUser())) {
1004 Log.w(TAG,"getName(): not allowed for non-active and non system user");
1005 return null;
Zhihai Xu40874a02012-10-08 17:57:03 -07001006 }
1007
fredc116d1d462012-04-20 14:47:08 -07001008 synchronized(mConnection) {
1009 if (mBluetooth != null) {
1010 try {
1011 return mBluetooth.getName();
1012 } catch (RemoteException e) {
1013 Log.e(TAG, "getName(): Unable to retrieve name remotely..Returning cached name",e);
1014 }
1015 }
1016 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001017 // mName is accessed from outside.
1018 // It alright without a lock. Here, bluetooth is off, no other thread is
1019 // changing mName
fredc0f420372012-04-12 00:02:00 -07001020 return mName;
1021 }
1022
fredc0f420372012-04-12 00:02:00 -07001023 private class BluetoothServiceConnection implements ServiceConnection {
1024
1025 private boolean mGetNameAddressOnly;
1026
1027 public void setGetNameAddressOnly(boolean getOnly) {
1028 mGetNameAddressOnly = getOnly;
1029 }
1030
1031 public boolean isGetNameAddressOnly() {
1032 return mGetNameAddressOnly;
1033 }
1034
1035 public void onServiceConnected(ComponentName className, IBinder service) {
Matthew Xieddf7e472013-03-01 18:41:02 -08001036 if (DBG) Log.d(TAG, "BluetoothServiceConnection: " + className.getClassName());
fredc0f420372012-04-12 00:02:00 -07001037 Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_SERVICE_CONNECTED);
Matthew Xieddf7e472013-03-01 18:41:02 -08001038 // TBD if (className.getClassName().equals(IBluetooth.class.getName())) {
1039 if (className.getClassName().equals("com.android.bluetooth.btservice.AdapterService")) {
1040 msg.arg1 = SERVICE_IBLUETOOTH;
1041 // } else if (className.getClassName().equals(IBluetoothGatt.class.getName())) {
1042 } else if (className.getClassName().equals("com.android.bluetooth.gatt.GattService")) {
1043 msg.arg1 = SERVICE_IBLUETOOTHGATT;
1044 } else {
1045 Log.e(TAG, "Unknown service connected: " + className.getClassName());
1046 return;
1047 }
fredc0f420372012-04-12 00:02:00 -07001048 msg.obj = service;
1049 mHandler.sendMessage(msg);
1050 }
1051
1052 public void onServiceDisconnected(ComponentName className) {
fredc0f420372012-04-12 00:02:00 -07001053 // Called if we unexpected disconnected.
Matthew Xieddf7e472013-03-01 18:41:02 -08001054 if (DBG) Log.d(TAG, "BluetoothServiceConnection, disconnected: " +
1055 className.getClassName());
fredc0f420372012-04-12 00:02:00 -07001056 Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED);
Matthew Xieddf7e472013-03-01 18:41:02 -08001057 if (className.getClassName().equals("com.android.bluetooth.btservice.AdapterService")) {
1058 msg.arg1 = SERVICE_IBLUETOOTH;
1059 } else if (className.getClassName().equals("com.android.bluetooth.gatt.GattService")) {
1060 msg.arg1 = SERVICE_IBLUETOOTHGATT;
1061 } else {
1062 Log.e(TAG, "Unknown service disconnected: " + className.getClassName());
1063 return;
1064 }
fredc0f420372012-04-12 00:02:00 -07001065 mHandler.sendMessage(msg);
1066 }
1067 }
1068
1069 private BluetoothServiceConnection mConnection = new BluetoothServiceConnection();
1070
Zhihai Xu40874a02012-10-08 17:57:03 -07001071 private class BluetoothHandler extends Handler {
1072 public BluetoothHandler(Looper looper) {
1073 super(looper);
1074 }
1075
fredc0f420372012-04-12 00:02:00 -07001076 @Override
1077 public void handleMessage(Message msg) {
1078 if (DBG) Log.d (TAG, "Message: " + msg.what);
fredc0f420372012-04-12 00:02:00 -07001079 switch (msg.what) {
1080 case MESSAGE_GET_NAME_AND_ADDRESS: {
fredc649fe492012-04-19 01:07:18 -07001081 if (DBG) Log.d(TAG,"MESSAGE_GET_NAME_AND_ADDRESS");
Matthew Xiecdce0b92012-07-12 19:06:15 -07001082 synchronized(mConnection) {
fredc0f420372012-04-12 00:02:00 -07001083 //Start bind request
Zhihai Xu40874a02012-10-08 17:57:03 -07001084 if ((mBluetooth == null) && (!mBinding)) {
fredc0f420372012-04-12 00:02:00 -07001085 if (DBG) Log.d(TAG, "Binding to service to get name and address");
1086 mConnection.setGetNameAddressOnly(true);
1087 //Start bind timeout and bind
1088 Message timeoutMsg = mHandler.obtainMessage(MESSAGE_TIMEOUT_BIND);
1089 mHandler.sendMessageDelayed(timeoutMsg,TIMEOUT_BIND_MS);
1090 Intent i = new Intent(IBluetooth.class.getName());
Dianne Hackborn221ea892013-08-04 16:50:16 -07001091 if (!doBind(i, mConnection,
Dianne Hackbornce09f5a2014-10-10 15:03:13 -07001092 Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT,
1093 UserHandle.CURRENT)) {
fredc0f420372012-04-12 00:02:00 -07001094 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
Zhihai Xu40874a02012-10-08 17:57:03 -07001095 } else {
1096 mBinding = true;
fredc0f420372012-04-12 00:02:00 -07001097 }
1098 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001099 else {
1100 Message saveMsg= mHandler.obtainMessage(MESSAGE_SAVE_NAME_AND_ADDRESS);
Zhihai Xu40874a02012-10-08 17:57:03 -07001101 saveMsg.arg1 = 0;
1102 if (mBluetooth != null) {
1103 mHandler.sendMessage(saveMsg);
1104 } else {
1105 // if enable is also called to bind the service
1106 // wait for MESSAGE_BLUETOOTH_SERVICE_CONNECTED
1107 mHandler.sendMessageDelayed(saveMsg, TIMEOUT_SAVE_MS);
1108 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001109 }
fredc0f420372012-04-12 00:02:00 -07001110 }
fredc649fe492012-04-19 01:07:18 -07001111 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001112 }
fredc0f420372012-04-12 00:02:00 -07001113 case MESSAGE_SAVE_NAME_AND_ADDRESS: {
Zhihai Xud31c3222012-10-31 16:08:57 -07001114 boolean unbind = false;
fredc649fe492012-04-19 01:07:18 -07001115 if (DBG) Log.d(TAG,"MESSAGE_SAVE_NAME_AND_ADDRESS");
Matthew Xiecdce0b92012-07-12 19:06:15 -07001116 synchronized(mConnection) {
Pavlin Radoslavovb5a479c2015-06-20 22:55:04 -07001117 if (!mEnable && mBluetooth != null && !mConnection.isGetNameAddressOnly()) {
Zhihai Xud31c3222012-10-31 16:08:57 -07001118 try {
1119 mBluetooth.enable();
1120 } catch (RemoteException e) {
1121 Log.e(TAG,"Unable to call enable()",e);
1122 }
1123 }
1124 }
Pavlin Radoslavovb5a479c2015-06-20 22:55:04 -07001125 if (mBluetooth != null && !mConnection.isGetNameAddressOnly()) waitForOnOff(true, false);
Zhihai Xud31c3222012-10-31 16:08:57 -07001126 synchronized(mConnection) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001127 if (mBluetooth != null) {
1128 String name = null;
1129 String address = null;
1130 try {
1131 name = mBluetooth.getName();
1132 address = mBluetooth.getAddress();
1133 } catch (RemoteException re) {
1134 Log.e(TAG,"",re);
1135 }
fredc0f420372012-04-12 00:02:00 -07001136
Matthew Xiecdce0b92012-07-12 19:06:15 -07001137 if (name != null && address != null) {
1138 storeNameAndAddress(name,address);
Zhihai Xu40874a02012-10-08 17:57:03 -07001139 if (mConnection.isGetNameAddressOnly()) {
Zhihai Xud31c3222012-10-31 16:08:57 -07001140 unbind = true;
Zhihai Xu40874a02012-10-08 17:57:03 -07001141 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001142 } else {
1143 if (msg.arg1 < MAX_SAVE_RETRIES) {
1144 Message retryMsg = mHandler.obtainMessage(MESSAGE_SAVE_NAME_AND_ADDRESS);
1145 retryMsg.arg1= 1+msg.arg1;
1146 if (DBG) Log.d(TAG,"Retrying name/address remote retrieval and save.....Retry count =" + retryMsg.arg1);
1147 mHandler.sendMessageDelayed(retryMsg, TIMEOUT_SAVE_MS);
1148 } else {
1149 Log.w(TAG,"Maximum name/address remote retrieval retry exceeded");
Zhihai Xu40874a02012-10-08 17:57:03 -07001150 if (mConnection.isGetNameAddressOnly()) {
Zhihai Xud31c3222012-10-31 16:08:57 -07001151 unbind = true;
Zhihai Xu40874a02012-10-08 17:57:03 -07001152 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001153 }
fredc0f420372012-04-12 00:02:00 -07001154 }
Pavlin Radoslavovb5a479c2015-06-20 22:55:04 -07001155 if (!mEnable && !mConnection.isGetNameAddressOnly()) {
Zhihai Xud31c3222012-10-31 16:08:57 -07001156 try {
1157 mBluetooth.disable();
1158 } catch (RemoteException e) {
1159 Log.e(TAG,"Unable to call disable()",e);
1160 }
1161 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001162 } else {
1163 // rebind service by Request GET NAME AND ADDRESS
1164 // if service is unbinded by disable or
1165 // MESSAGE_BLUETOOTH_SERVICE_CONNECTED is not received
1166 Message getMsg = mHandler.obtainMessage(MESSAGE_GET_NAME_AND_ADDRESS);
1167 mHandler.sendMessage(getMsg);
fredc0f420372012-04-12 00:02:00 -07001168 }
1169 }
Pavlin Radoslavovb5a479c2015-06-20 22:55:04 -07001170 if (!mEnable && mBluetooth != null && !mConnection.isGetNameAddressOnly()) {
1171 waitForOnOff(false, true);
1172 }
Zhihai Xud31c3222012-10-31 16:08:57 -07001173 if (unbind) {
1174 unbindAndFinish();
1175 }
fredc649fe492012-04-19 01:07:18 -07001176 break;
fredc649fe492012-04-19 01:07:18 -07001177 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001178 case MESSAGE_ENABLE:
fredcf2458862012-04-16 15:18:27 -07001179 if (DBG) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001180 Log.d(TAG, "MESSAGE_ENABLE: mBluetooth = " + mBluetooth);
fredc649fe492012-04-19 01:07:18 -07001181 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001182 mHandler.removeMessages(MESSAGE_RESTART_BLUETOOTH_SERVICE);
1183 mEnable = true;
Zhihai Xu401202b2012-12-03 11:36:21 -08001184 handleEnable(msg.arg1 == 1);
fredc649fe492012-04-19 01:07:18 -07001185 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001186
fredc0f420372012-04-12 00:02:00 -07001187 case MESSAGE_DISABLE:
Zhihai Xu40874a02012-10-08 17:57:03 -07001188 mHandler.removeMessages(MESSAGE_RESTART_BLUETOOTH_SERVICE);
1189 if (mEnable && mBluetooth != null) {
1190 waitForOnOff(true, false);
1191 mEnable = false;
Zhihai Xu401202b2012-12-03 11:36:21 -08001192 handleDisable();
Zhihai Xu40874a02012-10-08 17:57:03 -07001193 waitForOnOff(false, false);
1194 } else {
1195 mEnable = false;
Zhihai Xu401202b2012-12-03 11:36:21 -08001196 handleDisable();
Zhihai Xu40874a02012-10-08 17:57:03 -07001197 }
fredc0f420372012-04-12 00:02:00 -07001198 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001199
fredc0f420372012-04-12 00:02:00 -07001200 case MESSAGE_REGISTER_ADAPTER:
1201 {
1202 IBluetoothManagerCallback callback = (IBluetoothManagerCallback) msg.obj;
fredcd6883532012-04-25 17:46:13 -07001203 boolean added = mCallbacks.register(callback);
1204 Log.d(TAG,"Added callback: " + (callback == null? "null": callback) +":" +added );
fredc0f420372012-04-12 00:02:00 -07001205 }
1206 break;
1207 case MESSAGE_UNREGISTER_ADAPTER:
1208 {
1209 IBluetoothManagerCallback callback = (IBluetoothManagerCallback) msg.obj;
fredcd6883532012-04-25 17:46:13 -07001210 boolean removed = mCallbacks.unregister(callback);
1211 Log.d(TAG,"Removed callback: " + (callback == null? "null": callback) +":" + removed);
fredc0f420372012-04-12 00:02:00 -07001212 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001213 }
fredc0f420372012-04-12 00:02:00 -07001214 case MESSAGE_REGISTER_STATE_CHANGE_CALLBACK:
1215 {
1216 IBluetoothStateChangeCallback callback = (IBluetoothStateChangeCallback) msg.obj;
Matthew Xie9b693992013-10-10 11:21:40 -07001217 if (callback != null) {
1218 mStateChangeCallbacks.register(callback);
1219 }
fredc0f420372012-04-12 00:02:00 -07001220 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001221 }
fredc0f420372012-04-12 00:02:00 -07001222 case MESSAGE_UNREGISTER_STATE_CHANGE_CALLBACK:
1223 {
1224 IBluetoothStateChangeCallback callback = (IBluetoothStateChangeCallback) msg.obj;
Matthew Xie9b693992013-10-10 11:21:40 -07001225 if (callback != null) {
1226 mStateChangeCallbacks.unregister(callback);
1227 }
fredc0f420372012-04-12 00:02:00 -07001228 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001229 }
Benjamin Franze8b98922014-11-12 15:57:54 +00001230 case MESSAGE_ADD_PROXY_DELAYED:
1231 {
1232 ProfileServiceConnections psc = mProfileServices.get(
1233 new Integer(msg.arg1));
1234 if (psc == null) {
1235 break;
1236 }
1237 IBluetoothProfileServiceConnection proxy =
1238 (IBluetoothProfileServiceConnection) msg.obj;
1239 psc.addProxy(proxy);
1240 break;
1241 }
1242 case MESSAGE_BIND_PROFILE_SERVICE:
1243 {
1244 ProfileServiceConnections psc = (ProfileServiceConnections) msg.obj;
1245 removeMessages(MESSAGE_BIND_PROFILE_SERVICE, msg.obj);
1246 if (psc == null) {
1247 break;
1248 }
1249 psc.bindService();
1250 break;
1251 }
fredc0f420372012-04-12 00:02:00 -07001252 case MESSAGE_BLUETOOTH_SERVICE_CONNECTED:
1253 {
Matthew Xieddf7e472013-03-01 18:41:02 -08001254 if (DBG) Log.d(TAG,"MESSAGE_BLUETOOTH_SERVICE_CONNECTED: " + msg.arg1);
fredc0f420372012-04-12 00:02:00 -07001255
1256 IBinder service = (IBinder) msg.obj;
1257 synchronized(mConnection) {
Matthew Xieddf7e472013-03-01 18:41:02 -08001258 if (msg.arg1 == SERVICE_IBLUETOOTHGATT) {
1259 mBluetoothGatt = IBluetoothGatt.Stub.asInterface(service);
Nitin Arorad055adb2015-03-02 15:03:51 -08001260 onBluetoothGattServiceUp();
Matthew Xieddf7e472013-03-01 18:41:02 -08001261 break;
1262 } // else must be SERVICE_IBLUETOOTH
1263
1264 //Remove timeout
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001265 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
Matthew Xieddf7e472013-03-01 18:41:02 -08001266
fredc0f420372012-04-12 00:02:00 -07001267 mBinding = false;
1268 mBluetooth = IBluetooth.Stub.asInterface(service);
fredc0f420372012-04-12 00:02:00 -07001269
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001270 try {
1271 boolean enableHciSnoopLog = (Settings.Secure.getInt(mContentResolver,
1272 Settings.Secure.BLUETOOTH_HCI_LOG, 0) == 1);
1273 if (!mBluetooth.configHciSnoopLog(enableHciSnoopLog)) {
1274 Log.e(TAG,"IBluetooth.configHciSnoopLog return false");
1275 }
1276 } catch (RemoteException e) {
1277 Log.e(TAG,"Unable to call configHciSnoopLog", e);
1278 }
1279
Matthew Xiecdce0b92012-07-12 19:06:15 -07001280 if (mConnection.isGetNameAddressOnly()) {
1281 //Request GET NAME AND ADDRESS
1282 Message getMsg = mHandler.obtainMessage(MESSAGE_GET_NAME_AND_ADDRESS);
1283 mHandler.sendMessage(getMsg);
Zhihai Xu40874a02012-10-08 17:57:03 -07001284 if (!mEnable) return;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001285 }
fredc0f420372012-04-12 00:02:00 -07001286
Zhihai Xu40874a02012-10-08 17:57:03 -07001287 mConnection.setGetNameAddressOnly(false);
Matthew Xiecdce0b92012-07-12 19:06:15 -07001288 //Register callback object
fredcbf072a72012-05-09 16:52:50 -07001289 try {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001290 mBluetooth.registerCallback(mBluetoothCallback);
1291 } catch (RemoteException re) {
1292 Log.e(TAG, "Unable to register BluetoothCallback",re);
fredcbf072a72012-05-09 16:52:50 -07001293 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001294 //Inform BluetoothAdapter instances that service is up
Zhihai Xu40874a02012-10-08 17:57:03 -07001295 sendBluetoothServiceUpCallback();
1296
Matthew Xiecdce0b92012-07-12 19:06:15 -07001297 //Do enable request
1298 try {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001299 if (mQuietEnable == false) {
1300 if(!mBluetooth.enable()) {
1301 Log.e(TAG,"IBluetooth.enable() returned false");
1302 }
1303 }
1304 else
1305 {
1306 if(!mBluetooth.enableNoAutoConnect()) {
1307 Log.e(TAG,"IBluetooth.enableNoAutoConnect() returned false");
1308 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001309 }
1310 } catch (RemoteException e) {
1311 Log.e(TAG,"Unable to call enable()",e);
1312 }
Freda8c6df02012-07-11 10:25:23 -07001313 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001314
1315 if (!mEnable) {
1316 waitForOnOff(true, false);
Zhihai Xu401202b2012-12-03 11:36:21 -08001317 handleDisable();
Zhihai Xu40874a02012-10-08 17:57:03 -07001318 waitForOnOff(false, false);
1319 }
fredc649fe492012-04-19 01:07:18 -07001320 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001321 }
fredc649fe492012-04-19 01:07:18 -07001322 case MESSAGE_TIMEOUT_BIND: {
1323 Log.e(TAG, "MESSAGE_TIMEOUT_BIND");
fredc0f420372012-04-12 00:02:00 -07001324 synchronized(mConnection) {
1325 mBinding = false;
1326 }
fredc649fe492012-04-19 01:07:18 -07001327 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001328 }
fredcbf072a72012-05-09 16:52:50 -07001329 case MESSAGE_BLUETOOTH_STATE_CHANGE:
fredc0f420372012-04-12 00:02:00 -07001330 {
fredcbf072a72012-05-09 16:52:50 -07001331 int prevState = msg.arg1;
1332 int newState = msg.arg2;
1333 if (DBG) Log.d(TAG, "MESSAGE_BLUETOOTH_STATE_CHANGE: prevState = " + prevState + ", newState=" + newState);
Zhihai Xu40874a02012-10-08 17:57:03 -07001334 mState = newState;
1335 bluetoothStateChangeHandler(prevState, newState);
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001336 // handle error state transition case from TURNING_ON to OFF
1337 // unbind and rebind bluetooth service and enable bluetooth
Nitin Arorad055adb2015-03-02 15:03:51 -08001338 if ((prevState == BluetoothAdapter.STATE_BLE_TURNING_ON) &&
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001339 (newState == BluetoothAdapter.STATE_OFF) &&
1340 (mBluetooth != null) && mEnable) {
1341 recoverBluetoothServiceFromError();
1342 }
Nitin Arorad055adb2015-03-02 15:03:51 -08001343 if ((prevState == BluetoothAdapter.STATE_TURNING_ON) &&
1344 (newState == BluetoothAdapter.STATE_BLE_ON) &&
1345 (mBluetooth != null) && mEnable) {
1346 recoverBluetoothServiceFromError();
1347 }
1348 if (newState == BluetoothAdapter.STATE_ON ||
1349 newState == BluetoothAdapter.STATE_BLE_ON) {
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001350 // bluetooth is working, reset the counter
1351 if (mErrorRecoveryRetryCounter != 0) {
1352 Log.w(TAG, "bluetooth is recovered from error");
1353 mErrorRecoveryRetryCounter = 0;
1354 }
1355 }
fredc649fe492012-04-19 01:07:18 -07001356 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001357 }
fredc0f420372012-04-12 00:02:00 -07001358 case MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED:
1359 {
Matthew Xieddf7e472013-03-01 18:41:02 -08001360 Log.e(TAG, "MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED: " + msg.arg1);
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301361 synchronized(mConnection) {
Matthew Xieddf7e472013-03-01 18:41:02 -08001362 if (msg.arg1 == SERVICE_IBLUETOOTH) {
1363 // if service is unbinded already, do nothing and return
1364 if (mBluetooth == null) break;
1365 mBluetooth = null;
1366 } else if (msg.arg1 == SERVICE_IBLUETOOTHGATT) {
1367 mBluetoothGatt = null;
1368 break;
1369 } else {
1370 Log.e(TAG, "Bad msg.arg1: " + msg.arg1);
1371 break;
1372 }
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301373 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001374
1375 if (mEnable) {
1376 mEnable = false;
1377 // Send a Bluetooth Restart message
1378 Message restartMsg = mHandler.obtainMessage(
1379 MESSAGE_RESTART_BLUETOOTH_SERVICE);
1380 mHandler.sendMessageDelayed(restartMsg,
1381 SERVICE_RESTART_TIME_MS);
1382 }
1383
1384 if (!mConnection.isGetNameAddressOnly()) {
1385 sendBluetoothServiceDownCallback();
1386
1387 // Send BT state broadcast to update
1388 // the BT icon correctly
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001389 if ((mState == BluetoothAdapter.STATE_TURNING_ON) ||
1390 (mState == BluetoothAdapter.STATE_ON)) {
1391 bluetoothStateChangeHandler(BluetoothAdapter.STATE_ON,
1392 BluetoothAdapter.STATE_TURNING_OFF);
1393 mState = BluetoothAdapter.STATE_TURNING_OFF;
1394 }
1395 if (mState == BluetoothAdapter.STATE_TURNING_OFF) {
1396 bluetoothStateChangeHandler(BluetoothAdapter.STATE_TURNING_OFF,
1397 BluetoothAdapter.STATE_OFF);
1398 }
1399
1400 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
Zhihai Xu40874a02012-10-08 17:57:03 -07001401 mState = BluetoothAdapter.STATE_OFF;
1402 }
fredc649fe492012-04-19 01:07:18 -07001403 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001404 }
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301405 case MESSAGE_RESTART_BLUETOOTH_SERVICE:
1406 {
1407 Log.d(TAG, "MESSAGE_RESTART_BLUETOOTH_SERVICE:"
1408 +" Restart IBluetooth service");
1409 /* Enable without persisting the setting as
1410 it doesnt change when IBluetooth
1411 service restarts */
Zhihai Xu40874a02012-10-08 17:57:03 -07001412 mEnable = true;
Zhihai Xu401202b2012-12-03 11:36:21 -08001413 handleEnable(mQuietEnable);
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301414 break;
1415 }
1416
fredc0f420372012-04-12 00:02:00 -07001417 case MESSAGE_TIMEOUT_UNBIND:
1418 {
fredc649fe492012-04-19 01:07:18 -07001419 Log.e(TAG, "MESSAGE_TIMEOUT_UNBIND");
fredc0f420372012-04-12 00:02:00 -07001420 synchronized(mConnection) {
1421 mUnbinding = false;
1422 }
fredc649fe492012-04-19 01:07:18 -07001423 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001424 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001425
1426 case MESSAGE_USER_SWITCHED:
1427 {
1428 if (DBG) {
1429 Log.d(TAG, "MESSAGE_USER_SWITCHED");
1430 }
1431 mHandler.removeMessages(MESSAGE_USER_SWITCHED);
1432 /* disable and enable BT when detect a user switch */
1433 if (mEnable && mBluetooth != null) {
1434 synchronized (mConnection) {
1435 if (mBluetooth != null) {
1436 //Unregister callback object
1437 try {
1438 mBluetooth.unregisterCallback(mBluetoothCallback);
1439 } catch (RemoteException re) {
1440 Log.e(TAG, "Unable to unregister",re);
1441 }
1442 }
1443 }
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001444
1445 if (mState == BluetoothAdapter.STATE_TURNING_OFF) {
1446 // MESSAGE_USER_SWITCHED happened right after MESSAGE_ENABLE
1447 bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_OFF);
1448 mState = BluetoothAdapter.STATE_OFF;
1449 }
1450 if (mState == BluetoothAdapter.STATE_OFF) {
1451 bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_TURNING_ON);
1452 mState = BluetoothAdapter.STATE_TURNING_ON;
1453 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001454
1455 waitForOnOff(true, false);
1456
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001457 if (mState == BluetoothAdapter.STATE_TURNING_ON) {
1458 bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_ON);
1459 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001460
Benjamin Franze8b98922014-11-12 15:57:54 +00001461 unbindAllBluetoothProfileServices();
Zhihai Xu40874a02012-10-08 17:57:03 -07001462 // disable
Zhihai Xu401202b2012-12-03 11:36:21 -08001463 handleDisable();
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001464 // Pbap service need receive STATE_TURNING_OFF intent to close
1465 bluetoothStateChangeHandler(BluetoothAdapter.STATE_ON,
1466 BluetoothAdapter.STATE_TURNING_OFF);
Zhihai Xu40874a02012-10-08 17:57:03 -07001467
1468 waitForOnOff(false, true);
1469
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001470 bluetoothStateChangeHandler(BluetoothAdapter.STATE_TURNING_OFF,
Zhihai Xu40874a02012-10-08 17:57:03 -07001471 BluetoothAdapter.STATE_OFF);
Zhihai Xu40874a02012-10-08 17:57:03 -07001472 sendBluetoothServiceDownCallback();
1473 synchronized (mConnection) {
1474 if (mBluetooth != null) {
1475 mBluetooth = null;
1476 //Unbind
1477 mContext.unbindService(mConnection);
1478 }
1479 }
1480 SystemClock.sleep(100);
1481
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001482 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
1483 mState = BluetoothAdapter.STATE_OFF;
Zhihai Xu40874a02012-10-08 17:57:03 -07001484 // enable
Zhihai Xu401202b2012-12-03 11:36:21 -08001485 handleEnable(mQuietEnable);
John Spurlock8a985d22014-02-25 09:40:05 -05001486 } else if (mBinding || mBluetooth != null) {
Zhihai Xu40874a02012-10-08 17:57:03 -07001487 Message userMsg = mHandler.obtainMessage(MESSAGE_USER_SWITCHED);
1488 userMsg.arg2 = 1 + msg.arg2;
1489 // if user is switched when service is being binding
1490 // delay sending MESSAGE_USER_SWITCHED
1491 mHandler.sendMessageDelayed(userMsg, USER_SWITCHED_TIME_MS);
1492 if (DBG) {
1493 Log.d(TAG, "delay MESSAGE_USER_SWITCHED " + userMsg.arg2);
1494 }
John Spurlock8a985d22014-02-25 09:40:05 -05001495 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001496 break;
1497 }
fredc0f420372012-04-12 00:02:00 -07001498 }
1499 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001500 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001501
Zhihai Xu401202b2012-12-03 11:36:21 -08001502 private void handleEnable(boolean quietMode) {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001503 mQuietEnable = quietMode;
1504
Matthew Xiecdce0b92012-07-12 19:06:15 -07001505 synchronized(mConnection) {
Zhihai Xu40874a02012-10-08 17:57:03 -07001506 if ((mBluetooth == null) && (!mBinding)) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001507 //Start bind timeout and bind
1508 Message timeoutMsg=mHandler.obtainMessage(MESSAGE_TIMEOUT_BIND);
1509 mHandler.sendMessageDelayed(timeoutMsg,TIMEOUT_BIND_MS);
1510 mConnection.setGetNameAddressOnly(false);
1511 Intent i = new Intent(IBluetooth.class.getName());
Dianne Hackbornce09f5a2014-10-10 15:03:13 -07001512 if (!doBind(i, mConnection,Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT,
1513 UserHandle.CURRENT)) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001514 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
Zhihai Xu40874a02012-10-08 17:57:03 -07001515 } else {
1516 mBinding = true;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001517 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001518 } else if (mBluetooth != null) {
1519 if (mConnection.isGetNameAddressOnly()) {
1520 // if GetNameAddressOnly is set, we can clear this flag,
1521 // so the service won't be unbind
1522 // after name and address are saved
1523 mConnection.setGetNameAddressOnly(false);
1524 //Register callback object
1525 try {
1526 mBluetooth.registerCallback(mBluetoothCallback);
1527 } catch (RemoteException re) {
1528 Log.e(TAG, "Unable to register BluetoothCallback",re);
1529 }
1530 //Inform BluetoothAdapter instances that service is up
1531 sendBluetoothServiceUpCallback();
1532 }
1533
Matthew Xiecdce0b92012-07-12 19:06:15 -07001534 //Enable bluetooth
1535 try {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001536 if (!mQuietEnable) {
1537 if(!mBluetooth.enable()) {
1538 Log.e(TAG,"IBluetooth.enable() returned false");
1539 }
1540 }
1541 else {
1542 if(!mBluetooth.enableNoAutoConnect()) {
1543 Log.e(TAG,"IBluetooth.enableNoAutoConnect() returned false");
1544 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001545 }
1546 } catch (RemoteException e) {
1547 Log.e(TAG,"Unable to call enable()",e);
1548 }
1549 }
1550 }
1551 }
1552
Dianne Hackborn221ea892013-08-04 16:50:16 -07001553 boolean doBind(Intent intent, ServiceConnection conn, int flags, UserHandle user) {
1554 ComponentName comp = intent.resolveSystemService(mContext.getPackageManager(), 0);
1555 intent.setComponent(comp);
1556 if (comp == null || !mContext.bindServiceAsUser(intent, conn, flags, user)) {
1557 Log.e(TAG, "Fail to bind to: " + intent);
1558 return false;
1559 }
1560 return true;
1561 }
1562
Zhihai Xu401202b2012-12-03 11:36:21 -08001563 private void handleDisable() {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001564 synchronized(mConnection) {
Zhihai Xu40874a02012-10-08 17:57:03 -07001565 // don't need to disable if GetNameAddressOnly is set,
1566 // service will be unbinded after Name and Address are saved
1567 if ((mBluetooth != null) && (!mConnection.isGetNameAddressOnly())) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001568 if (DBG) Log.d(TAG,"Sending off request.");
1569
1570 try {
1571 if(!mBluetooth.disable()) {
1572 Log.e(TAG,"IBluetooth.disable() returned false");
1573 }
1574 } catch (RemoteException e) {
1575 Log.e(TAG,"Unable to call disable()",e);
1576 }
1577 }
1578 }
1579 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001580
1581 private boolean checkIfCallerIsForegroundUser() {
1582 int foregroundUser;
1583 int callingUser = UserHandle.getCallingUserId();
Martijn Coenen8385c5a2012-11-29 10:14:16 -08001584 int callingUid = Binder.getCallingUid();
Zhihai Xu40874a02012-10-08 17:57:03 -07001585 long callingIdentity = Binder.clearCallingIdentity();
Benjamin Franze8b98922014-11-12 15:57:54 +00001586 UserManager um = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
1587 UserInfo ui = um.getProfileParent(callingUser);
1588 int parentUser = (ui != null) ? ui.id : UserHandle.USER_NULL;
Martijn Coenen8385c5a2012-11-29 10:14:16 -08001589 int callingAppId = UserHandle.getAppId(callingUid);
Zhihai Xu40874a02012-10-08 17:57:03 -07001590 boolean valid = false;
1591 try {
1592 foregroundUser = ActivityManager.getCurrentUser();
Martijn Coenen8385c5a2012-11-29 10:14:16 -08001593 valid = (callingUser == foregroundUser) ||
Benjamin Franze8b98922014-11-12 15:57:54 +00001594 parentUser == foregroundUser ||
Adrian Roosbd9a9a52014-08-18 15:31:57 +02001595 callingAppId == Process.NFC_UID ||
1596 callingAppId == mSystemUiUid;
Zhihai Xu40874a02012-10-08 17:57:03 -07001597 if (DBG) {
1598 Log.d(TAG, "checkIfCallerIsForegroundUser: valid=" + valid
1599 + " callingUser=" + callingUser
Benjamin Franze8b98922014-11-12 15:57:54 +00001600 + " parentUser=" + parentUser
Zhihai Xu40874a02012-10-08 17:57:03 -07001601 + " foregroundUser=" + foregroundUser);
1602 }
1603 } finally {
1604 Binder.restoreCallingIdentity(callingIdentity);
1605 }
1606 return valid;
1607 }
1608
Nitin Arorad055adb2015-03-02 15:03:51 -08001609 private void sendBleStateChanged(int prevState, int newState) {
1610 if (DBG) Log.d(TAG,"BLE State Change Intent: " + prevState + " -> " + newState);
1611 // Send broadcast message to everyone else
1612 Intent intent = new Intent(BluetoothAdapter.ACTION_BLE_STATE_CHANGED);
1613 intent.putExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE, prevState);
1614 intent.putExtra(BluetoothAdapter.EXTRA_STATE, newState);
1615 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1616 mContext.sendBroadcastAsUser(intent, UserHandle.ALL, BLUETOOTH_PERM);
1617 }
1618
Zhihai Xu40874a02012-10-08 17:57:03 -07001619 private void bluetoothStateChangeHandler(int prevState, int newState) {
Nitin Arorad055adb2015-03-02 15:03:51 -08001620 boolean isStandardBroadcast = true;
Zhihai Xu40874a02012-10-08 17:57:03 -07001621 if (prevState != newState) {
1622 //Notify all proxy objects first of adapter state change
Nitin Arorad055adb2015-03-02 15:03:51 -08001623 if (newState == BluetoothAdapter.STATE_BLE_ON
1624 || newState == BluetoothAdapter.STATE_OFF) {
1625 boolean intermediate_off = (prevState == BluetoothAdapter.STATE_TURNING_OFF
1626 && newState == BluetoothAdapter.STATE_BLE_ON);
Zhihai Xu40874a02012-10-08 17:57:03 -07001627
Nitin Arorad055adb2015-03-02 15:03:51 -08001628 if (newState == BluetoothAdapter.STATE_OFF) {
1629 // If Bluetooth is off, send service down event to proxy objects, and unbind
1630 if (DBG) Log.d(TAG, "Bluetooth is complete turn off");
1631 if (canUnbindBluetoothService()) {
1632 if (DBG) Log.d(TAG, "Good to unbind!");
Matthew Xieddf7e472013-03-01 18:41:02 -08001633 sendBluetoothServiceDownCallback();
1634 unbindAndFinish();
Nitin Arorad055adb2015-03-02 15:03:51 -08001635 sendBleStateChanged(prevState, newState);
1636 // Don't broadcast as it has already been broadcast before
1637 isStandardBroadcast = false;
Matthew Xieddf7e472013-03-01 18:41:02 -08001638 }
Nitin Arorad055adb2015-03-02 15:03:51 -08001639
1640 } else if (!intermediate_off) {
1641 // connect to GattService
1642 if (DBG) Log.d(TAG, "Bluetooth is in LE only mode");
1643 if (mBluetoothGatt != null) {
1644 if (DBG) Log.d(TAG, "Calling BluetoothGattServiceUp");
1645 onBluetoothGattServiceUp();
1646 } else {
1647 if (DBG) Log.d(TAG, "Binding Bluetooth GATT service");
1648 if (mContext.getPackageManager().hasSystemFeature(
1649 PackageManager.FEATURE_BLUETOOTH_LE)) {
1650 Intent i = new Intent(IBluetoothGatt.class.getName());
1651 doBind(i, mConnection, Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT, UserHandle.CURRENT);
1652 }
1653 }
1654 sendBleStateChanged(prevState, newState);
1655 //Don't broadcase this as std intent
1656 isStandardBroadcast = false;
1657
1658 } else if (intermediate_off){
1659 if (DBG) Log.d(TAG, "Intermediate off, back to LE only mode");
1660 // For LE only mode, broadcast as is
1661 sendBleStateChanged(prevState, newState);
1662 sendBluetoothStateCallback(false); // BT is OFF for general users
1663 // Broadcast as STATE_OFF
1664 newState = BluetoothAdapter.STATE_OFF;
1665 sendBrEdrDownCallback();
Zhihai Xu40874a02012-10-08 17:57:03 -07001666 }
Nitin Arorad055adb2015-03-02 15:03:51 -08001667 } else if (newState == BluetoothAdapter.STATE_ON) {
1668 boolean isUp = (newState==BluetoothAdapter.STATE_ON);
1669 sendBluetoothStateCallback(isUp);
1670 sendBleStateChanged(prevState, newState);
1671
1672 } else if (newState == BluetoothAdapter.STATE_BLE_TURNING_ON
1673 || newState == BluetoothAdapter.STATE_BLE_TURNING_OFF ) {
1674 sendBleStateChanged(prevState, newState);
1675 isStandardBroadcast = false;
1676
1677 } else if (newState == BluetoothAdapter.STATE_TURNING_ON
1678 || newState == BluetoothAdapter.STATE_TURNING_OFF) {
1679 sendBleStateChanged(prevState, newState);
Zhihai Xu40874a02012-10-08 17:57:03 -07001680 }
1681
Nitin Arorad055adb2015-03-02 15:03:51 -08001682 if (isStandardBroadcast) {
1683 if (prevState == BluetoothAdapter.STATE_BLE_ON) {
1684 // Show prevState of BLE_ON as OFF to standard users
1685 prevState = BluetoothAdapter.STATE_OFF;
1686 }
1687 Intent intent = new Intent(BluetoothAdapter.ACTION_STATE_CHANGED);
1688 intent.putExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE, prevState);
1689 intent.putExtra(BluetoothAdapter.EXTRA_STATE, newState);
1690 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1691 mContext.sendBroadcastAsUser(intent, UserHandle.ALL, BLUETOOTH_PERM);
1692 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001693 }
1694 }
1695
1696 /**
1697 * if on is true, wait for state become ON
1698 * if off is true, wait for state become OFF
1699 * if both on and off are false, wait for state not ON
1700 */
1701 private boolean waitForOnOff(boolean on, boolean off) {
1702 int i = 0;
1703 while (i < 10) {
1704 synchronized(mConnection) {
1705 try {
1706 if (mBluetooth == null) break;
1707 if (on) {
1708 if (mBluetooth.getState() == BluetoothAdapter.STATE_ON) return true;
1709 } else if (off) {
1710 if (mBluetooth.getState() == BluetoothAdapter.STATE_OFF) return true;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07001711 } else {
Zhihai Xu40874a02012-10-08 17:57:03 -07001712 if (mBluetooth.getState() != BluetoothAdapter.STATE_ON) return true;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07001713 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001714 } catch (RemoteException e) {
1715 Log.e(TAG, "getState()", e);
1716 break;
1717 }
1718 }
1719 if (on || off) {
1720 SystemClock.sleep(300);
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07001721 } else {
Zhihai Xu40874a02012-10-08 17:57:03 -07001722 SystemClock.sleep(50);
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07001723 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001724 i++;
1725 }
1726 Log.e(TAG,"waitForOnOff time out");
1727 return false;
1728 }
Zhihai Xu681ae7f2012-11-12 15:14:18 -08001729
Zhihai Xu401202b2012-12-03 11:36:21 -08001730 private void sendDisableMsg() {
1731 mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_DISABLE));
1732 }
1733
1734 private void sendEnableMsg(boolean quietMode) {
1735 mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_ENABLE,
1736 quietMode ? 1 : 0, 0));
1737 }
1738
Zhihai Xu681ae7f2012-11-12 15:14:18 -08001739 private boolean canUnbindBluetoothService() {
1740 synchronized(mConnection) {
1741 //Only unbind with mEnable flag not set
1742 //For race condition: disable and enable back-to-back
1743 //Avoid unbind right after enable due to callback from disable
1744 //Only unbind with Bluetooth at OFF state
1745 //Only unbind without any MESSAGE_BLUETOOTH_STATE_CHANGE message
1746 try {
1747 if (mEnable || (mBluetooth == null)) return false;
1748 if (mHandler.hasMessages(MESSAGE_BLUETOOTH_STATE_CHANGE)) return false;
1749 return (mBluetooth.getState() == BluetoothAdapter.STATE_OFF);
1750 } catch (RemoteException e) {
1751 Log.e(TAG, "getState()", e);
1752 }
1753 }
1754 return false;
1755 }
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001756
1757 private void recoverBluetoothServiceFromError() {
1758 Log.e(TAG,"recoverBluetoothServiceFromError");
1759 synchronized (mConnection) {
1760 if (mBluetooth != null) {
1761 //Unregister callback object
1762 try {
1763 mBluetooth.unregisterCallback(mBluetoothCallback);
1764 } catch (RemoteException re) {
1765 Log.e(TAG, "Unable to unregister",re);
1766 }
1767 }
1768 }
1769
1770 SystemClock.sleep(500);
1771
1772 // disable
1773 handleDisable();
1774
1775 waitForOnOff(false, true);
1776
1777 sendBluetoothServiceDownCallback();
1778 synchronized (mConnection) {
1779 if (mBluetooth != null) {
1780 mBluetooth = null;
1781 //Unbind
1782 mContext.unbindService(mConnection);
1783 }
1784 }
1785
1786 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
1787 mState = BluetoothAdapter.STATE_OFF;
1788
1789 mEnable = false;
1790
1791 if (mErrorRecoveryRetryCounter++ < MAX_ERROR_RESTART_RETRIES) {
1792 // Send a Bluetooth Restart message to reenable bluetooth
1793 Message restartMsg = mHandler.obtainMessage(
1794 MESSAGE_RESTART_BLUETOOTH_SERVICE);
1795 mHandler.sendMessageDelayed(restartMsg, ERROR_RESTART_TIME_MS);
1796 } else {
1797 // todo: notify user to power down and power up phone to make bluetooth work.
1798 }
1799 }
Mike Lockwood726d4de2014-10-28 14:06:28 -07001800
1801 @Override
1802 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Mike Lockwood75b52bb2014-12-18 14:16:36 -08001803 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DUMP, TAG);
1804
Andre Eisenbach14dcb5f2014-12-05 09:31:30 -08001805 writer.println("Bluetooth Status");
1806 writer.println(" enabled: " + mEnable);
1807 writer.println(" state: " + mState);
1808 writer.println(" address: " + mAddress);
1809 writer.println(" name: " + mName + "\n");
1810 writer.flush();
1811
Mike Lockwood726d4de2014-10-28 14:06:28 -07001812 if (mBluetooth == null) {
1813 writer.println("Bluetooth Service not connected");
1814 } else {
Andre Eisenbach14dcb5f2014-12-05 09:31:30 -08001815 ParcelFileDescriptor pfd = null;
Mike Lockwood726d4de2014-10-28 14:06:28 -07001816 try {
Sharvil Nanavati7c250052015-06-20 12:05:52 -07001817 writer.println("Bonded devices:");
1818 for (BluetoothDevice device : mBluetooth.getBondedDevices()) {
1819 writer.println(" " + device.getAddress() +
1820 " [" + DEVICE_TYPE_NAMES[device.getType()] + "] " +
1821 device.getName());
1822 }
1823 writer.flush();
1824
Andre Eisenbach14dcb5f2014-12-05 09:31:30 -08001825 pfd = ParcelFileDescriptor.dup(fd);
1826 mBluetooth.dump(pfd);
Mike Lockwood726d4de2014-10-28 14:06:28 -07001827 } catch (RemoteException re) {
1828 writer.println("RemoteException while calling Bluetooth Service");
Andre Eisenbach14dcb5f2014-12-05 09:31:30 -08001829 } catch (IOException ioe) {
1830 writer.println("IOException attempting to dup() fd");
1831 } finally {
1832 if (pfd != null) {
1833 try {
1834 pfd.close();
1835 } catch (IOException ioe) {
1836 writer.println("IOException attempting to close() fd");
1837 }
1838 }
Mike Lockwood726d4de2014-10-28 14:06:28 -07001839 }
1840 }
1841 }
fredc0f420372012-04-12 00:02:00 -07001842}