blob: 66fd36fb0f1e49a6ac963eba88886492f1a3cd91 [file] [log] [blame]
fredc0f420372012-04-12 00:02:00 -07001/*
Zhihai Xufa0fd392012-10-23 17:31:56 -07002 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
fredc0f420372012-04-12 00:02:00 -070015 */
16
17package com.android.server;
18
Svet Ganov408abf72015-05-12 19:13:36 -070019import android.Manifest;
Zhihai Xu40874a02012-10-08 17:57:03 -070020import android.app.ActivityManager;
fredc0f420372012-04-12 00:02:00 -070021import android.bluetooth.BluetoothAdapter;
Benjamin Franze8b98922014-11-12 15:57:54 +000022import android.bluetooth.BluetoothProfile;
fredc0f420372012-04-12 00:02:00 -070023import android.bluetooth.IBluetooth;
Matthew Xieddf7e472013-03-01 18:41:02 -080024import android.bluetooth.IBluetoothGatt;
fredcbf072a72012-05-09 16:52:50 -070025import android.bluetooth.IBluetoothCallback;
Benjamin Franze8b98922014-11-12 15:57:54 +000026import android.bluetooth.IBluetoothHeadset;
fredc0f420372012-04-12 00:02:00 -070027import android.bluetooth.IBluetoothManager;
28import android.bluetooth.IBluetoothManagerCallback;
Benjamin Franze8b98922014-11-12 15:57:54 +000029import android.bluetooth.IBluetoothProfileServiceConnection;
fredc0f420372012-04-12 00:02:00 -070030import android.bluetooth.IBluetoothStateChangeCallback;
fredc0f420372012-04-12 00:02:00 -070031import android.content.BroadcastReceiver;
32import android.content.ComponentName;
33import android.content.ContentResolver;
34import android.content.Context;
35import android.content.Intent;
36import android.content.IntentFilter;
37import android.content.ServiceConnection;
Matthew Xie32ab77b2013-05-08 19:26:57 -070038import android.content.pm.PackageManager;
Benjamin Franze8b98922014-11-12 15:57:54 +000039import android.content.pm.UserInfo;
Zhihai Xu40874a02012-10-08 17:57:03 -070040import android.os.Binder;
fredc0f420372012-04-12 00:02:00 -070041import android.os.Handler;
fredc0f420372012-04-12 00:02:00 -070042import android.os.IBinder;
Zhihai Xu40874a02012-10-08 17:57:03 -070043import android.os.Looper;
fredc0f420372012-04-12 00:02:00 -070044import android.os.Message;
Andre Eisenbach14dcb5f2014-12-05 09:31:30 -080045import android.os.ParcelFileDescriptor;
Zhihai Xu40874a02012-10-08 17:57:03 -070046import android.os.Process;
fredcd6883532012-04-25 17:46:13 -070047import android.os.RemoteCallbackList;
fredc0f420372012-04-12 00:02:00 -070048import android.os.RemoteException;
Zhihai Xu40874a02012-10-08 17:57:03 -070049import android.os.SystemClock;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070050import android.os.UserHandle;
Benjamin Franze8b98922014-11-12 15:57:54 +000051import android.os.UserManager;
fredc0f420372012-04-12 00:02:00 -070052import android.provider.Settings;
Wei Wang67d84162015-04-26 17:04:29 -070053import android.provider.Settings.SettingNotFoundException;
fredc0f420372012-04-12 00:02:00 -070054import android.util.Log;
Mike Lockwood726d4de2014-10-28 14:06:28 -070055
56import java.io.FileDescriptor;
Andre Eisenbach14dcb5f2014-12-05 09:31:30 -080057import java.io.IOException;
Mike Lockwood726d4de2014-10-28 14:06:28 -070058import java.io.PrintWriter;
59
Benjamin Franze8b98922014-11-12 15:57:54 +000060import java.util.HashMap;
61import java.util.Map;
Benjamin Franze8b98922014-11-12 15:57:54 +000062
Nitin Arora6ddbb5e2015-03-02 15:03:51 -080063import java.util.*;
fredc0f420372012-04-12 00:02:00 -070064class BluetoothManagerService extends IBluetoothManager.Stub {
65 private static final String TAG = "BluetoothManagerService";
66 private static final boolean DBG = true;
67
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
fredc0f420372012-04-12 00:02:00 -0700119 private final Context mContext;
Nitin Arorad055adb2015-03-02 15:03:51 -0800120 private static int mBleAppCount = 0;
Matthew Xiecdce0b92012-07-12 19:06:15 -0700121
122 // Locks are not provided for mName and mAddress.
123 // They are accessed in handler or broadcast receiver, same thread context.
fredc0f420372012-04-12 00:02:00 -0700124 private String mAddress;
125 private String mName;
Matthew Xie6fde3092012-07-11 17:10:07 -0700126 private final ContentResolver mContentResolver;
127 private final RemoteCallbackList<IBluetoothManagerCallback> mCallbacks;
128 private final RemoteCallbackList<IBluetoothStateChangeCallback> mStateChangeCallbacks;
fredc649fe492012-04-19 01:07:18 -0700129 private IBluetooth mBluetooth;
Matthew Xieddf7e472013-03-01 18:41:02 -0800130 private IBluetoothGatt mBluetoothGatt;
fredc649fe492012-04-19 01:07:18 -0700131 private boolean mBinding;
132 private boolean mUnbinding;
Zhihai Xu401202b2012-12-03 11:36:21 -0800133 // used inside handler thread
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700134 private boolean mQuietEnable = false;
Zhihai Xu401202b2012-12-03 11:36:21 -0800135 // configuarion from external IBinder call which is used to
136 // synchronize with broadcast receiver.
137 private boolean mQuietEnableExternal;
138 // configuarion from external IBinder call which is used to
139 // synchronize with broadcast receiver.
140 private boolean mEnableExternal;
141 // used inside handler thread
Zhihai Xu40874a02012-10-08 17:57:03 -0700142 private boolean mEnable;
143 private int mState;
Zhihai Xu40874a02012-10-08 17:57:03 -0700144 private final BluetoothHandler mHandler;
Zhihai Xudd9d17d2013-01-08 17:05:58 -0800145 private int mErrorRecoveryRetryCounter;
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200146 private final int mSystemUiUid;
fredc0f420372012-04-12 00:02:00 -0700147
Benjamin Franze8b98922014-11-12 15:57:54 +0000148 // Save a ProfileServiceConnections object for each of the bound
149 // bluetooth profile services
150 private final Map <Integer, ProfileServiceConnections> mProfileServices =
151 new HashMap <Integer, ProfileServiceConnections>();
152
fredc649fe492012-04-19 01:07:18 -0700153 private void registerForAirplaneMode(IntentFilter filter) {
154 final ContentResolver resolver = mContext.getContentResolver();
Christopher Tatec09cdce2012-09-10 16:50:14 -0700155 final String airplaneModeRadios = Settings.Global.getString(resolver,
156 Settings.Global.AIRPLANE_MODE_RADIOS);
157 final String toggleableRadios = Settings.Global.getString(resolver,
158 Settings.Global.AIRPLANE_MODE_TOGGLEABLE_RADIOS);
fredc649fe492012-04-19 01:07:18 -0700159 boolean mIsAirplaneSensitive = airplaneModeRadios == null ? true :
Christopher Tatec09cdce2012-09-10 16:50:14 -0700160 airplaneModeRadios.contains(Settings.Global.RADIO_BLUETOOTH);
fredc649fe492012-04-19 01:07:18 -0700161 if (mIsAirplaneSensitive) {
162 filter.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED);
163 }
164 }
165
fredcbf072a72012-05-09 16:52:50 -0700166 private final IBluetoothCallback mBluetoothCallback = new IBluetoothCallback.Stub() {
167 @Override
168 public void onBluetoothStateChange(int prevState, int newState) throws RemoteException {
169 Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_STATE_CHANGE,prevState,newState);
170 mHandler.sendMessage(msg);
171 }
172 };
173
174 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
fredc0f420372012-04-12 00:02:00 -0700175 @Override
176 public void onReceive(Context context, Intent intent) {
177 String action = intent.getAction();
fredcbf072a72012-05-09 16:52:50 -0700178 if (BluetoothAdapter.ACTION_LOCAL_NAME_CHANGED.equals(action)) {
fredc0f420372012-04-12 00:02:00 -0700179 String newName = intent.getStringExtra(BluetoothAdapter.EXTRA_LOCAL_NAME);
Freda8c6df02012-07-11 10:25:23 -0700180 if (DBG) Log.d(TAG, "Bluetooth Adapter name changed to " + newName);
fredc0f420372012-04-12 00:02:00 -0700181 if (newName != null) {
182 storeNameAndAddress(newName, null);
183 }
fredc649fe492012-04-19 01:07:18 -0700184 } else if (Intent.ACTION_AIRPLANE_MODE_CHANGED.equals(action)) {
Zhihai Xu401202b2012-12-03 11:36:21 -0800185 synchronized(mReceiver) {
186 if (isBluetoothPersistedStateOn()) {
187 if (isAirplaneModeOn()) {
188 persistBluetoothSetting(BLUETOOTH_ON_AIRPLANE);
189 } else {
190 persistBluetoothSetting(BLUETOOTH_ON_BLUETOOTH);
191 }
192 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800193
194 int st = BluetoothAdapter.STATE_OFF;
195 if (mBluetooth != null) {
196 try {
197 st = mBluetooth.getState();
198 } catch (RemoteException e) {
199 Log.e(TAG,"Unable to call getState", e);
200 }
201 }
202 Log.d(TAG, "state" + st);
203
Zhihai Xu401202b2012-12-03 11:36:21 -0800204 if (isAirplaneModeOn()) {
Nitin Arorad055adb2015-03-02 15:03:51 -0800205 // Clear registered LE apps to force shut-off
206 synchronized (this) {
207 mBleAppCount = 0;
Nitin Arora11f83882015-05-07 18:45:44 -0700208 mBleApps.clear();
Nitin Arorad055adb2015-03-02 15:03:51 -0800209 }
210 if (st == BluetoothAdapter.STATE_BLE_ON) {
211 //if state is BLE_ON make sure you trigger disableBLE part
212 try {
213 if (mBluetooth != null) {
214 mBluetooth.onBrEdrDown();
215 mEnableExternal = false;
216 }
217 } catch(RemoteException e) {
218 Log.e(TAG,"Unable to call onBrEdrDown", e);
219 }
220 } else if (st == BluetoothAdapter.STATE_ON){
221 // disable without persisting the setting
222 Log.d(TAG, "Calling disable");
223 sendDisableMsg();
224 }
Zhihai Xu401202b2012-12-03 11:36:21 -0800225 } else if (mEnableExternal) {
226 // enable without persisting the setting
Nitin Arorad055adb2015-03-02 15:03:51 -0800227 Log.d(TAG, "Calling enable");
Zhihai Xu401202b2012-12-03 11:36:21 -0800228 sendEnableMsg(mQuietEnableExternal);
229 }
fredc649fe492012-04-19 01:07:18 -0700230 }
Zhihai Xu40874a02012-10-08 17:57:03 -0700231 } else if (Intent.ACTION_USER_SWITCHED.equals(action)) {
232 mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_USER_SWITCHED,
233 intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0), 0));
Zhihai Xu401202b2012-12-03 11:36:21 -0800234 } else if (Intent.ACTION_BOOT_COMPLETED.equals(action)) {
235 synchronized(mReceiver) {
236 if (mEnableExternal && isBluetoothPersistedStateOnBluetooth()) {
237 //Enable
238 if (DBG) Log.d(TAG, "Auto-enabling Bluetooth.");
239 sendEnableMsg(mQuietEnableExternal);
240 }
241 }
fredc0f420372012-04-12 00:02:00 -0700242 }
243 }
244 };
245
246 BluetoothManagerService(Context context) {
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700247 mHandler = new BluetoothHandler(IoThread.get().getLooper());
Zhihai Xu40874a02012-10-08 17:57:03 -0700248
fredc0f420372012-04-12 00:02:00 -0700249 mContext = context;
250 mBluetooth = null;
Nitin Arorad055adb2015-03-02 15:03:51 -0800251 mBluetoothGatt = null;
fredc0f420372012-04-12 00:02:00 -0700252 mBinding = false;
253 mUnbinding = false;
Zhihai Xu40874a02012-10-08 17:57:03 -0700254 mEnable = false;
255 mState = BluetoothAdapter.STATE_OFF;
Zhihai Xu401202b2012-12-03 11:36:21 -0800256 mQuietEnableExternal = false;
257 mEnableExternal = false;
fredc0f420372012-04-12 00:02:00 -0700258 mAddress = null;
259 mName = null;
Zhihai Xudd9d17d2013-01-08 17:05:58 -0800260 mErrorRecoveryRetryCounter = 0;
fredc0f420372012-04-12 00:02:00 -0700261 mContentResolver = context.getContentResolver();
fredcd6883532012-04-25 17:46:13 -0700262 mCallbacks = new RemoteCallbackList<IBluetoothManagerCallback>();
263 mStateChangeCallbacks = new RemoteCallbackList<IBluetoothStateChangeCallback>();
Zhihai Xu401202b2012-12-03 11:36:21 -0800264 IntentFilter filter = new IntentFilter(Intent.ACTION_BOOT_COMPLETED);
Matthew Xie6fde3092012-07-11 17:10:07 -0700265 filter.addAction(BluetoothAdapter.ACTION_LOCAL_NAME_CHANGED);
Zhihai Xu40874a02012-10-08 17:57:03 -0700266 filter.addAction(Intent.ACTION_USER_SWITCHED);
Matthew Xie6fde3092012-07-11 17:10:07 -0700267 registerForAirplaneMode(filter);
Dianne Hackbornd83a0962014-05-02 16:28:33 -0700268 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
Matthew Xie6fde3092012-07-11 17:10:07 -0700269 mContext.registerReceiver(mReceiver, filter);
fredc0f420372012-04-12 00:02:00 -0700270 loadStoredNameAndAddress();
Zhihai Xu401202b2012-12-03 11:36:21 -0800271 if (isBluetoothPersistedStateOn()) {
272 mEnableExternal = true;
fredc0f420372012-04-12 00:02:00 -0700273 }
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200274
275 int sysUiUid = -1;
276 try {
277 sysUiUid = mContext.getPackageManager().getPackageUid("com.android.systemui",
278 UserHandle.USER_OWNER);
279 } catch (PackageManager.NameNotFoundException e) {
280 Log.wtf(TAG, "Unable to resolve SystemUI's UID.", e);
281 }
282 mSystemUiUid = sysUiUid;
fredc0f420372012-04-12 00:02:00 -0700283 }
284
fredc649fe492012-04-19 01:07:18 -0700285 /**
286 * Returns true if airplane mode is currently on
287 */
288 private final boolean isAirplaneModeOn() {
Christopher Tatec09cdce2012-09-10 16:50:14 -0700289 return Settings.Global.getInt(mContext.getContentResolver(),
290 Settings.Global.AIRPLANE_MODE_ON, 0) == 1;
fredc649fe492012-04-19 01:07:18 -0700291 }
292
293 /**
294 * Returns true if the Bluetooth saved state is "on"
295 */
296 private final boolean isBluetoothPersistedStateOn() {
Jeff Brownbf6f6f92012-09-25 15:03:20 -0700297 return Settings.Global.getInt(mContentResolver,
Zhihai Xu401202b2012-12-03 11:36:21 -0800298 Settings.Global.BLUETOOTH_ON, 0) != BLUETOOTH_OFF;
299 }
300
301 /**
302 * Returns true if the Bluetooth saved state is BLUETOOTH_ON_BLUETOOTH
303 */
304 private final boolean isBluetoothPersistedStateOnBluetooth() {
305 return Settings.Global.getInt(mContentResolver,
306 Settings.Global.BLUETOOTH_ON, 0) == BLUETOOTH_ON_BLUETOOTH;
fredc649fe492012-04-19 01:07:18 -0700307 }
308
309 /**
310 * Save the Bluetooth on/off state
311 *
312 */
Zhihai Xu401202b2012-12-03 11:36:21 -0800313 private void persistBluetoothSetting(int value) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -0700314 Settings.Global.putInt(mContext.getContentResolver(),
315 Settings.Global.BLUETOOTH_ON,
Zhihai Xu401202b2012-12-03 11:36:21 -0800316 value);
fredc649fe492012-04-19 01:07:18 -0700317 }
318
319 /**
320 * Returns true if the Bluetooth Adapter's name and address is
321 * locally cached
322 * @return
323 */
fredc0f420372012-04-12 00:02:00 -0700324 private boolean isNameAndAddressSet() {
325 return mName !=null && mAddress!= null && mName.length()>0 && mAddress.length()>0;
326 }
327
fredc649fe492012-04-19 01:07:18 -0700328 /**
329 * Retrieve the Bluetooth Adapter's name and address and save it in
330 * in the local cache
331 */
fredc0f420372012-04-12 00:02:00 -0700332 private void loadStoredNameAndAddress() {
333 if (DBG) Log.d(TAG, "Loading stored name and address");
Zhihai Xud31c3222012-10-31 16:08:57 -0700334 if (mContext.getResources().getBoolean
335 (com.android.internal.R.bool.config_bluetooth_address_validation) &&
336 Settings.Secure.getInt(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDR_VALID, 0) == 0) {
337 // if the valid flag is not set, don't load the address and name
338 if (DBG) Log.d(TAG, "invalid bluetooth name and address stored");
339 return;
340 }
fredc0f420372012-04-12 00:02:00 -0700341 mName = Settings.Secure.getString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_NAME);
342 mAddress = Settings.Secure.getString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDRESS);
Zhihai Xud31c3222012-10-31 16:08:57 -0700343 if (DBG) Log.d(TAG, "Stored bluetooth Name=" + mName + ",Address=" + mAddress);
fredc0f420372012-04-12 00:02:00 -0700344 }
345
fredc649fe492012-04-19 01:07:18 -0700346 /**
347 * Save the Bluetooth name and address in the persistent store.
348 * Only non-null values will be saved.
349 * @param name
350 * @param address
351 */
fredc0f420372012-04-12 00:02:00 -0700352 private void storeNameAndAddress(String name, String address) {
353 if (name != null) {
354 Settings.Secure.putString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_NAME, name);
fredc0f420372012-04-12 00:02:00 -0700355 mName = name;
fredc649fe492012-04-19 01:07:18 -0700356 if (DBG) Log.d(TAG,"Stored Bluetooth name: " +
357 Settings.Secure.getString(mContentResolver,SECURE_SETTINGS_BLUETOOTH_NAME));
fredc0f420372012-04-12 00:02:00 -0700358 }
359
360 if (address != null) {
361 Settings.Secure.putString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDRESS, address);
fredc0f420372012-04-12 00:02:00 -0700362 mAddress=address;
fredc649fe492012-04-19 01:07:18 -0700363 if (DBG) Log.d(TAG,"Stored Bluetoothaddress: " +
364 Settings.Secure.getString(mContentResolver,SECURE_SETTINGS_BLUETOOTH_ADDRESS));
fredc0f420372012-04-12 00:02:00 -0700365 }
Zhihai Xud31c3222012-10-31 16:08:57 -0700366
367 if ((name != null) && (address != null)) {
368 Settings.Secure.putInt(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDR_VALID, 1);
369 }
fredc0f420372012-04-12 00:02:00 -0700370 }
371
372 public IBluetooth registerAdapter(IBluetoothManagerCallback callback){
Natalie Silvanovich55db6462014-05-01 16:12:23 -0700373 if (callback == null) {
374 Log.w(TAG, "Callback is null in registerAdapter");
375 return null;
376 }
fredc0f420372012-04-12 00:02:00 -0700377 Message msg = mHandler.obtainMessage(MESSAGE_REGISTER_ADAPTER);
378 msg.obj = callback;
379 mHandler.sendMessage(msg);
380 synchronized(mConnection) {
381 return mBluetooth;
382 }
383 }
384
385 public void unregisterAdapter(IBluetoothManagerCallback callback) {
Natalie Silvanovich55db6462014-05-01 16:12:23 -0700386 if (callback == null) {
387 Log.w(TAG, "Callback is null in unregisterAdapter");
388 return;
389 }
fredc0f420372012-04-12 00:02:00 -0700390 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
391 "Need BLUETOOTH permission");
392 Message msg = mHandler.obtainMessage(MESSAGE_UNREGISTER_ADAPTER);
393 msg.obj = callback;
394 mHandler.sendMessage(msg);
395 }
396
397 public void registerStateChangeCallback(IBluetoothStateChangeCallback callback) {
398 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
399 "Need BLUETOOTH permission");
400 Message msg = mHandler.obtainMessage(MESSAGE_REGISTER_STATE_CHANGE_CALLBACK);
401 msg.obj = callback;
402 mHandler.sendMessage(msg);
403 }
404
405 public void unregisterStateChangeCallback(IBluetoothStateChangeCallback callback) {
406 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
407 "Need BLUETOOTH permission");
408 Message msg = mHandler.obtainMessage(MESSAGE_UNREGISTER_STATE_CHANGE_CALLBACK);
409 msg.obj = callback;
410 mHandler.sendMessage(msg);
411 }
412
413 public boolean isEnabled() {
Zhihai Xu6eb76522012-11-29 15:41:04 -0800414 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
415 (!checkIfCallerIsForegroundUser())) {
416 Log.w(TAG,"isEnabled(): not allowed for non-active and non system user");
Zhihai Xu40874a02012-10-08 17:57:03 -0700417 return false;
418 }
419
fredc0f420372012-04-12 00:02:00 -0700420 synchronized(mConnection) {
421 try {
422 return (mBluetooth != null && mBluetooth.isEnabled());
423 } catch (RemoteException e) {
424 Log.e(TAG, "isEnabled()", e);
425 }
426 }
427 return false;
428 }
429
Nitin Arorad055adb2015-03-02 15:03:51 -0800430 class ClientDeathRecipient implements IBinder.DeathRecipient {
431 public void binderDied() {
432 if (DBG) Log.d(TAG, "Binder is dead - unregister Ble App");
433 if (mBleAppCount > 0) --mBleAppCount;
434
435 if (mBleAppCount == 0) {
436 if (DBG) Log.d(TAG, "Disabling LE only mode after application crash");
437 try {
438 if (mBluetooth != null) {
439 mBluetooth.onBrEdrDown();
440 }
441 } catch(RemoteException e) {
442 Log.e(TAG,"Unable to call onBrEdrDown", e);
443 }
444 }
445 }
446 }
447
448 /** Internal death rec list */
449 Map<IBinder, ClientDeathRecipient> mBleApps = new HashMap<IBinder, ClientDeathRecipient>();
450
Wei Wang67d84162015-04-26 17:04:29 -0700451 @Override
452 public boolean isBleScanAlwaysAvailable() {
453 try {
454 return (Settings.Global.getInt(mContentResolver,
455 Settings.Global.BLE_SCAN_ALWAYS_AVAILABLE)) != 0;
456 } catch (SettingNotFoundException e) {
457 }
458 return false;
459 }
460
Nitin Arorad055adb2015-03-02 15:03:51 -0800461 public int updateBleAppCount(IBinder token, boolean enable) {
462 if (enable) {
463 ClientDeathRecipient r = mBleApps.get(token);
464 if (r == null) {
465 ClientDeathRecipient deathRec = new ClientDeathRecipient();
466 try {
467 token.linkToDeath(deathRec, 0);
468 } catch (RemoteException ex) {
469 throw new IllegalArgumentException("Wake lock is already dead.");
470 }
471 mBleApps.put(token, deathRec);
472 synchronized (this) {
473 ++mBleAppCount;
474 }
475 if (DBG) Log.d(TAG, "Registered for death Notification");
476 }
477
478 } else {
479 ClientDeathRecipient r = mBleApps.get(token);
480 if (r != null) {
481 try {
482 token.linkToDeath(r, 0);
483 } catch (RemoteException ex) {
484 throw new IllegalArgumentException("Wake lock is already dead.");
485 }
486 mBleApps.remove(token);
487 synchronized (this) {
488 if (mBleAppCount > 0) --mBleAppCount;
489 }
490 if (DBG) Log.d(TAG, "Unregistered for death Notification");
491 }
492 }
493 if (DBG) Log.d(TAG, "Updated BleAppCount" + mBleAppCount);
494 if (mBleAppCount == 0 && mEnable) {
495 try {
496 if (mBluetooth != null && (mBluetooth.getState() != BluetoothAdapter.STATE_ON)) {
497 if (DBG) Log.d(TAG, "Reseting the mEnable flag for clean disable");
498 mEnable = false;
499 }
500 } catch (RemoteException e) {
501 Log.e(TAG, "getState()", e);
502 }
503 }
504 return mBleAppCount;
505 }
506
507 /** @hide*/
508 public boolean isBleAppPresent() {
509 if (DBG) Log.d(TAG, "isBleAppPresent() count: " + mBleAppCount);
510 return (mBleAppCount > 0);
511 }
512
513 /**
514 * Action taken when GattService is turned off
515 */
516 private void onBluetoothGattServiceUp() {
517 if (DBG) Log.d(TAG,"BluetoothGatt Service is Up");
518 try{
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700519 if (isBleAppPresent() == false && mBluetooth != null
520 && mBluetooth.getState() == BluetoothAdapter.STATE_BLE_ON) {
Nitin Arorad055adb2015-03-02 15:03:51 -0800521 mBluetooth.onLeServiceUp();
522
523 // waive WRITE_SECURE_SETTINGS permission check
524 long callingIdentity = Binder.clearCallingIdentity();
525 persistBluetoothSetting(BLUETOOTH_ON_BLUETOOTH);
526 Binder.restoreCallingIdentity(callingIdentity);
527 }
528 } catch(RemoteException e) {
529 Log.e(TAG,"Unable to call onServiceUp", e);
530 }
531 }
532
533 /**
534 * Inform BluetoothAdapter instances that BREDR part is down
535 * and turn off all service and stack if no LE app needs it
536 */
537 private void sendBrEdrDownCallback() {
538 if (DBG) Log.d(TAG,"Calling sendBrEdrDownCallback callbacks");
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700539
540 if(mBluetooth == null) {
541 Log.w(TAG, "Bluetooth handle is null");
542 return;
543 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800544
545 if (isBleAppPresent() == false) {
546 try {
547 mBluetooth.onBrEdrDown();
548 } catch(RemoteException e) {
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700549 Log.e(TAG, "Call to onBrEdrDown() failed.", e);
Nitin Arorad055adb2015-03-02 15:03:51 -0800550 }
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700551 } else {
552 // Need to stay at BLE ON. Disconnect all Gatt connections
Nitin Arorad055adb2015-03-02 15:03:51 -0800553 try{
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700554 mBluetoothGatt.unregAll();
Nitin Arorad055adb2015-03-02 15:03:51 -0800555 } catch(RemoteException e) {
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700556 Log.e(TAG, "Unable to disconnect all apps.", e);
Nitin Arorad055adb2015-03-02 15:03:51 -0800557 }
558 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800559 }
560
561 /** @hide*/
fredc0f420372012-04-12 00:02:00 -0700562 public void getNameAndAddress() {
fredcf2458862012-04-16 15:18:27 -0700563 if (DBG) {
Matthew Xiecdce0b92012-07-12 19:06:15 -0700564 Log.d(TAG,"getNameAndAddress(): mBluetooth = " + mBluetooth +
565 " mBinding = " + mBinding);
fredcf2458862012-04-16 15:18:27 -0700566 }
fredc0f420372012-04-12 00:02:00 -0700567 Message msg = mHandler.obtainMessage(MESSAGE_GET_NAME_AND_ADDRESS);
568 mHandler.sendMessage(msg);
569 }
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700570 public boolean enableNoAutoConnect()
571 {
572 mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
573 "Need BLUETOOTH ADMIN permission");
Zhihai Xu40874a02012-10-08 17:57:03 -0700574
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700575 if (DBG) {
576 Log.d(TAG,"enableNoAutoConnect(): mBluetooth =" + mBluetooth +
577 " mBinding = " + mBinding);
578 }
Martijn Coenen8385c5a2012-11-29 10:14:16 -0800579 int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
580
581 if (callingAppId != Process.NFC_UID) {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700582 throw new SecurityException("no permission to enable Bluetooth quietly");
583 }
Martijn Coenen8385c5a2012-11-29 10:14:16 -0800584
Zhihai Xu401202b2012-12-03 11:36:21 -0800585 synchronized(mReceiver) {
586 mQuietEnableExternal = true;
587 mEnableExternal = true;
588 sendEnableMsg(true);
589 }
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700590 return true;
591
592 }
fredc0f420372012-04-12 00:02:00 -0700593 public boolean enable() {
Zhihai Xu6eb76522012-11-29 15:41:04 -0800594 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
595 (!checkIfCallerIsForegroundUser())) {
596 Log.w(TAG,"enable(): not allowed for non-active and non system user");
Zhihai Xu40874a02012-10-08 17:57:03 -0700597 return false;
fredcf2458862012-04-16 15:18:27 -0700598 }
599
Zhihai Xu401202b2012-12-03 11:36:21 -0800600 mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
601 "Need BLUETOOTH ADMIN permission");
602 if (DBG) {
603 Log.d(TAG,"enable(): mBluetooth =" + mBluetooth +
604 " mBinding = " + mBinding);
605 }
606
607 synchronized(mReceiver) {
608 mQuietEnableExternal = false;
609 mEnableExternal = true;
610 // waive WRITE_SECURE_SETTINGS permission check
Zhihai Xu401202b2012-12-03 11:36:21 -0800611 sendEnableMsg(false);
612 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800613 if (DBG) Log.d(TAG, "enable returning");
Zhihai Xu401202b2012-12-03 11:36:21 -0800614 return true;
fredc0f420372012-04-12 00:02:00 -0700615 }
616
617 public boolean disable(boolean persist) {
618 mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
619 "Need BLUETOOTH ADMIN permissicacheNameAndAddresson");
Zhihai Xu40874a02012-10-08 17:57:03 -0700620
Zhihai Xu6eb76522012-11-29 15:41:04 -0800621 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
622 (!checkIfCallerIsForegroundUser())) {
623 Log.w(TAG,"disable(): not allowed for non-active and non system user");
Zhihai Xu40874a02012-10-08 17:57:03 -0700624 return false;
625 }
626
fredcf2458862012-04-16 15:18:27 -0700627 if (DBG) {
Matthew Xiecdce0b92012-07-12 19:06:15 -0700628 Log.d(TAG,"disable(): mBluetooth = " + mBluetooth +
629 " mBinding = " + mBinding);
630 }
fredcf2458862012-04-16 15:18:27 -0700631
Zhihai Xu401202b2012-12-03 11:36:21 -0800632 synchronized(mReceiver) {
633 if (persist) {
634 // waive WRITE_SECURE_SETTINGS permission check
635 long callingIdentity = Binder.clearCallingIdentity();
636 persistBluetoothSetting(BLUETOOTH_OFF);
637 Binder.restoreCallingIdentity(callingIdentity);
638 }
639 mEnableExternal = false;
640 sendDisableMsg();
641 }
fredc0f420372012-04-12 00:02:00 -0700642 return true;
643 }
644
fredc649fe492012-04-19 01:07:18 -0700645 public void unbindAndFinish() {
fredcf2458862012-04-16 15:18:27 -0700646 if (DBG) {
Matthew Xiecdce0b92012-07-12 19:06:15 -0700647 Log.d(TAG,"unbindAndFinish(): " + mBluetooth +
648 " mBinding = " + mBinding);
fredcf2458862012-04-16 15:18:27 -0700649 }
650
fredc0f420372012-04-12 00:02:00 -0700651 synchronized (mConnection) {
652 if (mUnbinding) return;
653 mUnbinding = true;
Zhihai Xu40874a02012-10-08 17:57:03 -0700654 if (mBluetooth != null) {
fredcbf072a72012-05-09 16:52:50 -0700655 if (!mConnection.isGetNameAddressOnly()) {
656 //Unregister callback object
657 try {
658 mBluetooth.unregisterCallback(mBluetoothCallback);
659 } catch (RemoteException re) {
Zhihai Xu40874a02012-10-08 17:57:03 -0700660 Log.e(TAG, "Unable to unregister BluetoothCallback",re);
fredcbf072a72012-05-09 16:52:50 -0700661 }
662 }
fredc0f420372012-04-12 00:02:00 -0700663 if (DBG) Log.d(TAG, "Sending unbind request.");
fredcd6883532012-04-25 17:46:13 -0700664 mBluetooth = null;
665 //Unbind
fredc0f420372012-04-12 00:02:00 -0700666 mContext.unbindService(mConnection);
fredcd6883532012-04-25 17:46:13 -0700667 mUnbinding = false;
Zhihai Xu40874a02012-10-08 17:57:03 -0700668 mBinding = false;
fredcf2458862012-04-16 15:18:27 -0700669 } else {
670 mUnbinding=false;
fredc0f420372012-04-12 00:02:00 -0700671 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800672 mBluetoothGatt = null;
fredc0f420372012-04-12 00:02:00 -0700673 }
674 }
675
Matthew Xieddf7e472013-03-01 18:41:02 -0800676 public IBluetoothGatt getBluetoothGatt() {
677 // sync protection
678 return mBluetoothGatt;
679 }
680
Benjamin Franze8b98922014-11-12 15:57:54 +0000681 @Override
682 public boolean bindBluetoothProfileService(int bluetoothProfile,
683 IBluetoothProfileServiceConnection proxy) {
684 if (!mEnable) {
685 if (DBG) {
686 Log.d(TAG, "Trying to bind to profile: " + bluetoothProfile +
687 ", while Bluetooth was disabled");
688 }
689 return false;
690 }
691 synchronized (mProfileServices) {
692 ProfileServiceConnections psc = mProfileServices.get(new Integer(bluetoothProfile));
693 if (psc == null) {
694 if (DBG) {
695 Log.d(TAG, "Creating new ProfileServiceConnections object for"
696 + " profile: " + bluetoothProfile);
697 }
Benjamin Franz5b614592014-12-09 18:58:45 +0000698
699 if (bluetoothProfile != BluetoothProfile.HEADSET) return false;
700
701 Intent intent = new Intent(IBluetoothHeadset.class.getName());
Benjamin Franze8b98922014-11-12 15:57:54 +0000702 psc = new ProfileServiceConnections(intent);
Benjamin Franz5b614592014-12-09 18:58:45 +0000703 if (!psc.bindService()) return false;
704
Benjamin Franze8b98922014-11-12 15:57:54 +0000705 mProfileServices.put(new Integer(bluetoothProfile), psc);
Benjamin Franze8b98922014-11-12 15:57:54 +0000706 }
707 }
708
709 // Introducing a delay to give the client app time to prepare
710 Message addProxyMsg = mHandler.obtainMessage(MESSAGE_ADD_PROXY_DELAYED);
711 addProxyMsg.arg1 = bluetoothProfile;
712 addProxyMsg.obj = proxy;
713 mHandler.sendMessageDelayed(addProxyMsg, ADD_PROXY_DELAY_MS);
714 return true;
715 }
716
717 @Override
718 public void unbindBluetoothProfileService(int bluetoothProfile,
719 IBluetoothProfileServiceConnection proxy) {
720 synchronized (mProfileServices) {
721 ProfileServiceConnections psc = mProfileServices.get(new Integer(bluetoothProfile));
722 if (psc == null) {
723 return;
724 }
725 psc.removeProxy(proxy);
726 }
727 }
728
729 private void unbindAllBluetoothProfileServices() {
730 synchronized (mProfileServices) {
731 for (Integer i : mProfileServices.keySet()) {
732 ProfileServiceConnections psc = mProfileServices.get(i);
Benjamin Franz5b614592014-12-09 18:58:45 +0000733 try {
734 mContext.unbindService(psc);
735 } catch (IllegalArgumentException e) {
736 Log.e(TAG, "Unable to unbind service with intent: " + psc.mIntent, e);
737 }
Benjamin Franze8b98922014-11-12 15:57:54 +0000738 psc.removeAllProxies();
739 }
740 mProfileServices.clear();
741 }
742 }
743
744 /**
745 * This class manages the clients connected to a given ProfileService
746 * and maintains the connection with that service.
747 */
748 final private class ProfileServiceConnections implements ServiceConnection,
749 IBinder.DeathRecipient {
750 final RemoteCallbackList<IBluetoothProfileServiceConnection> mProxies =
751 new RemoteCallbackList <IBluetoothProfileServiceConnection>();
752 IBinder mService;
753 ComponentName mClassName;
754 Intent mIntent;
755
756 ProfileServiceConnections(Intent intent) {
757 mService = null;
758 mClassName = null;
759 mIntent = intent;
760 }
761
Benjamin Franz5b614592014-12-09 18:58:45 +0000762 private boolean bindService() {
763 if (mIntent != null && mService == null &&
764 doBind(mIntent, this, 0, UserHandle.CURRENT_OR_SELF)) {
Benjamin Franze8b98922014-11-12 15:57:54 +0000765 Message msg = mHandler.obtainMessage(MESSAGE_BIND_PROFILE_SERVICE);
766 msg.obj = this;
767 mHandler.sendMessageDelayed(msg, TIMEOUT_BIND_MS);
Benjamin Franz5b614592014-12-09 18:58:45 +0000768 return true;
Benjamin Franze8b98922014-11-12 15:57:54 +0000769 }
Benjamin Franz5b614592014-12-09 18:58:45 +0000770 Log.w(TAG, "Unable to bind with intent: " + mIntent);
771 return false;
Benjamin Franze8b98922014-11-12 15:57:54 +0000772 }
773
774 private void addProxy(IBluetoothProfileServiceConnection proxy) {
775 mProxies.register(proxy);
776 if (mService != null) {
777 try{
778 proxy.onServiceConnected(mClassName, mService);
779 } catch (RemoteException e) {
780 Log.e(TAG, "Unable to connect to proxy", e);
781 }
782 } else {
783 if (!mHandler.hasMessages(MESSAGE_BIND_PROFILE_SERVICE, this)) {
784 Message msg = mHandler.obtainMessage(MESSAGE_BIND_PROFILE_SERVICE);
785 msg.obj = this;
786 mHandler.sendMessage(msg);
787 }
788 }
789 }
790
791 private void removeProxy(IBluetoothProfileServiceConnection proxy) {
792 if (proxy != null) {
793 if (mProxies.unregister(proxy)) {
794 try {
795 proxy.onServiceDisconnected(mClassName);
796 } catch (RemoteException e) {
797 Log.e(TAG, "Unable to disconnect proxy", e);
798 }
799 }
800 } else {
801 Log.w(TAG, "Trying to remove a null proxy");
802 }
803 }
804
805 private void removeAllProxies() {
806 onServiceDisconnected(mClassName);
807 mProxies.kill();
808 }
809
810 @Override
811 public void onServiceConnected(ComponentName className, IBinder service) {
812 // remove timeout message
813 mHandler.removeMessages(MESSAGE_BIND_PROFILE_SERVICE, this);
814 mService = service;
815 mClassName = className;
816 try {
817 mService.linkToDeath(this, 0);
818 } catch (RemoteException e) {
819 Log.e(TAG, "Unable to linkToDeath", e);
820 }
821 int n = mProxies.beginBroadcast();
822 for (int i = 0; i < n; i++) {
823 try {
824 mProxies.getBroadcastItem(i).onServiceConnected(className, service);
825 } catch (RemoteException e) {
826 Log.e(TAG, "Unable to connect to proxy", e);
827 }
828 }
829 mProxies.finishBroadcast();
830 }
831
832 @Override
833 public void onServiceDisconnected(ComponentName className) {
834 if (mService == null) {
835 return;
836 }
837 mService.unlinkToDeath(this, 0);
838 mService = null;
839 mClassName = null;
840 int n = mProxies.beginBroadcast();
841 for (int i = 0; i < n; i++) {
842 try {
843 mProxies.getBroadcastItem(i).onServiceDisconnected(className);
844 } catch (RemoteException e) {
845 Log.e(TAG, "Unable to disconnect from proxy", e);
846 }
847 }
848 mProxies.finishBroadcast();
849 }
850
851 @Override
852 public void binderDied() {
853 if (DBG) {
854 Log.w(TAG, "Profile service for profile: " + mClassName
855 + " died.");
856 }
857 onServiceDisconnected(mClassName);
858 // Trigger rebind
859 Message msg = mHandler.obtainMessage(MESSAGE_BIND_PROFILE_SERVICE);
860 msg.obj = this;
861 mHandler.sendMessageDelayed(msg, TIMEOUT_BIND_MS);
862 }
863 }
864
fredcbf072a72012-05-09 16:52:50 -0700865 private void sendBluetoothStateCallback(boolean isUp) {
866 int n = mStateChangeCallbacks.beginBroadcast();
Freda8c6df02012-07-11 10:25:23 -0700867 if (DBG) Log.d(TAG,"Broadcasting onBluetoothStateChange("+isUp+") to " + n + " receivers.");
fredcbf072a72012-05-09 16:52:50 -0700868 for (int i=0; i <n;i++) {
869 try {
870 mStateChangeCallbacks.getBroadcastItem(i).onBluetoothStateChange(isUp);
871 } catch (RemoteException e) {
872 Log.e(TAG, "Unable to call onBluetoothStateChange() on callback #" + i , e);
873 }
874 }
875 mStateChangeCallbacks.finishBroadcast();
876 }
877
878 /**
Zhihai Xu40874a02012-10-08 17:57:03 -0700879 * Inform BluetoothAdapter instances that Adapter service is up
880 */
881 private void sendBluetoothServiceUpCallback() {
882 if (!mConnection.isGetNameAddressOnly()) {
883 if (DBG) Log.d(TAG,"Calling onBluetoothServiceUp callbacks");
884 int n = mCallbacks.beginBroadcast();
885 Log.d(TAG,"Broadcasting onBluetoothServiceUp() to " + n + " receivers.");
886 for (int i=0; i <n;i++) {
887 try {
888 mCallbacks.getBroadcastItem(i).onBluetoothServiceUp(mBluetooth);
889 } catch (RemoteException e) {
890 Log.e(TAG, "Unable to call onBluetoothServiceUp() on callback #" + i, e);
891 }
892 }
893 mCallbacks.finishBroadcast();
894 }
895 }
896 /**
fredcbf072a72012-05-09 16:52:50 -0700897 * Inform BluetoothAdapter instances that Adapter service is down
898 */
899 private void sendBluetoothServiceDownCallback() {
fredcd6883532012-04-25 17:46:13 -0700900 if (!mConnection.isGetNameAddressOnly()) {
901 if (DBG) Log.d(TAG,"Calling onBluetoothServiceDown callbacks");
902 int n = mCallbacks.beginBroadcast();
903 Log.d(TAG,"Broadcasting onBluetoothServiceDown() to " + n + " receivers.");
904 for (int i=0; i <n;i++) {
905 try {
906 mCallbacks.getBroadcastItem(i).onBluetoothServiceDown();
907 } catch (RemoteException e) {
908 Log.e(TAG, "Unable to call onBluetoothServiceDown() on callback #" + i, e);
909 }
910 }
911 mCallbacks.finishBroadcast();
912 }
913 }
Svet Ganov408abf72015-05-12 19:13:36 -0700914
fredc0f420372012-04-12 00:02:00 -0700915 public String getAddress() {
Matthew Xieaf5ddbf2012-12-04 10:47:43 -0800916 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
Svet Ganov408abf72015-05-12 19:13:36 -0700917 "Need BLUETOOTH permission");
Zhihai Xu40874a02012-10-08 17:57:03 -0700918
Zhihai Xu6eb76522012-11-29 15:41:04 -0800919 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
Svet Ganov408abf72015-05-12 19:13:36 -0700920 (!checkIfCallerIsForegroundUser())) {
Zhihai Xu6eb76522012-11-29 15:41:04 -0800921 Log.w(TAG,"getAddress(): not allowed for non-active and non system user");
922 return null;
Zhihai Xu40874a02012-10-08 17:57:03 -0700923 }
924
Svet Ganov408abf72015-05-12 19:13:36 -0700925 if (mContext.checkCallingOrSelfPermission(Manifest.permission.LOCAL_MAC_ADDRESS)
926 != PackageManager.PERMISSION_GRANTED) {
927 return BluetoothAdapter.DEFAULT_MAC_ADDRESS;
928 }
929
fredc116d1d462012-04-20 14:47:08 -0700930 synchronized(mConnection) {
931 if (mBluetooth != null) {
932 try {
933 return mBluetooth.getAddress();
934 } catch (RemoteException e) {
935 Log.e(TAG, "getAddress(): Unable to retrieve address remotely..Returning cached address",e);
936 }
937 }
938 }
Matthew Xiecdce0b92012-07-12 19:06:15 -0700939 // mAddress is accessed from outside.
940 // It is alright without a lock. Here, bluetooth is off, no other thread is
941 // changing mAddress
fredc0f420372012-04-12 00:02:00 -0700942 return mAddress;
943 }
fredc649fe492012-04-19 01:07:18 -0700944
fredc0f420372012-04-12 00:02:00 -0700945 public String getName() {
Matthew Xieaf5ddbf2012-12-04 10:47:43 -0800946 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
947 "Need BLUETOOTH permission");
Zhihai Xu40874a02012-10-08 17:57:03 -0700948
Zhihai Xu6eb76522012-11-29 15:41:04 -0800949 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
950 (!checkIfCallerIsForegroundUser())) {
951 Log.w(TAG,"getName(): not allowed for non-active and non system user");
952 return null;
Zhihai Xu40874a02012-10-08 17:57:03 -0700953 }
954
fredc116d1d462012-04-20 14:47:08 -0700955 synchronized(mConnection) {
956 if (mBluetooth != null) {
957 try {
958 return mBluetooth.getName();
959 } catch (RemoteException e) {
960 Log.e(TAG, "getName(): Unable to retrieve name remotely..Returning cached name",e);
961 }
962 }
963 }
Matthew Xiecdce0b92012-07-12 19:06:15 -0700964 // mName is accessed from outside.
965 // It alright without a lock. Here, bluetooth is off, no other thread is
966 // changing mName
fredc0f420372012-04-12 00:02:00 -0700967 return mName;
968 }
969
fredc0f420372012-04-12 00:02:00 -0700970 private class BluetoothServiceConnection implements ServiceConnection {
971
972 private boolean mGetNameAddressOnly;
973
974 public void setGetNameAddressOnly(boolean getOnly) {
975 mGetNameAddressOnly = getOnly;
976 }
977
978 public boolean isGetNameAddressOnly() {
979 return mGetNameAddressOnly;
980 }
981
982 public void onServiceConnected(ComponentName className, IBinder service) {
Matthew Xieddf7e472013-03-01 18:41:02 -0800983 if (DBG) Log.d(TAG, "BluetoothServiceConnection: " + className.getClassName());
fredc0f420372012-04-12 00:02:00 -0700984 Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_SERVICE_CONNECTED);
Matthew Xieddf7e472013-03-01 18:41:02 -0800985 // TBD if (className.getClassName().equals(IBluetooth.class.getName())) {
986 if (className.getClassName().equals("com.android.bluetooth.btservice.AdapterService")) {
987 msg.arg1 = SERVICE_IBLUETOOTH;
988 // } else if (className.getClassName().equals(IBluetoothGatt.class.getName())) {
989 } else if (className.getClassName().equals("com.android.bluetooth.gatt.GattService")) {
990 msg.arg1 = SERVICE_IBLUETOOTHGATT;
991 } else {
992 Log.e(TAG, "Unknown service connected: " + className.getClassName());
993 return;
994 }
fredc0f420372012-04-12 00:02:00 -0700995 msg.obj = service;
996 mHandler.sendMessage(msg);
997 }
998
999 public void onServiceDisconnected(ComponentName className) {
fredc0f420372012-04-12 00:02:00 -07001000 // Called if we unexpected disconnected.
Matthew Xieddf7e472013-03-01 18:41:02 -08001001 if (DBG) Log.d(TAG, "BluetoothServiceConnection, disconnected: " +
1002 className.getClassName());
fredc0f420372012-04-12 00:02:00 -07001003 Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED);
Matthew Xieddf7e472013-03-01 18:41:02 -08001004 if (className.getClassName().equals("com.android.bluetooth.btservice.AdapterService")) {
1005 msg.arg1 = SERVICE_IBLUETOOTH;
1006 } else if (className.getClassName().equals("com.android.bluetooth.gatt.GattService")) {
1007 msg.arg1 = SERVICE_IBLUETOOTHGATT;
1008 } else {
1009 Log.e(TAG, "Unknown service disconnected: " + className.getClassName());
1010 return;
1011 }
fredc0f420372012-04-12 00:02:00 -07001012 mHandler.sendMessage(msg);
1013 }
1014 }
1015
1016 private BluetoothServiceConnection mConnection = new BluetoothServiceConnection();
1017
Zhihai Xu40874a02012-10-08 17:57:03 -07001018 private class BluetoothHandler extends Handler {
1019 public BluetoothHandler(Looper looper) {
1020 super(looper);
1021 }
1022
fredc0f420372012-04-12 00:02:00 -07001023 @Override
1024 public void handleMessage(Message msg) {
1025 if (DBG) Log.d (TAG, "Message: " + msg.what);
fredc0f420372012-04-12 00:02:00 -07001026 switch (msg.what) {
1027 case MESSAGE_GET_NAME_AND_ADDRESS: {
fredc649fe492012-04-19 01:07:18 -07001028 if (DBG) Log.d(TAG,"MESSAGE_GET_NAME_AND_ADDRESS");
Matthew Xiecdce0b92012-07-12 19:06:15 -07001029 synchronized(mConnection) {
fredc0f420372012-04-12 00:02:00 -07001030 //Start bind request
Zhihai Xu40874a02012-10-08 17:57:03 -07001031 if ((mBluetooth == null) && (!mBinding)) {
fredc0f420372012-04-12 00:02:00 -07001032 if (DBG) Log.d(TAG, "Binding to service to get name and address");
1033 mConnection.setGetNameAddressOnly(true);
1034 //Start bind timeout and bind
1035 Message timeoutMsg = mHandler.obtainMessage(MESSAGE_TIMEOUT_BIND);
1036 mHandler.sendMessageDelayed(timeoutMsg,TIMEOUT_BIND_MS);
1037 Intent i = new Intent(IBluetooth.class.getName());
Dianne Hackborn221ea892013-08-04 16:50:16 -07001038 if (!doBind(i, mConnection,
Dianne Hackbornce09f5a2014-10-10 15:03:13 -07001039 Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT,
1040 UserHandle.CURRENT)) {
fredc0f420372012-04-12 00:02:00 -07001041 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
Zhihai Xu40874a02012-10-08 17:57:03 -07001042 } else {
1043 mBinding = true;
fredc0f420372012-04-12 00:02:00 -07001044 }
1045 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001046 else {
1047 Message saveMsg= mHandler.obtainMessage(MESSAGE_SAVE_NAME_AND_ADDRESS);
Zhihai Xu40874a02012-10-08 17:57:03 -07001048 saveMsg.arg1 = 0;
1049 if (mBluetooth != null) {
1050 mHandler.sendMessage(saveMsg);
1051 } else {
1052 // if enable is also called to bind the service
1053 // wait for MESSAGE_BLUETOOTH_SERVICE_CONNECTED
1054 mHandler.sendMessageDelayed(saveMsg, TIMEOUT_SAVE_MS);
1055 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001056 }
fredc0f420372012-04-12 00:02:00 -07001057 }
fredc649fe492012-04-19 01:07:18 -07001058 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001059 }
fredc0f420372012-04-12 00:02:00 -07001060 case MESSAGE_SAVE_NAME_AND_ADDRESS: {
Zhihai Xud31c3222012-10-31 16:08:57 -07001061 boolean unbind = false;
fredc649fe492012-04-19 01:07:18 -07001062 if (DBG) Log.d(TAG,"MESSAGE_SAVE_NAME_AND_ADDRESS");
Matthew Xiecdce0b92012-07-12 19:06:15 -07001063 synchronized(mConnection) {
Zhihai Xud31c3222012-10-31 16:08:57 -07001064 if (!mEnable && mBluetooth != null) {
1065 try {
1066 mBluetooth.enable();
1067 } catch (RemoteException e) {
1068 Log.e(TAG,"Unable to call enable()",e);
1069 }
1070 }
1071 }
1072 if (mBluetooth != null) waitForOnOff(true, false);
1073 synchronized(mConnection) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001074 if (mBluetooth != null) {
1075 String name = null;
1076 String address = null;
1077 try {
1078 name = mBluetooth.getName();
1079 address = mBluetooth.getAddress();
1080 } catch (RemoteException re) {
1081 Log.e(TAG,"",re);
1082 }
fredc0f420372012-04-12 00:02:00 -07001083
Matthew Xiecdce0b92012-07-12 19:06:15 -07001084 if (name != null && address != null) {
1085 storeNameAndAddress(name,address);
Zhihai Xu40874a02012-10-08 17:57:03 -07001086 if (mConnection.isGetNameAddressOnly()) {
Zhihai Xud31c3222012-10-31 16:08:57 -07001087 unbind = true;
Zhihai Xu40874a02012-10-08 17:57:03 -07001088 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001089 } else {
1090 if (msg.arg1 < MAX_SAVE_RETRIES) {
1091 Message retryMsg = mHandler.obtainMessage(MESSAGE_SAVE_NAME_AND_ADDRESS);
1092 retryMsg.arg1= 1+msg.arg1;
1093 if (DBG) Log.d(TAG,"Retrying name/address remote retrieval and save.....Retry count =" + retryMsg.arg1);
1094 mHandler.sendMessageDelayed(retryMsg, TIMEOUT_SAVE_MS);
1095 } else {
1096 Log.w(TAG,"Maximum name/address remote retrieval retry exceeded");
Zhihai Xu40874a02012-10-08 17:57:03 -07001097 if (mConnection.isGetNameAddressOnly()) {
Zhihai Xud31c3222012-10-31 16:08:57 -07001098 unbind = true;
Zhihai Xu40874a02012-10-08 17:57:03 -07001099 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001100 }
fredc0f420372012-04-12 00:02:00 -07001101 }
Zhihai Xud31c3222012-10-31 16:08:57 -07001102 if (!mEnable) {
1103 try {
1104 mBluetooth.disable();
1105 } catch (RemoteException e) {
1106 Log.e(TAG,"Unable to call disable()",e);
1107 }
1108 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001109 } else {
1110 // rebind service by Request GET NAME AND ADDRESS
1111 // if service is unbinded by disable or
1112 // MESSAGE_BLUETOOTH_SERVICE_CONNECTED is not received
1113 Message getMsg = mHandler.obtainMessage(MESSAGE_GET_NAME_AND_ADDRESS);
1114 mHandler.sendMessage(getMsg);
fredc0f420372012-04-12 00:02:00 -07001115 }
1116 }
Zhihai Xud31c3222012-10-31 16:08:57 -07001117 if (!mEnable && mBluetooth != null) waitForOnOff(false, true);
1118 if (unbind) {
1119 unbindAndFinish();
1120 }
fredc649fe492012-04-19 01:07:18 -07001121 break;
fredc649fe492012-04-19 01:07:18 -07001122 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001123 case MESSAGE_ENABLE:
fredcf2458862012-04-16 15:18:27 -07001124 if (DBG) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001125 Log.d(TAG, "MESSAGE_ENABLE: mBluetooth = " + mBluetooth);
fredc649fe492012-04-19 01:07:18 -07001126 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001127 mHandler.removeMessages(MESSAGE_RESTART_BLUETOOTH_SERVICE);
1128 mEnable = true;
Zhihai Xu401202b2012-12-03 11:36:21 -08001129 handleEnable(msg.arg1 == 1);
fredc649fe492012-04-19 01:07:18 -07001130 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001131
fredc0f420372012-04-12 00:02:00 -07001132 case MESSAGE_DISABLE:
Zhihai Xu40874a02012-10-08 17:57:03 -07001133 mHandler.removeMessages(MESSAGE_RESTART_BLUETOOTH_SERVICE);
1134 if (mEnable && mBluetooth != null) {
1135 waitForOnOff(true, false);
1136 mEnable = false;
Zhihai Xu401202b2012-12-03 11:36:21 -08001137 handleDisable();
Zhihai Xu40874a02012-10-08 17:57:03 -07001138 waitForOnOff(false, false);
1139 } else {
1140 mEnable = false;
Zhihai Xu401202b2012-12-03 11:36:21 -08001141 handleDisable();
Zhihai Xu40874a02012-10-08 17:57:03 -07001142 }
fredc0f420372012-04-12 00:02:00 -07001143 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001144
fredc0f420372012-04-12 00:02:00 -07001145 case MESSAGE_REGISTER_ADAPTER:
1146 {
1147 IBluetoothManagerCallback callback = (IBluetoothManagerCallback) msg.obj;
fredcd6883532012-04-25 17:46:13 -07001148 boolean added = mCallbacks.register(callback);
1149 Log.d(TAG,"Added callback: " + (callback == null? "null": callback) +":" +added );
fredc0f420372012-04-12 00:02:00 -07001150 }
1151 break;
1152 case MESSAGE_UNREGISTER_ADAPTER:
1153 {
1154 IBluetoothManagerCallback callback = (IBluetoothManagerCallback) msg.obj;
fredcd6883532012-04-25 17:46:13 -07001155 boolean removed = mCallbacks.unregister(callback);
1156 Log.d(TAG,"Removed callback: " + (callback == null? "null": callback) +":" + removed);
fredc0f420372012-04-12 00:02:00 -07001157 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001158 }
fredc0f420372012-04-12 00:02:00 -07001159 case MESSAGE_REGISTER_STATE_CHANGE_CALLBACK:
1160 {
1161 IBluetoothStateChangeCallback callback = (IBluetoothStateChangeCallback) msg.obj;
Matthew Xie9b693992013-10-10 11:21:40 -07001162 if (callback != null) {
1163 mStateChangeCallbacks.register(callback);
1164 }
fredc0f420372012-04-12 00:02:00 -07001165 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001166 }
fredc0f420372012-04-12 00:02:00 -07001167 case MESSAGE_UNREGISTER_STATE_CHANGE_CALLBACK:
1168 {
1169 IBluetoothStateChangeCallback callback = (IBluetoothStateChangeCallback) msg.obj;
Matthew Xie9b693992013-10-10 11:21:40 -07001170 if (callback != null) {
1171 mStateChangeCallbacks.unregister(callback);
1172 }
fredc0f420372012-04-12 00:02:00 -07001173 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001174 }
Benjamin Franze8b98922014-11-12 15:57:54 +00001175 case MESSAGE_ADD_PROXY_DELAYED:
1176 {
1177 ProfileServiceConnections psc = mProfileServices.get(
1178 new Integer(msg.arg1));
1179 if (psc == null) {
1180 break;
1181 }
1182 IBluetoothProfileServiceConnection proxy =
1183 (IBluetoothProfileServiceConnection) msg.obj;
1184 psc.addProxy(proxy);
1185 break;
1186 }
1187 case MESSAGE_BIND_PROFILE_SERVICE:
1188 {
1189 ProfileServiceConnections psc = (ProfileServiceConnections) msg.obj;
1190 removeMessages(MESSAGE_BIND_PROFILE_SERVICE, msg.obj);
1191 if (psc == null) {
1192 break;
1193 }
1194 psc.bindService();
1195 break;
1196 }
fredc0f420372012-04-12 00:02:00 -07001197 case MESSAGE_BLUETOOTH_SERVICE_CONNECTED:
1198 {
Matthew Xieddf7e472013-03-01 18:41:02 -08001199 if (DBG) Log.d(TAG,"MESSAGE_BLUETOOTH_SERVICE_CONNECTED: " + msg.arg1);
fredc0f420372012-04-12 00:02:00 -07001200
1201 IBinder service = (IBinder) msg.obj;
1202 synchronized(mConnection) {
Matthew Xieddf7e472013-03-01 18:41:02 -08001203 if (msg.arg1 == SERVICE_IBLUETOOTHGATT) {
1204 mBluetoothGatt = IBluetoothGatt.Stub.asInterface(service);
Nitin Arorad055adb2015-03-02 15:03:51 -08001205 onBluetoothGattServiceUp();
Matthew Xieddf7e472013-03-01 18:41:02 -08001206 break;
1207 } // else must be SERVICE_IBLUETOOTH
1208
1209 //Remove timeout
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001210 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
Matthew Xieddf7e472013-03-01 18:41:02 -08001211
fredc0f420372012-04-12 00:02:00 -07001212 mBinding = false;
1213 mBluetooth = IBluetooth.Stub.asInterface(service);
fredc0f420372012-04-12 00:02:00 -07001214
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001215 try {
1216 boolean enableHciSnoopLog = (Settings.Secure.getInt(mContentResolver,
1217 Settings.Secure.BLUETOOTH_HCI_LOG, 0) == 1);
1218 if (!mBluetooth.configHciSnoopLog(enableHciSnoopLog)) {
1219 Log.e(TAG,"IBluetooth.configHciSnoopLog return false");
1220 }
1221 } catch (RemoteException e) {
1222 Log.e(TAG,"Unable to call configHciSnoopLog", e);
1223 }
1224
Matthew Xiecdce0b92012-07-12 19:06:15 -07001225 if (mConnection.isGetNameAddressOnly()) {
1226 //Request GET NAME AND ADDRESS
1227 Message getMsg = mHandler.obtainMessage(MESSAGE_GET_NAME_AND_ADDRESS);
1228 mHandler.sendMessage(getMsg);
Zhihai Xu40874a02012-10-08 17:57:03 -07001229 if (!mEnable) return;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001230 }
fredc0f420372012-04-12 00:02:00 -07001231
Zhihai Xu40874a02012-10-08 17:57:03 -07001232 mConnection.setGetNameAddressOnly(false);
Matthew Xiecdce0b92012-07-12 19:06:15 -07001233 //Register callback object
fredcbf072a72012-05-09 16:52:50 -07001234 try {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001235 mBluetooth.registerCallback(mBluetoothCallback);
1236 } catch (RemoteException re) {
1237 Log.e(TAG, "Unable to register BluetoothCallback",re);
fredcbf072a72012-05-09 16:52:50 -07001238 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001239 //Inform BluetoothAdapter instances that service is up
Zhihai Xu40874a02012-10-08 17:57:03 -07001240 sendBluetoothServiceUpCallback();
1241
Matthew Xiecdce0b92012-07-12 19:06:15 -07001242 //Do enable request
1243 try {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001244 if (mQuietEnable == false) {
1245 if(!mBluetooth.enable()) {
1246 Log.e(TAG,"IBluetooth.enable() returned false");
1247 }
1248 }
1249 else
1250 {
1251 if(!mBluetooth.enableNoAutoConnect()) {
1252 Log.e(TAG,"IBluetooth.enableNoAutoConnect() returned false");
1253 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001254 }
1255 } catch (RemoteException e) {
1256 Log.e(TAG,"Unable to call enable()",e);
1257 }
Freda8c6df02012-07-11 10:25:23 -07001258 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001259
1260 if (!mEnable) {
1261 waitForOnOff(true, false);
Zhihai Xu401202b2012-12-03 11:36:21 -08001262 handleDisable();
Zhihai Xu40874a02012-10-08 17:57:03 -07001263 waitForOnOff(false, false);
1264 }
fredc649fe492012-04-19 01:07:18 -07001265 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001266 }
fredc649fe492012-04-19 01:07:18 -07001267 case MESSAGE_TIMEOUT_BIND: {
1268 Log.e(TAG, "MESSAGE_TIMEOUT_BIND");
fredc0f420372012-04-12 00:02:00 -07001269 synchronized(mConnection) {
1270 mBinding = false;
1271 }
fredc649fe492012-04-19 01:07:18 -07001272 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001273 }
fredcbf072a72012-05-09 16:52:50 -07001274 case MESSAGE_BLUETOOTH_STATE_CHANGE:
fredc0f420372012-04-12 00:02:00 -07001275 {
fredcbf072a72012-05-09 16:52:50 -07001276 int prevState = msg.arg1;
1277 int newState = msg.arg2;
1278 if (DBG) Log.d(TAG, "MESSAGE_BLUETOOTH_STATE_CHANGE: prevState = " + prevState + ", newState=" + newState);
Zhihai Xu40874a02012-10-08 17:57:03 -07001279 mState = newState;
1280 bluetoothStateChangeHandler(prevState, newState);
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001281 // handle error state transition case from TURNING_ON to OFF
1282 // unbind and rebind bluetooth service and enable bluetooth
Nitin Arorad055adb2015-03-02 15:03:51 -08001283 if ((prevState == BluetoothAdapter.STATE_BLE_TURNING_ON) &&
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001284 (newState == BluetoothAdapter.STATE_OFF) &&
1285 (mBluetooth != null) && mEnable) {
1286 recoverBluetoothServiceFromError();
1287 }
Nitin Arorad055adb2015-03-02 15:03:51 -08001288 if ((prevState == BluetoothAdapter.STATE_TURNING_ON) &&
1289 (newState == BluetoothAdapter.STATE_BLE_ON) &&
1290 (mBluetooth != null) && mEnable) {
1291 recoverBluetoothServiceFromError();
1292 }
1293 if (newState == BluetoothAdapter.STATE_ON ||
1294 newState == BluetoothAdapter.STATE_BLE_ON) {
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001295 // bluetooth is working, reset the counter
1296 if (mErrorRecoveryRetryCounter != 0) {
1297 Log.w(TAG, "bluetooth is recovered from error");
1298 mErrorRecoveryRetryCounter = 0;
1299 }
1300 }
fredc649fe492012-04-19 01:07:18 -07001301 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001302 }
fredc0f420372012-04-12 00:02:00 -07001303 case MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED:
1304 {
Matthew Xieddf7e472013-03-01 18:41:02 -08001305 Log.e(TAG, "MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED: " + msg.arg1);
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301306 synchronized(mConnection) {
Matthew Xieddf7e472013-03-01 18:41:02 -08001307 if (msg.arg1 == SERVICE_IBLUETOOTH) {
1308 // if service is unbinded already, do nothing and return
1309 if (mBluetooth == null) break;
1310 mBluetooth = null;
1311 } else if (msg.arg1 == SERVICE_IBLUETOOTHGATT) {
1312 mBluetoothGatt = null;
1313 break;
1314 } else {
1315 Log.e(TAG, "Bad msg.arg1: " + msg.arg1);
1316 break;
1317 }
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301318 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001319
1320 if (mEnable) {
1321 mEnable = false;
1322 // Send a Bluetooth Restart message
1323 Message restartMsg = mHandler.obtainMessage(
1324 MESSAGE_RESTART_BLUETOOTH_SERVICE);
1325 mHandler.sendMessageDelayed(restartMsg,
1326 SERVICE_RESTART_TIME_MS);
1327 }
1328
1329 if (!mConnection.isGetNameAddressOnly()) {
1330 sendBluetoothServiceDownCallback();
1331
1332 // Send BT state broadcast to update
1333 // the BT icon correctly
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001334 if ((mState == BluetoothAdapter.STATE_TURNING_ON) ||
1335 (mState == BluetoothAdapter.STATE_ON)) {
1336 bluetoothStateChangeHandler(BluetoothAdapter.STATE_ON,
1337 BluetoothAdapter.STATE_TURNING_OFF);
1338 mState = BluetoothAdapter.STATE_TURNING_OFF;
1339 }
1340 if (mState == BluetoothAdapter.STATE_TURNING_OFF) {
1341 bluetoothStateChangeHandler(BluetoothAdapter.STATE_TURNING_OFF,
1342 BluetoothAdapter.STATE_OFF);
1343 }
1344
1345 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
Zhihai Xu40874a02012-10-08 17:57:03 -07001346 mState = BluetoothAdapter.STATE_OFF;
1347 }
fredc649fe492012-04-19 01:07:18 -07001348 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001349 }
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301350 case MESSAGE_RESTART_BLUETOOTH_SERVICE:
1351 {
1352 Log.d(TAG, "MESSAGE_RESTART_BLUETOOTH_SERVICE:"
1353 +" Restart IBluetooth service");
1354 /* Enable without persisting the setting as
1355 it doesnt change when IBluetooth
1356 service restarts */
Zhihai Xu40874a02012-10-08 17:57:03 -07001357 mEnable = true;
Zhihai Xu401202b2012-12-03 11:36:21 -08001358 handleEnable(mQuietEnable);
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301359 break;
1360 }
1361
fredc0f420372012-04-12 00:02:00 -07001362 case MESSAGE_TIMEOUT_UNBIND:
1363 {
fredc649fe492012-04-19 01:07:18 -07001364 Log.e(TAG, "MESSAGE_TIMEOUT_UNBIND");
fredc0f420372012-04-12 00:02:00 -07001365 synchronized(mConnection) {
1366 mUnbinding = false;
1367 }
fredc649fe492012-04-19 01:07:18 -07001368 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001369 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001370
1371 case MESSAGE_USER_SWITCHED:
1372 {
1373 if (DBG) {
1374 Log.d(TAG, "MESSAGE_USER_SWITCHED");
1375 }
1376 mHandler.removeMessages(MESSAGE_USER_SWITCHED);
1377 /* disable and enable BT when detect a user switch */
1378 if (mEnable && mBluetooth != null) {
1379 synchronized (mConnection) {
1380 if (mBluetooth != null) {
1381 //Unregister callback object
1382 try {
1383 mBluetooth.unregisterCallback(mBluetoothCallback);
1384 } catch (RemoteException re) {
1385 Log.e(TAG, "Unable to unregister",re);
1386 }
1387 }
1388 }
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001389
1390 if (mState == BluetoothAdapter.STATE_TURNING_OFF) {
1391 // MESSAGE_USER_SWITCHED happened right after MESSAGE_ENABLE
1392 bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_OFF);
1393 mState = BluetoothAdapter.STATE_OFF;
1394 }
1395 if (mState == BluetoothAdapter.STATE_OFF) {
1396 bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_TURNING_ON);
1397 mState = BluetoothAdapter.STATE_TURNING_ON;
1398 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001399
1400 waitForOnOff(true, false);
1401
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001402 if (mState == BluetoothAdapter.STATE_TURNING_ON) {
1403 bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_ON);
1404 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001405
Benjamin Franze8b98922014-11-12 15:57:54 +00001406 unbindAllBluetoothProfileServices();
Zhihai Xu40874a02012-10-08 17:57:03 -07001407 // disable
Zhihai Xu401202b2012-12-03 11:36:21 -08001408 handleDisable();
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001409 // Pbap service need receive STATE_TURNING_OFF intent to close
1410 bluetoothStateChangeHandler(BluetoothAdapter.STATE_ON,
1411 BluetoothAdapter.STATE_TURNING_OFF);
Zhihai Xu40874a02012-10-08 17:57:03 -07001412
1413 waitForOnOff(false, true);
1414
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001415 bluetoothStateChangeHandler(BluetoothAdapter.STATE_TURNING_OFF,
Zhihai Xu40874a02012-10-08 17:57:03 -07001416 BluetoothAdapter.STATE_OFF);
Zhihai Xu40874a02012-10-08 17:57:03 -07001417 sendBluetoothServiceDownCallback();
1418 synchronized (mConnection) {
1419 if (mBluetooth != null) {
1420 mBluetooth = null;
1421 //Unbind
1422 mContext.unbindService(mConnection);
1423 }
1424 }
1425 SystemClock.sleep(100);
1426
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001427 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
1428 mState = BluetoothAdapter.STATE_OFF;
Zhihai Xu40874a02012-10-08 17:57:03 -07001429 // enable
Zhihai Xu401202b2012-12-03 11:36:21 -08001430 handleEnable(mQuietEnable);
John Spurlock8a985d22014-02-25 09:40:05 -05001431 } else if (mBinding || mBluetooth != null) {
Zhihai Xu40874a02012-10-08 17:57:03 -07001432 Message userMsg = mHandler.obtainMessage(MESSAGE_USER_SWITCHED);
1433 userMsg.arg2 = 1 + msg.arg2;
1434 // if user is switched when service is being binding
1435 // delay sending MESSAGE_USER_SWITCHED
1436 mHandler.sendMessageDelayed(userMsg, USER_SWITCHED_TIME_MS);
1437 if (DBG) {
1438 Log.d(TAG, "delay MESSAGE_USER_SWITCHED " + userMsg.arg2);
1439 }
John Spurlock8a985d22014-02-25 09:40:05 -05001440 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001441 break;
1442 }
fredc0f420372012-04-12 00:02:00 -07001443 }
1444 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001445 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001446
Zhihai Xu401202b2012-12-03 11:36:21 -08001447 private void handleEnable(boolean quietMode) {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001448 mQuietEnable = quietMode;
1449
Matthew Xiecdce0b92012-07-12 19:06:15 -07001450 synchronized(mConnection) {
Zhihai Xu40874a02012-10-08 17:57:03 -07001451 if ((mBluetooth == null) && (!mBinding)) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001452 //Start bind timeout and bind
1453 Message timeoutMsg=mHandler.obtainMessage(MESSAGE_TIMEOUT_BIND);
1454 mHandler.sendMessageDelayed(timeoutMsg,TIMEOUT_BIND_MS);
1455 mConnection.setGetNameAddressOnly(false);
1456 Intent i = new Intent(IBluetooth.class.getName());
Dianne Hackbornce09f5a2014-10-10 15:03:13 -07001457 if (!doBind(i, mConnection,Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT,
1458 UserHandle.CURRENT)) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001459 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
Zhihai Xu40874a02012-10-08 17:57:03 -07001460 } else {
1461 mBinding = true;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001462 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001463 } else if (mBluetooth != null) {
1464 if (mConnection.isGetNameAddressOnly()) {
1465 // if GetNameAddressOnly is set, we can clear this flag,
1466 // so the service won't be unbind
1467 // after name and address are saved
1468 mConnection.setGetNameAddressOnly(false);
1469 //Register callback object
1470 try {
1471 mBluetooth.registerCallback(mBluetoothCallback);
1472 } catch (RemoteException re) {
1473 Log.e(TAG, "Unable to register BluetoothCallback",re);
1474 }
1475 //Inform BluetoothAdapter instances that service is up
1476 sendBluetoothServiceUpCallback();
1477 }
1478
Matthew Xiecdce0b92012-07-12 19:06:15 -07001479 //Enable bluetooth
1480 try {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001481 if (!mQuietEnable) {
1482 if(!mBluetooth.enable()) {
1483 Log.e(TAG,"IBluetooth.enable() returned false");
1484 }
1485 }
1486 else {
1487 if(!mBluetooth.enableNoAutoConnect()) {
1488 Log.e(TAG,"IBluetooth.enableNoAutoConnect() returned false");
1489 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001490 }
1491 } catch (RemoteException e) {
1492 Log.e(TAG,"Unable to call enable()",e);
1493 }
1494 }
1495 }
1496 }
1497
Dianne Hackborn221ea892013-08-04 16:50:16 -07001498 boolean doBind(Intent intent, ServiceConnection conn, int flags, UserHandle user) {
1499 ComponentName comp = intent.resolveSystemService(mContext.getPackageManager(), 0);
1500 intent.setComponent(comp);
1501 if (comp == null || !mContext.bindServiceAsUser(intent, conn, flags, user)) {
1502 Log.e(TAG, "Fail to bind to: " + intent);
1503 return false;
1504 }
1505 return true;
1506 }
1507
Zhihai Xu401202b2012-12-03 11:36:21 -08001508 private void handleDisable() {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001509 synchronized(mConnection) {
Zhihai Xu40874a02012-10-08 17:57:03 -07001510 // don't need to disable if GetNameAddressOnly is set,
1511 // service will be unbinded after Name and Address are saved
1512 if ((mBluetooth != null) && (!mConnection.isGetNameAddressOnly())) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001513 if (DBG) Log.d(TAG,"Sending off request.");
1514
1515 try {
1516 if(!mBluetooth.disable()) {
1517 Log.e(TAG,"IBluetooth.disable() returned false");
1518 }
1519 } catch (RemoteException e) {
1520 Log.e(TAG,"Unable to call disable()",e);
1521 }
1522 }
1523 }
1524 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001525
1526 private boolean checkIfCallerIsForegroundUser() {
1527 int foregroundUser;
1528 int callingUser = UserHandle.getCallingUserId();
Martijn Coenen8385c5a2012-11-29 10:14:16 -08001529 int callingUid = Binder.getCallingUid();
Zhihai Xu40874a02012-10-08 17:57:03 -07001530 long callingIdentity = Binder.clearCallingIdentity();
Benjamin Franze8b98922014-11-12 15:57:54 +00001531 UserManager um = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
1532 UserInfo ui = um.getProfileParent(callingUser);
1533 int parentUser = (ui != null) ? ui.id : UserHandle.USER_NULL;
Martijn Coenen8385c5a2012-11-29 10:14:16 -08001534 int callingAppId = UserHandle.getAppId(callingUid);
Zhihai Xu40874a02012-10-08 17:57:03 -07001535 boolean valid = false;
1536 try {
1537 foregroundUser = ActivityManager.getCurrentUser();
Martijn Coenen8385c5a2012-11-29 10:14:16 -08001538 valid = (callingUser == foregroundUser) ||
Benjamin Franze8b98922014-11-12 15:57:54 +00001539 parentUser == foregroundUser ||
Adrian Roosbd9a9a52014-08-18 15:31:57 +02001540 callingAppId == Process.NFC_UID ||
1541 callingAppId == mSystemUiUid;
Zhihai Xu40874a02012-10-08 17:57:03 -07001542 if (DBG) {
1543 Log.d(TAG, "checkIfCallerIsForegroundUser: valid=" + valid
1544 + " callingUser=" + callingUser
Benjamin Franze8b98922014-11-12 15:57:54 +00001545 + " parentUser=" + parentUser
Zhihai Xu40874a02012-10-08 17:57:03 -07001546 + " foregroundUser=" + foregroundUser);
1547 }
1548 } finally {
1549 Binder.restoreCallingIdentity(callingIdentity);
1550 }
1551 return valid;
1552 }
1553
Nitin Arorad055adb2015-03-02 15:03:51 -08001554 private void sendBleStateChanged(int prevState, int newState) {
1555 if (DBG) Log.d(TAG,"BLE State Change Intent: " + prevState + " -> " + newState);
1556 // Send broadcast message to everyone else
1557 Intent intent = new Intent(BluetoothAdapter.ACTION_BLE_STATE_CHANGED);
1558 intent.putExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE, prevState);
1559 intent.putExtra(BluetoothAdapter.EXTRA_STATE, newState);
1560 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1561 mContext.sendBroadcastAsUser(intent, UserHandle.ALL, BLUETOOTH_PERM);
1562 }
1563
Zhihai Xu40874a02012-10-08 17:57:03 -07001564 private void bluetoothStateChangeHandler(int prevState, int newState) {
Nitin Arorad055adb2015-03-02 15:03:51 -08001565 boolean isStandardBroadcast = true;
Zhihai Xu40874a02012-10-08 17:57:03 -07001566 if (prevState != newState) {
1567 //Notify all proxy objects first of adapter state change
Nitin Arorad055adb2015-03-02 15:03:51 -08001568 if (newState == BluetoothAdapter.STATE_BLE_ON
1569 || newState == BluetoothAdapter.STATE_OFF) {
1570 boolean intermediate_off = (prevState == BluetoothAdapter.STATE_TURNING_OFF
1571 && newState == BluetoothAdapter.STATE_BLE_ON);
Zhihai Xu40874a02012-10-08 17:57:03 -07001572
Nitin Arorad055adb2015-03-02 15:03:51 -08001573 if (newState == BluetoothAdapter.STATE_OFF) {
1574 // If Bluetooth is off, send service down event to proxy objects, and unbind
1575 if (DBG) Log.d(TAG, "Bluetooth is complete turn off");
1576 if (canUnbindBluetoothService()) {
1577 if (DBG) Log.d(TAG, "Good to unbind!");
Matthew Xieddf7e472013-03-01 18:41:02 -08001578 sendBluetoothServiceDownCallback();
1579 unbindAndFinish();
Nitin Arorad055adb2015-03-02 15:03:51 -08001580 sendBleStateChanged(prevState, newState);
1581 // Don't broadcast as it has already been broadcast before
1582 isStandardBroadcast = false;
Matthew Xieddf7e472013-03-01 18:41:02 -08001583 }
Nitin Arorad055adb2015-03-02 15:03:51 -08001584
1585 } else if (!intermediate_off) {
1586 // connect to GattService
1587 if (DBG) Log.d(TAG, "Bluetooth is in LE only mode");
1588 if (mBluetoothGatt != null) {
1589 if (DBG) Log.d(TAG, "Calling BluetoothGattServiceUp");
1590 onBluetoothGattServiceUp();
1591 } else {
1592 if (DBG) Log.d(TAG, "Binding Bluetooth GATT service");
1593 if (mContext.getPackageManager().hasSystemFeature(
1594 PackageManager.FEATURE_BLUETOOTH_LE)) {
1595 Intent i = new Intent(IBluetoothGatt.class.getName());
1596 doBind(i, mConnection, Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT, UserHandle.CURRENT);
1597 }
1598 }
1599 sendBleStateChanged(prevState, newState);
1600 //Don't broadcase this as std intent
1601 isStandardBroadcast = false;
1602
1603 } else if (intermediate_off){
1604 if (DBG) Log.d(TAG, "Intermediate off, back to LE only mode");
1605 // For LE only mode, broadcast as is
1606 sendBleStateChanged(prevState, newState);
1607 sendBluetoothStateCallback(false); // BT is OFF for general users
1608 // Broadcast as STATE_OFF
1609 newState = BluetoothAdapter.STATE_OFF;
1610 sendBrEdrDownCallback();
Zhihai Xu40874a02012-10-08 17:57:03 -07001611 }
Nitin Arorad055adb2015-03-02 15:03:51 -08001612 } else if (newState == BluetoothAdapter.STATE_ON) {
1613 boolean isUp = (newState==BluetoothAdapter.STATE_ON);
1614 sendBluetoothStateCallback(isUp);
1615 sendBleStateChanged(prevState, newState);
1616
1617 } else if (newState == BluetoothAdapter.STATE_BLE_TURNING_ON
1618 || newState == BluetoothAdapter.STATE_BLE_TURNING_OFF ) {
1619 sendBleStateChanged(prevState, newState);
1620 isStandardBroadcast = false;
1621
1622 } else if (newState == BluetoothAdapter.STATE_TURNING_ON
1623 || newState == BluetoothAdapter.STATE_TURNING_OFF) {
1624 sendBleStateChanged(prevState, newState);
Zhihai Xu40874a02012-10-08 17:57:03 -07001625 }
1626
Nitin Arorad055adb2015-03-02 15:03:51 -08001627 if (isStandardBroadcast) {
1628 if (prevState == BluetoothAdapter.STATE_BLE_ON) {
1629 // Show prevState of BLE_ON as OFF to standard users
1630 prevState = BluetoothAdapter.STATE_OFF;
1631 }
1632 Intent intent = new Intent(BluetoothAdapter.ACTION_STATE_CHANGED);
1633 intent.putExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE, prevState);
1634 intent.putExtra(BluetoothAdapter.EXTRA_STATE, newState);
1635 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1636 mContext.sendBroadcastAsUser(intent, UserHandle.ALL, BLUETOOTH_PERM);
1637 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001638 }
1639 }
1640
1641 /**
1642 * if on is true, wait for state become ON
1643 * if off is true, wait for state become OFF
1644 * if both on and off are false, wait for state not ON
1645 */
1646 private boolean waitForOnOff(boolean on, boolean off) {
1647 int i = 0;
1648 while (i < 10) {
1649 synchronized(mConnection) {
1650 try {
1651 if (mBluetooth == null) break;
1652 if (on) {
1653 if (mBluetooth.getState() == BluetoothAdapter.STATE_ON) return true;
1654 } else if (off) {
1655 if (mBluetooth.getState() == BluetoothAdapter.STATE_OFF) return true;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07001656 } else {
Zhihai Xu40874a02012-10-08 17:57:03 -07001657 if (mBluetooth.getState() != BluetoothAdapter.STATE_ON) return true;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07001658 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001659 } catch (RemoteException e) {
1660 Log.e(TAG, "getState()", e);
1661 break;
1662 }
1663 }
1664 if (on || off) {
1665 SystemClock.sleep(300);
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07001666 } else {
Zhihai Xu40874a02012-10-08 17:57:03 -07001667 SystemClock.sleep(50);
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07001668 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001669 i++;
1670 }
1671 Log.e(TAG,"waitForOnOff time out");
1672 return false;
1673 }
Zhihai Xu681ae7f2012-11-12 15:14:18 -08001674
Zhihai Xu401202b2012-12-03 11:36:21 -08001675 private void sendDisableMsg() {
1676 mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_DISABLE));
1677 }
1678
1679 private void sendEnableMsg(boolean quietMode) {
1680 mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_ENABLE,
1681 quietMode ? 1 : 0, 0));
1682 }
1683
Zhihai Xu681ae7f2012-11-12 15:14:18 -08001684 private boolean canUnbindBluetoothService() {
1685 synchronized(mConnection) {
1686 //Only unbind with mEnable flag not set
1687 //For race condition: disable and enable back-to-back
1688 //Avoid unbind right after enable due to callback from disable
1689 //Only unbind with Bluetooth at OFF state
1690 //Only unbind without any MESSAGE_BLUETOOTH_STATE_CHANGE message
1691 try {
1692 if (mEnable || (mBluetooth == null)) return false;
1693 if (mHandler.hasMessages(MESSAGE_BLUETOOTH_STATE_CHANGE)) return false;
1694 return (mBluetooth.getState() == BluetoothAdapter.STATE_OFF);
1695 } catch (RemoteException e) {
1696 Log.e(TAG, "getState()", e);
1697 }
1698 }
1699 return false;
1700 }
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001701
1702 private void recoverBluetoothServiceFromError() {
1703 Log.e(TAG,"recoverBluetoothServiceFromError");
1704 synchronized (mConnection) {
1705 if (mBluetooth != null) {
1706 //Unregister callback object
1707 try {
1708 mBluetooth.unregisterCallback(mBluetoothCallback);
1709 } catch (RemoteException re) {
1710 Log.e(TAG, "Unable to unregister",re);
1711 }
1712 }
1713 }
1714
1715 SystemClock.sleep(500);
1716
1717 // disable
1718 handleDisable();
1719
1720 waitForOnOff(false, true);
1721
1722 sendBluetoothServiceDownCallback();
1723 synchronized (mConnection) {
1724 if (mBluetooth != null) {
1725 mBluetooth = null;
1726 //Unbind
1727 mContext.unbindService(mConnection);
1728 }
1729 }
1730
1731 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
1732 mState = BluetoothAdapter.STATE_OFF;
1733
1734 mEnable = false;
1735
1736 if (mErrorRecoveryRetryCounter++ < MAX_ERROR_RESTART_RETRIES) {
1737 // Send a Bluetooth Restart message to reenable bluetooth
1738 Message restartMsg = mHandler.obtainMessage(
1739 MESSAGE_RESTART_BLUETOOTH_SERVICE);
1740 mHandler.sendMessageDelayed(restartMsg, ERROR_RESTART_TIME_MS);
1741 } else {
1742 // todo: notify user to power down and power up phone to make bluetooth work.
1743 }
1744 }
Mike Lockwood726d4de2014-10-28 14:06:28 -07001745
1746 @Override
1747 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Mike Lockwood75b52bb2014-12-18 14:16:36 -08001748 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DUMP, TAG);
1749
Andre Eisenbach14dcb5f2014-12-05 09:31:30 -08001750 writer.println("Bluetooth Status");
1751 writer.println(" enabled: " + mEnable);
1752 writer.println(" state: " + mState);
1753 writer.println(" address: " + mAddress);
1754 writer.println(" name: " + mName + "\n");
1755 writer.flush();
1756
Mike Lockwood726d4de2014-10-28 14:06:28 -07001757 if (mBluetooth == null) {
1758 writer.println("Bluetooth Service not connected");
1759 } else {
Andre Eisenbach14dcb5f2014-12-05 09:31:30 -08001760 ParcelFileDescriptor pfd = null;
Mike Lockwood726d4de2014-10-28 14:06:28 -07001761 try {
Andre Eisenbach14dcb5f2014-12-05 09:31:30 -08001762 pfd = ParcelFileDescriptor.dup(fd);
1763 mBluetooth.dump(pfd);
Mike Lockwood726d4de2014-10-28 14:06:28 -07001764 } catch (RemoteException re) {
1765 writer.println("RemoteException while calling Bluetooth Service");
Andre Eisenbach14dcb5f2014-12-05 09:31:30 -08001766 } catch (IOException ioe) {
1767 writer.println("IOException attempting to dup() fd");
1768 } finally {
1769 if (pfd != null) {
1770 try {
1771 pfd.close();
1772 } catch (IOException ioe) {
1773 writer.println("IOException attempting to close() fd");
1774 }
1775 }
Mike Lockwood726d4de2014-10-28 14:06:28 -07001776 }
1777 }
1778 }
fredc0f420372012-04-12 00:02:00 -07001779}