blob: 32b91d25fb17031caa32194f453ccdbd2af505eb [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
Zhihai Xu40874a02012-10-08 17:57:03 -070019import android.app.ActivityManager;
fredc0f420372012-04-12 00:02:00 -070020import android.bluetooth.BluetoothAdapter;
Benjamin Franze8b98922014-11-12 15:57:54 +000021import android.bluetooth.BluetoothProfile;
fredc0f420372012-04-12 00:02:00 -070022import android.bluetooth.IBluetooth;
Matthew Xieddf7e472013-03-01 18:41:02 -080023import android.bluetooth.IBluetoothGatt;
fredcbf072a72012-05-09 16:52:50 -070024import android.bluetooth.IBluetoothCallback;
Benjamin Franze8b98922014-11-12 15:57:54 +000025import android.bluetooth.IBluetoothHeadset;
fredc0f420372012-04-12 00:02:00 -070026import android.bluetooth.IBluetoothManager;
27import android.bluetooth.IBluetoothManagerCallback;
Benjamin Franze8b98922014-11-12 15:57:54 +000028import android.bluetooth.IBluetoothProfileServiceConnection;
fredc0f420372012-04-12 00:02:00 -070029import android.bluetooth.IBluetoothStateChangeCallback;
fredc0f420372012-04-12 00:02:00 -070030import android.content.BroadcastReceiver;
31import android.content.ComponentName;
32import android.content.ContentResolver;
33import android.content.Context;
34import android.content.Intent;
35import android.content.IntentFilter;
36import android.content.ServiceConnection;
Matthew Xie32ab77b2013-05-08 19:26:57 -070037import android.content.pm.PackageManager;
Benjamin Franze8b98922014-11-12 15:57:54 +000038import android.content.pm.UserInfo;
Zhihai Xu40874a02012-10-08 17:57:03 -070039import android.os.Binder;
fredc0f420372012-04-12 00:02:00 -070040import android.os.Handler;
fredc0f420372012-04-12 00:02:00 -070041import android.os.IBinder;
Zhihai Xu40874a02012-10-08 17:57:03 -070042import android.os.Looper;
fredc0f420372012-04-12 00:02:00 -070043import android.os.Message;
Zhihai Xu40874a02012-10-08 17:57:03 -070044import android.os.Process;
fredcd6883532012-04-25 17:46:13 -070045import android.os.RemoteCallbackList;
fredc0f420372012-04-12 00:02:00 -070046import android.os.RemoteException;
Zhihai Xu40874a02012-10-08 17:57:03 -070047import android.os.SystemClock;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070048import android.os.UserHandle;
Benjamin Franze8b98922014-11-12 15:57:54 +000049import android.os.UserManager;
fredc0f420372012-04-12 00:02:00 -070050import android.provider.Settings;
Wei Wang67d84162015-04-26 17:04:29 -070051import android.provider.Settings.SettingNotFoundException;
fredc0f420372012-04-12 00:02:00 -070052import android.util.Log;
Mike Lockwood726d4de2014-10-28 14:06:28 -070053
54import java.io.FileDescriptor;
55import java.io.PrintWriter;
56
Benjamin Franze8b98922014-11-12 15:57:54 +000057import java.util.HashMap;
58import java.util.Map;
Benjamin Franze8b98922014-11-12 15:57:54 +000059
Nitin Arora6ddbb5e2015-03-02 15:03:51 -080060import java.util.*;
fredc0f420372012-04-12 00:02:00 -070061class BluetoothManagerService extends IBluetoothManager.Stub {
62 private static final String TAG = "BluetoothManagerService";
63 private static final boolean DBG = true;
64
fredc0f420372012-04-12 00:02:00 -070065 private static final String BLUETOOTH_ADMIN_PERM = android.Manifest.permission.BLUETOOTH_ADMIN;
66 private static final String BLUETOOTH_PERM = android.Manifest.permission.BLUETOOTH;
fredc0f420372012-04-12 00:02:00 -070067 private static final String ACTION_SERVICE_STATE_CHANGED="com.android.bluetooth.btservice.action.STATE_CHANGED";
68 private static final String EXTRA_ACTION="action";
Zhihai Xud31c3222012-10-31 16:08:57 -070069 private static final String SECURE_SETTINGS_BLUETOOTH_ADDR_VALID="bluetooth_addr_valid";
fredc0f420372012-04-12 00:02:00 -070070 private static final String SECURE_SETTINGS_BLUETOOTH_ADDRESS="bluetooth_address";
71 private static final String SECURE_SETTINGS_BLUETOOTH_NAME="bluetooth_name";
fredc0f420372012-04-12 00:02:00 -070072 private static final int TIMEOUT_BIND_MS = 3000; //Maximum msec to wait for a bind
73 private static final int TIMEOUT_SAVE_MS = 500; //Maximum msec to wait for a save
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +053074 //Maximum msec to wait for service restart
75 private static final int SERVICE_RESTART_TIME_MS = 200;
Zhihai Xudd9d17d2013-01-08 17:05:58 -080076 //Maximum msec to wait for restart due to error
77 private static final int ERROR_RESTART_TIME_MS = 3000;
Zhihai Xu40874a02012-10-08 17:57:03 -070078 //Maximum msec to delay MESSAGE_USER_SWITCHED
79 private static final int USER_SWITCHED_TIME_MS = 200;
Benjamin Franze8b98922014-11-12 15:57:54 +000080 // Delay for the addProxy function in msec
81 private static final int ADD_PROXY_DELAY_MS = 100;
fredc0f420372012-04-12 00:02:00 -070082
83 private static final int MESSAGE_ENABLE = 1;
84 private static final int MESSAGE_DISABLE = 2;
fredc649fe492012-04-19 01:07:18 -070085 private static final int MESSAGE_REGISTER_ADAPTER = 20;
86 private static final int MESSAGE_UNREGISTER_ADAPTER = 21;
87 private static final int MESSAGE_REGISTER_STATE_CHANGE_CALLBACK = 30;
88 private static final int MESSAGE_UNREGISTER_STATE_CHANGE_CALLBACK = 31;
89 private static final int MESSAGE_BLUETOOTH_SERVICE_CONNECTED = 40;
90 private static final int MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED = 41;
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +053091 private static final int MESSAGE_RESTART_BLUETOOTH_SERVICE = 42;
fredcbf072a72012-05-09 16:52:50 -070092 private static final int MESSAGE_BLUETOOTH_STATE_CHANGE=60;
fredc0f420372012-04-12 00:02:00 -070093 private static final int MESSAGE_TIMEOUT_BIND =100;
94 private static final int MESSAGE_TIMEOUT_UNBIND =101;
95 private static final int MESSAGE_GET_NAME_AND_ADDRESS=200;
96 private static final int MESSAGE_SAVE_NAME_AND_ADDRESS=201;
Zhihai Xu40874a02012-10-08 17:57:03 -070097 private static final int MESSAGE_USER_SWITCHED = 300;
Benjamin Franze8b98922014-11-12 15:57:54 +000098 private static final int MESSAGE_ADD_PROXY_DELAYED = 400;
99 private static final int MESSAGE_BIND_PROFILE_SERVICE = 401;
fredc0f420372012-04-12 00:02:00 -0700100 private static final int MAX_SAVE_RETRIES=3;
Zhihai Xudd9d17d2013-01-08 17:05:58 -0800101 private static final int MAX_ERROR_RESTART_RETRIES=6;
102
Zhihai Xu401202b2012-12-03 11:36:21 -0800103 // Bluetooth persisted setting is off
104 private static final int BLUETOOTH_OFF=0;
105 // Bluetooth persisted setting is on
106 // and Airplane mode won't affect Bluetooth state at start up
107 private static final int BLUETOOTH_ON_BLUETOOTH=1;
108 // Bluetooth persisted setting is on
109 // but Airplane mode will affect Bluetooth state at start up
110 // and Airplane mode will have higher priority.
111 private static final int BLUETOOTH_ON_AIRPLANE=2;
fredc0f420372012-04-12 00:02:00 -0700112
Matthew Xieddf7e472013-03-01 18:41:02 -0800113 private static final int SERVICE_IBLUETOOTH = 1;
114 private static final int SERVICE_IBLUETOOTHGATT = 2;
115
fredc0f420372012-04-12 00:02:00 -0700116 private final Context mContext;
Nitin Arorad055adb2015-03-02 15:03:51 -0800117 private static int mBleAppCount = 0;
Matthew Xiecdce0b92012-07-12 19:06:15 -0700118
119 // Locks are not provided for mName and mAddress.
120 // They are accessed in handler or broadcast receiver, same thread context.
fredc0f420372012-04-12 00:02:00 -0700121 private String mAddress;
122 private String mName;
Matthew Xie6fde3092012-07-11 17:10:07 -0700123 private final ContentResolver mContentResolver;
124 private final RemoteCallbackList<IBluetoothManagerCallback> mCallbacks;
125 private final RemoteCallbackList<IBluetoothStateChangeCallback> mStateChangeCallbacks;
fredc649fe492012-04-19 01:07:18 -0700126 private IBluetooth mBluetooth;
Matthew Xieddf7e472013-03-01 18:41:02 -0800127 private IBluetoothGatt mBluetoothGatt;
fredc649fe492012-04-19 01:07:18 -0700128 private boolean mBinding;
129 private boolean mUnbinding;
Zhihai Xu401202b2012-12-03 11:36:21 -0800130 // used inside handler thread
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700131 private boolean mQuietEnable = false;
Zhihai Xu401202b2012-12-03 11:36:21 -0800132 // configuarion from external IBinder call which is used to
133 // synchronize with broadcast receiver.
134 private boolean mQuietEnableExternal;
135 // configuarion from external IBinder call which is used to
136 // synchronize with broadcast receiver.
137 private boolean mEnableExternal;
138 // used inside handler thread
Zhihai Xu40874a02012-10-08 17:57:03 -0700139 private boolean mEnable;
140 private int mState;
Zhihai Xu40874a02012-10-08 17:57:03 -0700141 private final BluetoothHandler mHandler;
Zhihai Xudd9d17d2013-01-08 17:05:58 -0800142 private int mErrorRecoveryRetryCounter;
Adrian Roosbd9a9a52014-08-18 15:31:57 +0200143 private final int mSystemUiUid;
fredc0f420372012-04-12 00:02:00 -0700144
Benjamin Franze8b98922014-11-12 15:57:54 +0000145 // Save a ProfileServiceConnections object for each of the bound
146 // bluetooth profile services
147 private final Map <Integer, ProfileServiceConnections> mProfileServices =
148 new HashMap <Integer, ProfileServiceConnections>();
149
fredc649fe492012-04-19 01:07:18 -0700150 private void registerForAirplaneMode(IntentFilter filter) {
151 final ContentResolver resolver = mContext.getContentResolver();
Christopher Tatec09cdce2012-09-10 16:50:14 -0700152 final String airplaneModeRadios = Settings.Global.getString(resolver,
153 Settings.Global.AIRPLANE_MODE_RADIOS);
154 final String toggleableRadios = Settings.Global.getString(resolver,
155 Settings.Global.AIRPLANE_MODE_TOGGLEABLE_RADIOS);
fredc649fe492012-04-19 01:07:18 -0700156 boolean mIsAirplaneSensitive = airplaneModeRadios == null ? true :
Christopher Tatec09cdce2012-09-10 16:50:14 -0700157 airplaneModeRadios.contains(Settings.Global.RADIO_BLUETOOTH);
fredc649fe492012-04-19 01:07:18 -0700158 if (mIsAirplaneSensitive) {
159 filter.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED);
160 }
161 }
162
fredcbf072a72012-05-09 16:52:50 -0700163 private final IBluetoothCallback mBluetoothCallback = new IBluetoothCallback.Stub() {
164 @Override
165 public void onBluetoothStateChange(int prevState, int newState) throws RemoteException {
166 Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_STATE_CHANGE,prevState,newState);
167 mHandler.sendMessage(msg);
168 }
169 };
170
171 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
fredc0f420372012-04-12 00:02:00 -0700172 @Override
173 public void onReceive(Context context, Intent intent) {
174 String action = intent.getAction();
fredcbf072a72012-05-09 16:52:50 -0700175 if (BluetoothAdapter.ACTION_LOCAL_NAME_CHANGED.equals(action)) {
fredc0f420372012-04-12 00:02:00 -0700176 String newName = intent.getStringExtra(BluetoothAdapter.EXTRA_LOCAL_NAME);
Freda8c6df02012-07-11 10:25:23 -0700177 if (DBG) Log.d(TAG, "Bluetooth Adapter name changed to " + newName);
fredc0f420372012-04-12 00:02:00 -0700178 if (newName != null) {
179 storeNameAndAddress(newName, null);
180 }
fredc649fe492012-04-19 01:07:18 -0700181 } else if (Intent.ACTION_AIRPLANE_MODE_CHANGED.equals(action)) {
Zhihai Xu401202b2012-12-03 11:36:21 -0800182 synchronized(mReceiver) {
183 if (isBluetoothPersistedStateOn()) {
184 if (isAirplaneModeOn()) {
185 persistBluetoothSetting(BLUETOOTH_ON_AIRPLANE);
186 } else {
187 persistBluetoothSetting(BLUETOOTH_ON_BLUETOOTH);
188 }
189 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800190
191 int st = BluetoothAdapter.STATE_OFF;
192 if (mBluetooth != null) {
193 try {
194 st = mBluetooth.getState();
195 } catch (RemoteException e) {
196 Log.e(TAG,"Unable to call getState", e);
197 }
198 }
199 Log.d(TAG, "state" + st);
200
Zhihai Xu401202b2012-12-03 11:36:21 -0800201 if (isAirplaneModeOn()) {
Nitin Arorad055adb2015-03-02 15:03:51 -0800202 // Clear registered LE apps to force shut-off
203 synchronized (this) {
204 mBleAppCount = 0;
205 }
206 if (st == BluetoothAdapter.STATE_BLE_ON) {
207 //if state is BLE_ON make sure you trigger disableBLE part
208 try {
209 if (mBluetooth != null) {
210 mBluetooth.onBrEdrDown();
211 mEnableExternal = false;
212 }
213 } catch(RemoteException e) {
214 Log.e(TAG,"Unable to call onBrEdrDown", e);
215 }
216 } else if (st == BluetoothAdapter.STATE_ON){
217 // disable without persisting the setting
218 Log.d(TAG, "Calling disable");
219 sendDisableMsg();
220 }
Zhihai Xu401202b2012-12-03 11:36:21 -0800221 } else if (mEnableExternal) {
222 // enable without persisting the setting
Nitin Arorad055adb2015-03-02 15:03:51 -0800223 Log.d(TAG, "Calling enable");
Zhihai Xu401202b2012-12-03 11:36:21 -0800224 sendEnableMsg(mQuietEnableExternal);
225 }
fredc649fe492012-04-19 01:07:18 -0700226 }
Zhihai Xu40874a02012-10-08 17:57:03 -0700227 } else if (Intent.ACTION_USER_SWITCHED.equals(action)) {
228 mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_USER_SWITCHED,
229 intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0), 0));
Zhihai Xu401202b2012-12-03 11:36:21 -0800230 } else if (Intent.ACTION_BOOT_COMPLETED.equals(action)) {
231 synchronized(mReceiver) {
232 if (mEnableExternal && isBluetoothPersistedStateOnBluetooth()) {
233 //Enable
234 if (DBG) Log.d(TAG, "Auto-enabling Bluetooth.");
235 sendEnableMsg(mQuietEnableExternal);
236 }
237 }
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();
fredcd6883532012-04-25 17:46:13 -0700258 mCallbacks = new RemoteCallbackList<IBluetoothManagerCallback>();
259 mStateChangeCallbacks = new RemoteCallbackList<IBluetoothStateChangeCallback>();
Zhihai Xu401202b2012-12-03 11:36:21 -0800260 IntentFilter filter = new IntentFilter(Intent.ACTION_BOOT_COMPLETED);
Matthew Xie6fde3092012-07-11 17:10:07 -0700261 filter.addAction(BluetoothAdapter.ACTION_LOCAL_NAME_CHANGED);
Zhihai Xu40874a02012-10-08 17:57:03 -0700262 filter.addAction(Intent.ACTION_USER_SWITCHED);
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
Nitin Arorad055adb2015-03-02 15:03:51 -0800457 public int updateBleAppCount(IBinder token, boolean enable) {
458 if (enable) {
459 ClientDeathRecipient r = mBleApps.get(token);
460 if (r == null) {
461 ClientDeathRecipient deathRec = new ClientDeathRecipient();
462 try {
463 token.linkToDeath(deathRec, 0);
464 } catch (RemoteException ex) {
465 throw new IllegalArgumentException("Wake lock is already dead.");
466 }
467 mBleApps.put(token, deathRec);
468 synchronized (this) {
469 ++mBleAppCount;
470 }
471 if (DBG) Log.d(TAG, "Registered for death Notification");
472 }
473
474 } else {
475 ClientDeathRecipient r = mBleApps.get(token);
476 if (r != null) {
477 try {
478 token.linkToDeath(r, 0);
479 } catch (RemoteException ex) {
480 throw new IllegalArgumentException("Wake lock is already dead.");
481 }
482 mBleApps.remove(token);
483 synchronized (this) {
484 if (mBleAppCount > 0) --mBleAppCount;
485 }
486 if (DBG) Log.d(TAG, "Unregistered for death Notification");
487 }
488 }
489 if (DBG) Log.d(TAG, "Updated BleAppCount" + mBleAppCount);
490 if (mBleAppCount == 0 && mEnable) {
491 try {
492 if (mBluetooth != null && (mBluetooth.getState() != BluetoothAdapter.STATE_ON)) {
493 if (DBG) Log.d(TAG, "Reseting the mEnable flag for clean disable");
494 mEnable = false;
495 }
496 } catch (RemoteException e) {
497 Log.e(TAG, "getState()", e);
498 }
499 }
500 return mBleAppCount;
501 }
502
503 /** @hide*/
504 public boolean isBleAppPresent() {
505 if (DBG) Log.d(TAG, "isBleAppPresent() count: " + mBleAppCount);
506 return (mBleAppCount > 0);
507 }
508
509 /**
510 * Action taken when GattService is turned off
511 */
512 private void onBluetoothGattServiceUp() {
513 if (DBG) Log.d(TAG,"BluetoothGatt Service is Up");
514 try{
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700515 if (isBleAppPresent() == false && mBluetooth != null
516 && mBluetooth.getState() == BluetoothAdapter.STATE_BLE_ON) {
Nitin Arorad055adb2015-03-02 15:03:51 -0800517 mBluetooth.onLeServiceUp();
518
519 // waive WRITE_SECURE_SETTINGS permission check
520 long callingIdentity = Binder.clearCallingIdentity();
521 persistBluetoothSetting(BLUETOOTH_ON_BLUETOOTH);
522 Binder.restoreCallingIdentity(callingIdentity);
523 }
524 } catch(RemoteException e) {
525 Log.e(TAG,"Unable to call onServiceUp", e);
526 }
527 }
528
529 /**
530 * Inform BluetoothAdapter instances that BREDR part is down
531 * and turn off all service and stack if no LE app needs it
532 */
533 private void sendBrEdrDownCallback() {
534 if (DBG) Log.d(TAG,"Calling sendBrEdrDownCallback callbacks");
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700535
536 if(mBluetooth == null) {
537 Log.w(TAG, "Bluetooth handle is null");
538 return;
539 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800540
541 if (isBleAppPresent() == false) {
542 try {
543 mBluetooth.onBrEdrDown();
544 } catch(RemoteException e) {
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700545 Log.e(TAG, "Call to onBrEdrDown() failed.", e);
Nitin Arorad055adb2015-03-02 15:03:51 -0800546 }
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700547 } else {
548 // Need to stay at BLE ON. Disconnect all Gatt connections
Nitin Arorad055adb2015-03-02 15:03:51 -0800549 try{
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700550 mBluetoothGatt.unregAll();
Nitin Arorad055adb2015-03-02 15:03:51 -0800551 } catch(RemoteException e) {
Nitin Arorabdfaa7f2015-04-29 12:35:03 -0700552 Log.e(TAG, "Unable to disconnect all apps.", e);
Nitin Arorad055adb2015-03-02 15:03:51 -0800553 }
554 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800555 }
556
557 /** @hide*/
fredc0f420372012-04-12 00:02:00 -0700558 public void getNameAndAddress() {
fredcf2458862012-04-16 15:18:27 -0700559 if (DBG) {
Matthew Xiecdce0b92012-07-12 19:06:15 -0700560 Log.d(TAG,"getNameAndAddress(): mBluetooth = " + mBluetooth +
561 " mBinding = " + mBinding);
fredcf2458862012-04-16 15:18:27 -0700562 }
fredc0f420372012-04-12 00:02:00 -0700563 Message msg = mHandler.obtainMessage(MESSAGE_GET_NAME_AND_ADDRESS);
564 mHandler.sendMessage(msg);
565 }
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700566 public boolean enableNoAutoConnect()
567 {
568 mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
569 "Need BLUETOOTH ADMIN permission");
Zhihai Xu40874a02012-10-08 17:57:03 -0700570
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700571 if (DBG) {
572 Log.d(TAG,"enableNoAutoConnect(): mBluetooth =" + mBluetooth +
573 " mBinding = " + mBinding);
574 }
Martijn Coenen8385c5a2012-11-29 10:14:16 -0800575 int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
576
577 if (callingAppId != Process.NFC_UID) {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700578 throw new SecurityException("no permission to enable Bluetooth quietly");
579 }
Martijn Coenen8385c5a2012-11-29 10:14:16 -0800580
Zhihai Xu401202b2012-12-03 11:36:21 -0800581 synchronized(mReceiver) {
582 mQuietEnableExternal = true;
583 mEnableExternal = true;
584 sendEnableMsg(true);
585 }
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700586 return true;
587
588 }
fredc0f420372012-04-12 00:02:00 -0700589 public boolean enable() {
Zhihai Xu6eb76522012-11-29 15:41:04 -0800590 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
591 (!checkIfCallerIsForegroundUser())) {
592 Log.w(TAG,"enable(): not allowed for non-active and non system user");
Zhihai Xu40874a02012-10-08 17:57:03 -0700593 return false;
fredcf2458862012-04-16 15:18:27 -0700594 }
595
Zhihai Xu401202b2012-12-03 11:36:21 -0800596 mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
597 "Need BLUETOOTH ADMIN permission");
598 if (DBG) {
599 Log.d(TAG,"enable(): mBluetooth =" + mBluetooth +
600 " mBinding = " + mBinding);
601 }
602
603 synchronized(mReceiver) {
604 mQuietEnableExternal = false;
605 mEnableExternal = true;
606 // waive WRITE_SECURE_SETTINGS permission check
Zhihai Xu401202b2012-12-03 11:36:21 -0800607 sendEnableMsg(false);
608 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800609 if (DBG) Log.d(TAG, "enable returning");
Zhihai Xu401202b2012-12-03 11:36:21 -0800610 return true;
fredc0f420372012-04-12 00:02:00 -0700611 }
612
613 public boolean disable(boolean persist) {
614 mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
615 "Need BLUETOOTH ADMIN permissicacheNameAndAddresson");
Zhihai Xu40874a02012-10-08 17:57:03 -0700616
Zhihai Xu6eb76522012-11-29 15:41:04 -0800617 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
618 (!checkIfCallerIsForegroundUser())) {
619 Log.w(TAG,"disable(): not allowed for non-active and non system user");
Zhihai Xu40874a02012-10-08 17:57:03 -0700620 return false;
621 }
622
fredcf2458862012-04-16 15:18:27 -0700623 if (DBG) {
Matthew Xiecdce0b92012-07-12 19:06:15 -0700624 Log.d(TAG,"disable(): mBluetooth = " + mBluetooth +
625 " mBinding = " + mBinding);
626 }
fredcf2458862012-04-16 15:18:27 -0700627
Zhihai Xu401202b2012-12-03 11:36:21 -0800628 synchronized(mReceiver) {
629 if (persist) {
630 // waive WRITE_SECURE_SETTINGS permission check
631 long callingIdentity = Binder.clearCallingIdentity();
632 persistBluetoothSetting(BLUETOOTH_OFF);
633 Binder.restoreCallingIdentity(callingIdentity);
634 }
635 mEnableExternal = false;
636 sendDisableMsg();
637 }
fredc0f420372012-04-12 00:02:00 -0700638 return true;
639 }
640
fredc649fe492012-04-19 01:07:18 -0700641 public void unbindAndFinish() {
fredcf2458862012-04-16 15:18:27 -0700642 if (DBG) {
Matthew Xiecdce0b92012-07-12 19:06:15 -0700643 Log.d(TAG,"unbindAndFinish(): " + mBluetooth +
644 " mBinding = " + mBinding);
fredcf2458862012-04-16 15:18:27 -0700645 }
646
fredc0f420372012-04-12 00:02:00 -0700647 synchronized (mConnection) {
648 if (mUnbinding) return;
649 mUnbinding = true;
Zhihai Xu40874a02012-10-08 17:57:03 -0700650 if (mBluetooth != null) {
fredcbf072a72012-05-09 16:52:50 -0700651 if (!mConnection.isGetNameAddressOnly()) {
652 //Unregister callback object
653 try {
654 mBluetooth.unregisterCallback(mBluetoothCallback);
655 } catch (RemoteException re) {
Zhihai Xu40874a02012-10-08 17:57:03 -0700656 Log.e(TAG, "Unable to unregister BluetoothCallback",re);
fredcbf072a72012-05-09 16:52:50 -0700657 }
658 }
fredc0f420372012-04-12 00:02:00 -0700659 if (DBG) Log.d(TAG, "Sending unbind request.");
fredcd6883532012-04-25 17:46:13 -0700660 mBluetooth = null;
661 //Unbind
fredc0f420372012-04-12 00:02:00 -0700662 mContext.unbindService(mConnection);
fredcd6883532012-04-25 17:46:13 -0700663 mUnbinding = false;
Zhihai Xu40874a02012-10-08 17:57:03 -0700664 mBinding = false;
fredcf2458862012-04-16 15:18:27 -0700665 } else {
666 mUnbinding=false;
fredc0f420372012-04-12 00:02:00 -0700667 }
Nitin Arorad055adb2015-03-02 15:03:51 -0800668 mBluetoothGatt = null;
fredc0f420372012-04-12 00:02:00 -0700669 }
670 }
671
Matthew Xieddf7e472013-03-01 18:41:02 -0800672 public IBluetoothGatt getBluetoothGatt() {
673 // sync protection
674 return mBluetoothGatt;
675 }
676
Benjamin Franze8b98922014-11-12 15:57:54 +0000677 @Override
678 public boolean bindBluetoothProfileService(int bluetoothProfile,
679 IBluetoothProfileServiceConnection proxy) {
680 if (!mEnable) {
681 if (DBG) {
682 Log.d(TAG, "Trying to bind to profile: " + bluetoothProfile +
683 ", while Bluetooth was disabled");
684 }
685 return false;
686 }
687 synchronized (mProfileServices) {
688 ProfileServiceConnections psc = mProfileServices.get(new Integer(bluetoothProfile));
689 if (psc == null) {
690 if (DBG) {
691 Log.d(TAG, "Creating new ProfileServiceConnections object for"
692 + " profile: " + bluetoothProfile);
693 }
Benjamin Franz5b614592014-12-09 18:58:45 +0000694
695 if (bluetoothProfile != BluetoothProfile.HEADSET) return false;
696
697 Intent intent = new Intent(IBluetoothHeadset.class.getName());
Benjamin Franze8b98922014-11-12 15:57:54 +0000698 psc = new ProfileServiceConnections(intent);
Benjamin Franz5b614592014-12-09 18:58:45 +0000699 if (!psc.bindService()) return false;
700
Benjamin Franze8b98922014-11-12 15:57:54 +0000701 mProfileServices.put(new Integer(bluetoothProfile), psc);
Benjamin Franze8b98922014-11-12 15:57:54 +0000702 }
703 }
704
705 // Introducing a delay to give the client app time to prepare
706 Message addProxyMsg = mHandler.obtainMessage(MESSAGE_ADD_PROXY_DELAYED);
707 addProxyMsg.arg1 = bluetoothProfile;
708 addProxyMsg.obj = proxy;
709 mHandler.sendMessageDelayed(addProxyMsg, ADD_PROXY_DELAY_MS);
710 return true;
711 }
712
713 @Override
714 public void unbindBluetoothProfileService(int bluetoothProfile,
715 IBluetoothProfileServiceConnection proxy) {
716 synchronized (mProfileServices) {
717 ProfileServiceConnections psc = mProfileServices.get(new Integer(bluetoothProfile));
718 if (psc == null) {
719 return;
720 }
721 psc.removeProxy(proxy);
722 }
723 }
724
725 private void unbindAllBluetoothProfileServices() {
726 synchronized (mProfileServices) {
727 for (Integer i : mProfileServices.keySet()) {
728 ProfileServiceConnections psc = mProfileServices.get(i);
Benjamin Franz5b614592014-12-09 18:58:45 +0000729 try {
730 mContext.unbindService(psc);
731 } catch (IllegalArgumentException e) {
732 Log.e(TAG, "Unable to unbind service with intent: " + psc.mIntent, e);
733 }
Benjamin Franze8b98922014-11-12 15:57:54 +0000734 psc.removeAllProxies();
735 }
736 mProfileServices.clear();
737 }
738 }
739
740 /**
741 * This class manages the clients connected to a given ProfileService
742 * and maintains the connection with that service.
743 */
744 final private class ProfileServiceConnections implements ServiceConnection,
745 IBinder.DeathRecipient {
746 final RemoteCallbackList<IBluetoothProfileServiceConnection> mProxies =
747 new RemoteCallbackList <IBluetoothProfileServiceConnection>();
748 IBinder mService;
749 ComponentName mClassName;
750 Intent mIntent;
751
752 ProfileServiceConnections(Intent intent) {
753 mService = null;
754 mClassName = null;
755 mIntent = intent;
756 }
757
Benjamin Franz5b614592014-12-09 18:58:45 +0000758 private boolean bindService() {
759 if (mIntent != null && mService == null &&
760 doBind(mIntent, this, 0, UserHandle.CURRENT_OR_SELF)) {
Benjamin Franze8b98922014-11-12 15:57:54 +0000761 Message msg = mHandler.obtainMessage(MESSAGE_BIND_PROFILE_SERVICE);
762 msg.obj = this;
763 mHandler.sendMessageDelayed(msg, TIMEOUT_BIND_MS);
Benjamin Franz5b614592014-12-09 18:58:45 +0000764 return true;
Benjamin Franze8b98922014-11-12 15:57:54 +0000765 }
Benjamin Franz5b614592014-12-09 18:58:45 +0000766 Log.w(TAG, "Unable to bind with intent: " + mIntent);
767 return false;
Benjamin Franze8b98922014-11-12 15:57:54 +0000768 }
769
770 private void addProxy(IBluetoothProfileServiceConnection proxy) {
771 mProxies.register(proxy);
772 if (mService != null) {
773 try{
774 proxy.onServiceConnected(mClassName, mService);
775 } catch (RemoteException e) {
776 Log.e(TAG, "Unable to connect to proxy", e);
777 }
778 } else {
779 if (!mHandler.hasMessages(MESSAGE_BIND_PROFILE_SERVICE, this)) {
780 Message msg = mHandler.obtainMessage(MESSAGE_BIND_PROFILE_SERVICE);
781 msg.obj = this;
782 mHandler.sendMessage(msg);
783 }
784 }
785 }
786
787 private void removeProxy(IBluetoothProfileServiceConnection proxy) {
788 if (proxy != null) {
789 if (mProxies.unregister(proxy)) {
790 try {
791 proxy.onServiceDisconnected(mClassName);
792 } catch (RemoteException e) {
793 Log.e(TAG, "Unable to disconnect proxy", e);
794 }
795 }
796 } else {
797 Log.w(TAG, "Trying to remove a null proxy");
798 }
799 }
800
801 private void removeAllProxies() {
802 onServiceDisconnected(mClassName);
803 mProxies.kill();
804 }
805
806 @Override
807 public void onServiceConnected(ComponentName className, IBinder service) {
808 // remove timeout message
809 mHandler.removeMessages(MESSAGE_BIND_PROFILE_SERVICE, this);
810 mService = service;
811 mClassName = className;
812 try {
813 mService.linkToDeath(this, 0);
814 } catch (RemoteException e) {
815 Log.e(TAG, "Unable to linkToDeath", e);
816 }
817 int n = mProxies.beginBroadcast();
818 for (int i = 0; i < n; i++) {
819 try {
820 mProxies.getBroadcastItem(i).onServiceConnected(className, service);
821 } catch (RemoteException e) {
822 Log.e(TAG, "Unable to connect to proxy", e);
823 }
824 }
825 mProxies.finishBroadcast();
826 }
827
828 @Override
829 public void onServiceDisconnected(ComponentName className) {
830 if (mService == null) {
831 return;
832 }
833 mService.unlinkToDeath(this, 0);
834 mService = null;
835 mClassName = null;
836 int n = mProxies.beginBroadcast();
837 for (int i = 0; i < n; i++) {
838 try {
839 mProxies.getBroadcastItem(i).onServiceDisconnected(className);
840 } catch (RemoteException e) {
841 Log.e(TAG, "Unable to disconnect from proxy", e);
842 }
843 }
844 mProxies.finishBroadcast();
845 }
846
847 @Override
848 public void binderDied() {
849 if (DBG) {
850 Log.w(TAG, "Profile service for profile: " + mClassName
851 + " died.");
852 }
853 onServiceDisconnected(mClassName);
854 // Trigger rebind
855 Message msg = mHandler.obtainMessage(MESSAGE_BIND_PROFILE_SERVICE);
856 msg.obj = this;
857 mHandler.sendMessageDelayed(msg, TIMEOUT_BIND_MS);
858 }
859 }
860
fredcbf072a72012-05-09 16:52:50 -0700861 private void sendBluetoothStateCallback(boolean isUp) {
862 int n = mStateChangeCallbacks.beginBroadcast();
Freda8c6df02012-07-11 10:25:23 -0700863 if (DBG) Log.d(TAG,"Broadcasting onBluetoothStateChange("+isUp+") to " + n + " receivers.");
fredcbf072a72012-05-09 16:52:50 -0700864 for (int i=0; i <n;i++) {
865 try {
866 mStateChangeCallbacks.getBroadcastItem(i).onBluetoothStateChange(isUp);
867 } catch (RemoteException e) {
868 Log.e(TAG, "Unable to call onBluetoothStateChange() on callback #" + i , e);
869 }
870 }
871 mStateChangeCallbacks.finishBroadcast();
872 }
873
874 /**
Zhihai Xu40874a02012-10-08 17:57:03 -0700875 * Inform BluetoothAdapter instances that Adapter service is up
876 */
877 private void sendBluetoothServiceUpCallback() {
878 if (!mConnection.isGetNameAddressOnly()) {
879 if (DBG) Log.d(TAG,"Calling onBluetoothServiceUp callbacks");
880 int n = mCallbacks.beginBroadcast();
881 Log.d(TAG,"Broadcasting onBluetoothServiceUp() to " + n + " receivers.");
882 for (int i=0; i <n;i++) {
883 try {
884 mCallbacks.getBroadcastItem(i).onBluetoothServiceUp(mBluetooth);
885 } catch (RemoteException e) {
886 Log.e(TAG, "Unable to call onBluetoothServiceUp() on callback #" + i, e);
887 }
888 }
889 mCallbacks.finishBroadcast();
890 }
891 }
892 /**
fredcbf072a72012-05-09 16:52:50 -0700893 * Inform BluetoothAdapter instances that Adapter service is down
894 */
895 private void sendBluetoothServiceDownCallback() {
fredcd6883532012-04-25 17:46:13 -0700896 if (!mConnection.isGetNameAddressOnly()) {
897 if (DBG) Log.d(TAG,"Calling onBluetoothServiceDown callbacks");
898 int n = mCallbacks.beginBroadcast();
899 Log.d(TAG,"Broadcasting onBluetoothServiceDown() to " + n + " receivers.");
900 for (int i=0; i <n;i++) {
901 try {
902 mCallbacks.getBroadcastItem(i).onBluetoothServiceDown();
903 } catch (RemoteException e) {
904 Log.e(TAG, "Unable to call onBluetoothServiceDown() on callback #" + i, e);
905 }
906 }
907 mCallbacks.finishBroadcast();
908 }
909 }
fredc0f420372012-04-12 00:02:00 -0700910 public String getAddress() {
Matthew Xieaf5ddbf2012-12-04 10:47:43 -0800911 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
912 "Need BLUETOOTH permission");
Zhihai Xu40874a02012-10-08 17:57:03 -0700913
Zhihai Xu6eb76522012-11-29 15:41:04 -0800914 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
915 (!checkIfCallerIsForegroundUser())) {
916 Log.w(TAG,"getAddress(): not allowed for non-active and non system user");
917 return null;
Zhihai Xu40874a02012-10-08 17:57:03 -0700918 }
919
fredc116d1d462012-04-20 14:47:08 -0700920 synchronized(mConnection) {
921 if (mBluetooth != null) {
922 try {
923 return mBluetooth.getAddress();
924 } catch (RemoteException e) {
925 Log.e(TAG, "getAddress(): Unable to retrieve address remotely..Returning cached address",e);
926 }
927 }
928 }
Matthew Xiecdce0b92012-07-12 19:06:15 -0700929 // mAddress is accessed from outside.
930 // It is alright without a lock. Here, bluetooth is off, no other thread is
931 // changing mAddress
fredc0f420372012-04-12 00:02:00 -0700932 return mAddress;
933 }
fredc649fe492012-04-19 01:07:18 -0700934
fredc0f420372012-04-12 00:02:00 -0700935 public String getName() {
Matthew Xieaf5ddbf2012-12-04 10:47:43 -0800936 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
937 "Need BLUETOOTH permission");
Zhihai Xu40874a02012-10-08 17:57:03 -0700938
Zhihai Xu6eb76522012-11-29 15:41:04 -0800939 if ((Binder.getCallingUid() != Process.SYSTEM_UID) &&
940 (!checkIfCallerIsForegroundUser())) {
941 Log.w(TAG,"getName(): not allowed for non-active and non system user");
942 return null;
Zhihai Xu40874a02012-10-08 17:57:03 -0700943 }
944
fredc116d1d462012-04-20 14:47:08 -0700945 synchronized(mConnection) {
946 if (mBluetooth != null) {
947 try {
948 return mBluetooth.getName();
949 } catch (RemoteException e) {
950 Log.e(TAG, "getName(): Unable to retrieve name remotely..Returning cached name",e);
951 }
952 }
953 }
Matthew Xiecdce0b92012-07-12 19:06:15 -0700954 // mName is accessed from outside.
955 // It alright without a lock. Here, bluetooth is off, no other thread is
956 // changing mName
fredc0f420372012-04-12 00:02:00 -0700957 return mName;
958 }
959
fredc0f420372012-04-12 00:02:00 -0700960 private class BluetoothServiceConnection implements ServiceConnection {
961
962 private boolean mGetNameAddressOnly;
963
964 public void setGetNameAddressOnly(boolean getOnly) {
965 mGetNameAddressOnly = getOnly;
966 }
967
968 public boolean isGetNameAddressOnly() {
969 return mGetNameAddressOnly;
970 }
971
972 public void onServiceConnected(ComponentName className, IBinder service) {
Matthew Xieddf7e472013-03-01 18:41:02 -0800973 if (DBG) Log.d(TAG, "BluetoothServiceConnection: " + className.getClassName());
fredc0f420372012-04-12 00:02:00 -0700974 Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_SERVICE_CONNECTED);
Matthew Xieddf7e472013-03-01 18:41:02 -0800975 // TBD if (className.getClassName().equals(IBluetooth.class.getName())) {
976 if (className.getClassName().equals("com.android.bluetooth.btservice.AdapterService")) {
977 msg.arg1 = SERVICE_IBLUETOOTH;
978 // } else if (className.getClassName().equals(IBluetoothGatt.class.getName())) {
979 } else if (className.getClassName().equals("com.android.bluetooth.gatt.GattService")) {
980 msg.arg1 = SERVICE_IBLUETOOTHGATT;
981 } else {
982 Log.e(TAG, "Unknown service connected: " + className.getClassName());
983 return;
984 }
fredc0f420372012-04-12 00:02:00 -0700985 msg.obj = service;
986 mHandler.sendMessage(msg);
987 }
988
989 public void onServiceDisconnected(ComponentName className) {
fredc0f420372012-04-12 00:02:00 -0700990 // Called if we unexpected disconnected.
Matthew Xieddf7e472013-03-01 18:41:02 -0800991 if (DBG) Log.d(TAG, "BluetoothServiceConnection, disconnected: " +
992 className.getClassName());
fredc0f420372012-04-12 00:02:00 -0700993 Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED);
Matthew Xieddf7e472013-03-01 18:41:02 -0800994 if (className.getClassName().equals("com.android.bluetooth.btservice.AdapterService")) {
995 msg.arg1 = SERVICE_IBLUETOOTH;
996 } else if (className.getClassName().equals("com.android.bluetooth.gatt.GattService")) {
997 msg.arg1 = SERVICE_IBLUETOOTHGATT;
998 } else {
999 Log.e(TAG, "Unknown service disconnected: " + className.getClassName());
1000 return;
1001 }
fredc0f420372012-04-12 00:02:00 -07001002 mHandler.sendMessage(msg);
1003 }
1004 }
1005
1006 private BluetoothServiceConnection mConnection = new BluetoothServiceConnection();
1007
Zhihai Xu40874a02012-10-08 17:57:03 -07001008 private class BluetoothHandler extends Handler {
1009 public BluetoothHandler(Looper looper) {
1010 super(looper);
1011 }
1012
fredc0f420372012-04-12 00:02:00 -07001013 @Override
1014 public void handleMessage(Message msg) {
1015 if (DBG) Log.d (TAG, "Message: " + msg.what);
fredc0f420372012-04-12 00:02:00 -07001016 switch (msg.what) {
1017 case MESSAGE_GET_NAME_AND_ADDRESS: {
fredc649fe492012-04-19 01:07:18 -07001018 if (DBG) Log.d(TAG,"MESSAGE_GET_NAME_AND_ADDRESS");
Matthew Xiecdce0b92012-07-12 19:06:15 -07001019 synchronized(mConnection) {
fredc0f420372012-04-12 00:02:00 -07001020 //Start bind request
Zhihai Xu40874a02012-10-08 17:57:03 -07001021 if ((mBluetooth == null) && (!mBinding)) {
fredc0f420372012-04-12 00:02:00 -07001022 if (DBG) Log.d(TAG, "Binding to service to get name and address");
1023 mConnection.setGetNameAddressOnly(true);
1024 //Start bind timeout and bind
1025 Message timeoutMsg = mHandler.obtainMessage(MESSAGE_TIMEOUT_BIND);
1026 mHandler.sendMessageDelayed(timeoutMsg,TIMEOUT_BIND_MS);
1027 Intent i = new Intent(IBluetooth.class.getName());
Dianne Hackborn221ea892013-08-04 16:50:16 -07001028 if (!doBind(i, mConnection,
Dianne Hackbornce09f5a2014-10-10 15:03:13 -07001029 Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT,
1030 UserHandle.CURRENT)) {
fredc0f420372012-04-12 00:02:00 -07001031 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
Zhihai Xu40874a02012-10-08 17:57:03 -07001032 } else {
1033 mBinding = true;
fredc0f420372012-04-12 00:02:00 -07001034 }
1035 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001036 else {
1037 Message saveMsg= mHandler.obtainMessage(MESSAGE_SAVE_NAME_AND_ADDRESS);
Zhihai Xu40874a02012-10-08 17:57:03 -07001038 saveMsg.arg1 = 0;
1039 if (mBluetooth != null) {
1040 mHandler.sendMessage(saveMsg);
1041 } else {
1042 // if enable is also called to bind the service
1043 // wait for MESSAGE_BLUETOOTH_SERVICE_CONNECTED
1044 mHandler.sendMessageDelayed(saveMsg, TIMEOUT_SAVE_MS);
1045 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001046 }
fredc0f420372012-04-12 00:02:00 -07001047 }
fredc649fe492012-04-19 01:07:18 -07001048 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001049 }
fredc0f420372012-04-12 00:02:00 -07001050 case MESSAGE_SAVE_NAME_AND_ADDRESS: {
Zhihai Xud31c3222012-10-31 16:08:57 -07001051 boolean unbind = false;
fredc649fe492012-04-19 01:07:18 -07001052 if (DBG) Log.d(TAG,"MESSAGE_SAVE_NAME_AND_ADDRESS");
Matthew Xiecdce0b92012-07-12 19:06:15 -07001053 synchronized(mConnection) {
Zhihai Xud31c3222012-10-31 16:08:57 -07001054 if (!mEnable && mBluetooth != null) {
1055 try {
1056 mBluetooth.enable();
1057 } catch (RemoteException e) {
1058 Log.e(TAG,"Unable to call enable()",e);
1059 }
1060 }
1061 }
1062 if (mBluetooth != null) waitForOnOff(true, false);
1063 synchronized(mConnection) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001064 if (mBluetooth != null) {
1065 String name = null;
1066 String address = null;
1067 try {
1068 name = mBluetooth.getName();
1069 address = mBluetooth.getAddress();
1070 } catch (RemoteException re) {
1071 Log.e(TAG,"",re);
1072 }
fredc0f420372012-04-12 00:02:00 -07001073
Matthew Xiecdce0b92012-07-12 19:06:15 -07001074 if (name != null && address != null) {
1075 storeNameAndAddress(name,address);
Zhihai Xu40874a02012-10-08 17:57:03 -07001076 if (mConnection.isGetNameAddressOnly()) {
Zhihai Xud31c3222012-10-31 16:08:57 -07001077 unbind = true;
Zhihai Xu40874a02012-10-08 17:57:03 -07001078 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001079 } else {
1080 if (msg.arg1 < MAX_SAVE_RETRIES) {
1081 Message retryMsg = mHandler.obtainMessage(MESSAGE_SAVE_NAME_AND_ADDRESS);
1082 retryMsg.arg1= 1+msg.arg1;
1083 if (DBG) Log.d(TAG,"Retrying name/address remote retrieval and save.....Retry count =" + retryMsg.arg1);
1084 mHandler.sendMessageDelayed(retryMsg, TIMEOUT_SAVE_MS);
1085 } else {
1086 Log.w(TAG,"Maximum name/address remote retrieval retry exceeded");
Zhihai Xu40874a02012-10-08 17:57:03 -07001087 if (mConnection.isGetNameAddressOnly()) {
Zhihai Xud31c3222012-10-31 16:08:57 -07001088 unbind = true;
Zhihai Xu40874a02012-10-08 17:57:03 -07001089 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001090 }
fredc0f420372012-04-12 00:02:00 -07001091 }
Zhihai Xud31c3222012-10-31 16:08:57 -07001092 if (!mEnable) {
1093 try {
1094 mBluetooth.disable();
1095 } catch (RemoteException e) {
1096 Log.e(TAG,"Unable to call disable()",e);
1097 }
1098 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001099 } else {
1100 // rebind service by Request GET NAME AND ADDRESS
1101 // if service is unbinded by disable or
1102 // MESSAGE_BLUETOOTH_SERVICE_CONNECTED is not received
1103 Message getMsg = mHandler.obtainMessage(MESSAGE_GET_NAME_AND_ADDRESS);
1104 mHandler.sendMessage(getMsg);
fredc0f420372012-04-12 00:02:00 -07001105 }
1106 }
Zhihai Xud31c3222012-10-31 16:08:57 -07001107 if (!mEnable && mBluetooth != null) waitForOnOff(false, true);
1108 if (unbind) {
1109 unbindAndFinish();
1110 }
fredc649fe492012-04-19 01:07:18 -07001111 break;
fredc649fe492012-04-19 01:07:18 -07001112 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001113 case MESSAGE_ENABLE:
fredcf2458862012-04-16 15:18:27 -07001114 if (DBG) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001115 Log.d(TAG, "MESSAGE_ENABLE: mBluetooth = " + mBluetooth);
fredc649fe492012-04-19 01:07:18 -07001116 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001117 mHandler.removeMessages(MESSAGE_RESTART_BLUETOOTH_SERVICE);
1118 mEnable = true;
Zhihai Xu401202b2012-12-03 11:36:21 -08001119 handleEnable(msg.arg1 == 1);
fredc649fe492012-04-19 01:07:18 -07001120 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001121
fredc0f420372012-04-12 00:02:00 -07001122 case MESSAGE_DISABLE:
Zhihai Xu40874a02012-10-08 17:57:03 -07001123 mHandler.removeMessages(MESSAGE_RESTART_BLUETOOTH_SERVICE);
1124 if (mEnable && mBluetooth != null) {
1125 waitForOnOff(true, false);
1126 mEnable = false;
Zhihai Xu401202b2012-12-03 11:36:21 -08001127 handleDisable();
Zhihai Xu40874a02012-10-08 17:57:03 -07001128 waitForOnOff(false, false);
1129 } else {
1130 mEnable = false;
Zhihai Xu401202b2012-12-03 11:36:21 -08001131 handleDisable();
Zhihai Xu40874a02012-10-08 17:57:03 -07001132 }
fredc0f420372012-04-12 00:02:00 -07001133 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001134
fredc0f420372012-04-12 00:02:00 -07001135 case MESSAGE_REGISTER_ADAPTER:
1136 {
1137 IBluetoothManagerCallback callback = (IBluetoothManagerCallback) msg.obj;
fredcd6883532012-04-25 17:46:13 -07001138 boolean added = mCallbacks.register(callback);
1139 Log.d(TAG,"Added callback: " + (callback == null? "null": callback) +":" +added );
fredc0f420372012-04-12 00:02:00 -07001140 }
1141 break;
1142 case MESSAGE_UNREGISTER_ADAPTER:
1143 {
1144 IBluetoothManagerCallback callback = (IBluetoothManagerCallback) msg.obj;
fredcd6883532012-04-25 17:46:13 -07001145 boolean removed = mCallbacks.unregister(callback);
1146 Log.d(TAG,"Removed callback: " + (callback == null? "null": callback) +":" + removed);
fredc0f420372012-04-12 00:02:00 -07001147 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001148 }
fredc0f420372012-04-12 00:02:00 -07001149 case MESSAGE_REGISTER_STATE_CHANGE_CALLBACK:
1150 {
1151 IBluetoothStateChangeCallback callback = (IBluetoothStateChangeCallback) msg.obj;
Matthew Xie9b693992013-10-10 11:21:40 -07001152 if (callback != null) {
1153 mStateChangeCallbacks.register(callback);
1154 }
fredc0f420372012-04-12 00:02:00 -07001155 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001156 }
fredc0f420372012-04-12 00:02:00 -07001157 case MESSAGE_UNREGISTER_STATE_CHANGE_CALLBACK:
1158 {
1159 IBluetoothStateChangeCallback callback = (IBluetoothStateChangeCallback) msg.obj;
Matthew Xie9b693992013-10-10 11:21:40 -07001160 if (callback != null) {
1161 mStateChangeCallbacks.unregister(callback);
1162 }
fredc0f420372012-04-12 00:02:00 -07001163 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001164 }
Benjamin Franze8b98922014-11-12 15:57:54 +00001165 case MESSAGE_ADD_PROXY_DELAYED:
1166 {
1167 ProfileServiceConnections psc = mProfileServices.get(
1168 new Integer(msg.arg1));
1169 if (psc == null) {
1170 break;
1171 }
1172 IBluetoothProfileServiceConnection proxy =
1173 (IBluetoothProfileServiceConnection) msg.obj;
1174 psc.addProxy(proxy);
1175 break;
1176 }
1177 case MESSAGE_BIND_PROFILE_SERVICE:
1178 {
1179 ProfileServiceConnections psc = (ProfileServiceConnections) msg.obj;
1180 removeMessages(MESSAGE_BIND_PROFILE_SERVICE, msg.obj);
1181 if (psc == null) {
1182 break;
1183 }
1184 psc.bindService();
1185 break;
1186 }
fredc0f420372012-04-12 00:02:00 -07001187 case MESSAGE_BLUETOOTH_SERVICE_CONNECTED:
1188 {
Matthew Xieddf7e472013-03-01 18:41:02 -08001189 if (DBG) Log.d(TAG,"MESSAGE_BLUETOOTH_SERVICE_CONNECTED: " + msg.arg1);
fredc0f420372012-04-12 00:02:00 -07001190
1191 IBinder service = (IBinder) msg.obj;
1192 synchronized(mConnection) {
Matthew Xieddf7e472013-03-01 18:41:02 -08001193 if (msg.arg1 == SERVICE_IBLUETOOTHGATT) {
1194 mBluetoothGatt = IBluetoothGatt.Stub.asInterface(service);
Nitin Arorad055adb2015-03-02 15:03:51 -08001195 onBluetoothGattServiceUp();
Matthew Xieddf7e472013-03-01 18:41:02 -08001196 break;
1197 } // else must be SERVICE_IBLUETOOTH
1198
1199 //Remove timeout
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001200 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
Matthew Xieddf7e472013-03-01 18:41:02 -08001201
fredc0f420372012-04-12 00:02:00 -07001202 mBinding = false;
1203 mBluetooth = IBluetooth.Stub.asInterface(service);
fredc0f420372012-04-12 00:02:00 -07001204
Zhihai Xuaf5971e2013-06-10 20:28:31 -07001205 try {
1206 boolean enableHciSnoopLog = (Settings.Secure.getInt(mContentResolver,
1207 Settings.Secure.BLUETOOTH_HCI_LOG, 0) == 1);
1208 if (!mBluetooth.configHciSnoopLog(enableHciSnoopLog)) {
1209 Log.e(TAG,"IBluetooth.configHciSnoopLog return false");
1210 }
1211 } catch (RemoteException e) {
1212 Log.e(TAG,"Unable to call configHciSnoopLog", e);
1213 }
1214
Matthew Xiecdce0b92012-07-12 19:06:15 -07001215 if (mConnection.isGetNameAddressOnly()) {
1216 //Request GET NAME AND ADDRESS
1217 Message getMsg = mHandler.obtainMessage(MESSAGE_GET_NAME_AND_ADDRESS);
1218 mHandler.sendMessage(getMsg);
Zhihai Xu40874a02012-10-08 17:57:03 -07001219 if (!mEnable) return;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001220 }
fredc0f420372012-04-12 00:02:00 -07001221
Zhihai Xu40874a02012-10-08 17:57:03 -07001222 mConnection.setGetNameAddressOnly(false);
Matthew Xiecdce0b92012-07-12 19:06:15 -07001223 //Register callback object
fredcbf072a72012-05-09 16:52:50 -07001224 try {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001225 mBluetooth.registerCallback(mBluetoothCallback);
1226 } catch (RemoteException re) {
1227 Log.e(TAG, "Unable to register BluetoothCallback",re);
fredcbf072a72012-05-09 16:52:50 -07001228 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001229 //Inform BluetoothAdapter instances that service is up
Zhihai Xu40874a02012-10-08 17:57:03 -07001230 sendBluetoothServiceUpCallback();
1231
Matthew Xiecdce0b92012-07-12 19:06:15 -07001232 //Do enable request
1233 try {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001234 if (mQuietEnable == false) {
1235 if(!mBluetooth.enable()) {
1236 Log.e(TAG,"IBluetooth.enable() returned false");
1237 }
1238 }
1239 else
1240 {
1241 if(!mBluetooth.enableNoAutoConnect()) {
1242 Log.e(TAG,"IBluetooth.enableNoAutoConnect() returned false");
1243 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001244 }
1245 } catch (RemoteException e) {
1246 Log.e(TAG,"Unable to call enable()",e);
1247 }
Freda8c6df02012-07-11 10:25:23 -07001248 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001249
1250 if (!mEnable) {
1251 waitForOnOff(true, false);
Zhihai Xu401202b2012-12-03 11:36:21 -08001252 handleDisable();
Zhihai Xu40874a02012-10-08 17:57:03 -07001253 waitForOnOff(false, false);
1254 }
fredc649fe492012-04-19 01:07:18 -07001255 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001256 }
fredc649fe492012-04-19 01:07:18 -07001257 case MESSAGE_TIMEOUT_BIND: {
1258 Log.e(TAG, "MESSAGE_TIMEOUT_BIND");
fredc0f420372012-04-12 00:02:00 -07001259 synchronized(mConnection) {
1260 mBinding = false;
1261 }
fredc649fe492012-04-19 01:07:18 -07001262 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001263 }
fredcbf072a72012-05-09 16:52:50 -07001264 case MESSAGE_BLUETOOTH_STATE_CHANGE:
fredc0f420372012-04-12 00:02:00 -07001265 {
fredcbf072a72012-05-09 16:52:50 -07001266 int prevState = msg.arg1;
1267 int newState = msg.arg2;
1268 if (DBG) Log.d(TAG, "MESSAGE_BLUETOOTH_STATE_CHANGE: prevState = " + prevState + ", newState=" + newState);
Zhihai Xu40874a02012-10-08 17:57:03 -07001269 mState = newState;
1270 bluetoothStateChangeHandler(prevState, newState);
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001271 // handle error state transition case from TURNING_ON to OFF
1272 // unbind and rebind bluetooth service and enable bluetooth
Nitin Arorad055adb2015-03-02 15:03:51 -08001273 if ((prevState == BluetoothAdapter.STATE_BLE_TURNING_ON) &&
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001274 (newState == BluetoothAdapter.STATE_OFF) &&
1275 (mBluetooth != null) && mEnable) {
1276 recoverBluetoothServiceFromError();
1277 }
Nitin Arorad055adb2015-03-02 15:03:51 -08001278 if ((prevState == BluetoothAdapter.STATE_TURNING_ON) &&
1279 (newState == BluetoothAdapter.STATE_BLE_ON) &&
1280 (mBluetooth != null) && mEnable) {
1281 recoverBluetoothServiceFromError();
1282 }
1283 if (newState == BluetoothAdapter.STATE_ON ||
1284 newState == BluetoothAdapter.STATE_BLE_ON) {
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001285 // bluetooth is working, reset the counter
1286 if (mErrorRecoveryRetryCounter != 0) {
1287 Log.w(TAG, "bluetooth is recovered from error");
1288 mErrorRecoveryRetryCounter = 0;
1289 }
1290 }
fredc649fe492012-04-19 01:07:18 -07001291 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001292 }
fredc0f420372012-04-12 00:02:00 -07001293 case MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED:
1294 {
Matthew Xieddf7e472013-03-01 18:41:02 -08001295 Log.e(TAG, "MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED: " + msg.arg1);
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301296 synchronized(mConnection) {
Matthew Xieddf7e472013-03-01 18:41:02 -08001297 if (msg.arg1 == SERVICE_IBLUETOOTH) {
1298 // if service is unbinded already, do nothing and return
1299 if (mBluetooth == null) break;
1300 mBluetooth = null;
1301 } else if (msg.arg1 == SERVICE_IBLUETOOTHGATT) {
1302 mBluetoothGatt = null;
1303 break;
1304 } else {
1305 Log.e(TAG, "Bad msg.arg1: " + msg.arg1);
1306 break;
1307 }
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301308 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001309
1310 if (mEnable) {
1311 mEnable = false;
1312 // Send a Bluetooth Restart message
1313 Message restartMsg = mHandler.obtainMessage(
1314 MESSAGE_RESTART_BLUETOOTH_SERVICE);
1315 mHandler.sendMessageDelayed(restartMsg,
1316 SERVICE_RESTART_TIME_MS);
1317 }
1318
1319 if (!mConnection.isGetNameAddressOnly()) {
1320 sendBluetoothServiceDownCallback();
1321
1322 // Send BT state broadcast to update
1323 // the BT icon correctly
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001324 if ((mState == BluetoothAdapter.STATE_TURNING_ON) ||
1325 (mState == BluetoothAdapter.STATE_ON)) {
1326 bluetoothStateChangeHandler(BluetoothAdapter.STATE_ON,
1327 BluetoothAdapter.STATE_TURNING_OFF);
1328 mState = BluetoothAdapter.STATE_TURNING_OFF;
1329 }
1330 if (mState == BluetoothAdapter.STATE_TURNING_OFF) {
1331 bluetoothStateChangeHandler(BluetoothAdapter.STATE_TURNING_OFF,
1332 BluetoothAdapter.STATE_OFF);
1333 }
1334
1335 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
Zhihai Xu40874a02012-10-08 17:57:03 -07001336 mState = BluetoothAdapter.STATE_OFF;
1337 }
fredc649fe492012-04-19 01:07:18 -07001338 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001339 }
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301340 case MESSAGE_RESTART_BLUETOOTH_SERVICE:
1341 {
1342 Log.d(TAG, "MESSAGE_RESTART_BLUETOOTH_SERVICE:"
1343 +" Restart IBluetooth service");
1344 /* Enable without persisting the setting as
1345 it doesnt change when IBluetooth
1346 service restarts */
Zhihai Xu40874a02012-10-08 17:57:03 -07001347 mEnable = true;
Zhihai Xu401202b2012-12-03 11:36:21 -08001348 handleEnable(mQuietEnable);
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +05301349 break;
1350 }
1351
fredc0f420372012-04-12 00:02:00 -07001352 case MESSAGE_TIMEOUT_UNBIND:
1353 {
fredc649fe492012-04-19 01:07:18 -07001354 Log.e(TAG, "MESSAGE_TIMEOUT_UNBIND");
fredc0f420372012-04-12 00:02:00 -07001355 synchronized(mConnection) {
1356 mUnbinding = false;
1357 }
fredc649fe492012-04-19 01:07:18 -07001358 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001359 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001360
1361 case MESSAGE_USER_SWITCHED:
1362 {
1363 if (DBG) {
1364 Log.d(TAG, "MESSAGE_USER_SWITCHED");
1365 }
1366 mHandler.removeMessages(MESSAGE_USER_SWITCHED);
1367 /* disable and enable BT when detect a user switch */
1368 if (mEnable && mBluetooth != null) {
1369 synchronized (mConnection) {
1370 if (mBluetooth != null) {
1371 //Unregister callback object
1372 try {
1373 mBluetooth.unregisterCallback(mBluetoothCallback);
1374 } catch (RemoteException re) {
1375 Log.e(TAG, "Unable to unregister",re);
1376 }
1377 }
1378 }
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001379
1380 if (mState == BluetoothAdapter.STATE_TURNING_OFF) {
1381 // MESSAGE_USER_SWITCHED happened right after MESSAGE_ENABLE
1382 bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_OFF);
1383 mState = BluetoothAdapter.STATE_OFF;
1384 }
1385 if (mState == BluetoothAdapter.STATE_OFF) {
1386 bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_TURNING_ON);
1387 mState = BluetoothAdapter.STATE_TURNING_ON;
1388 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001389
1390 waitForOnOff(true, false);
1391
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001392 if (mState == BluetoothAdapter.STATE_TURNING_ON) {
1393 bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_ON);
1394 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001395
Benjamin Franze8b98922014-11-12 15:57:54 +00001396 unbindAllBluetoothProfileServices();
Zhihai Xu40874a02012-10-08 17:57:03 -07001397 // disable
Zhihai Xu401202b2012-12-03 11:36:21 -08001398 handleDisable();
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001399 // Pbap service need receive STATE_TURNING_OFF intent to close
1400 bluetoothStateChangeHandler(BluetoothAdapter.STATE_ON,
1401 BluetoothAdapter.STATE_TURNING_OFF);
Zhihai Xu40874a02012-10-08 17:57:03 -07001402
1403 waitForOnOff(false, true);
1404
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001405 bluetoothStateChangeHandler(BluetoothAdapter.STATE_TURNING_OFF,
Zhihai Xu40874a02012-10-08 17:57:03 -07001406 BluetoothAdapter.STATE_OFF);
Zhihai Xu40874a02012-10-08 17:57:03 -07001407 sendBluetoothServiceDownCallback();
1408 synchronized (mConnection) {
1409 if (mBluetooth != null) {
1410 mBluetooth = null;
1411 //Unbind
1412 mContext.unbindService(mConnection);
1413 }
1414 }
1415 SystemClock.sleep(100);
1416
Zhihai Xu4e22ad32012-11-13 15:11:26 -08001417 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
1418 mState = BluetoothAdapter.STATE_OFF;
Zhihai Xu40874a02012-10-08 17:57:03 -07001419 // enable
Zhihai Xu401202b2012-12-03 11:36:21 -08001420 handleEnable(mQuietEnable);
John Spurlock8a985d22014-02-25 09:40:05 -05001421 } else if (mBinding || mBluetooth != null) {
Zhihai Xu40874a02012-10-08 17:57:03 -07001422 Message userMsg = mHandler.obtainMessage(MESSAGE_USER_SWITCHED);
1423 userMsg.arg2 = 1 + msg.arg2;
1424 // if user is switched when service is being binding
1425 // delay sending MESSAGE_USER_SWITCHED
1426 mHandler.sendMessageDelayed(userMsg, USER_SWITCHED_TIME_MS);
1427 if (DBG) {
1428 Log.d(TAG, "delay MESSAGE_USER_SWITCHED " + userMsg.arg2);
1429 }
John Spurlock8a985d22014-02-25 09:40:05 -05001430 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001431 break;
1432 }
fredc0f420372012-04-12 00:02:00 -07001433 }
1434 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001435 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001436
Zhihai Xu401202b2012-12-03 11:36:21 -08001437 private void handleEnable(boolean quietMode) {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001438 mQuietEnable = quietMode;
1439
Matthew Xiecdce0b92012-07-12 19:06:15 -07001440 synchronized(mConnection) {
Zhihai Xu40874a02012-10-08 17:57:03 -07001441 if ((mBluetooth == null) && (!mBinding)) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001442 //Start bind timeout and bind
1443 Message timeoutMsg=mHandler.obtainMessage(MESSAGE_TIMEOUT_BIND);
1444 mHandler.sendMessageDelayed(timeoutMsg,TIMEOUT_BIND_MS);
1445 mConnection.setGetNameAddressOnly(false);
1446 Intent i = new Intent(IBluetooth.class.getName());
Dianne Hackbornce09f5a2014-10-10 15:03:13 -07001447 if (!doBind(i, mConnection,Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT,
1448 UserHandle.CURRENT)) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001449 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
Zhihai Xu40874a02012-10-08 17:57:03 -07001450 } else {
1451 mBinding = true;
Matthew Xiecdce0b92012-07-12 19:06:15 -07001452 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001453 } else if (mBluetooth != null) {
1454 if (mConnection.isGetNameAddressOnly()) {
1455 // if GetNameAddressOnly is set, we can clear this flag,
1456 // so the service won't be unbind
1457 // after name and address are saved
1458 mConnection.setGetNameAddressOnly(false);
1459 //Register callback object
1460 try {
1461 mBluetooth.registerCallback(mBluetoothCallback);
1462 } catch (RemoteException re) {
1463 Log.e(TAG, "Unable to register BluetoothCallback",re);
1464 }
1465 //Inform BluetoothAdapter instances that service is up
1466 sendBluetoothServiceUpCallback();
1467 }
1468
Matthew Xiecdce0b92012-07-12 19:06:15 -07001469 //Enable bluetooth
1470 try {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -07001471 if (!mQuietEnable) {
1472 if(!mBluetooth.enable()) {
1473 Log.e(TAG,"IBluetooth.enable() returned false");
1474 }
1475 }
1476 else {
1477 if(!mBluetooth.enableNoAutoConnect()) {
1478 Log.e(TAG,"IBluetooth.enableNoAutoConnect() returned false");
1479 }
Matthew Xiecdce0b92012-07-12 19:06:15 -07001480 }
1481 } catch (RemoteException e) {
1482 Log.e(TAG,"Unable to call enable()",e);
1483 }
1484 }
1485 }
1486 }
1487
Dianne Hackborn221ea892013-08-04 16:50:16 -07001488 boolean doBind(Intent intent, ServiceConnection conn, int flags, UserHandle user) {
1489 ComponentName comp = intent.resolveSystemService(mContext.getPackageManager(), 0);
1490 intent.setComponent(comp);
1491 if (comp == null || !mContext.bindServiceAsUser(intent, conn, flags, user)) {
1492 Log.e(TAG, "Fail to bind to: " + intent);
1493 return false;
1494 }
1495 return true;
1496 }
1497
Zhihai Xu401202b2012-12-03 11:36:21 -08001498 private void handleDisable() {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001499 synchronized(mConnection) {
Zhihai Xu40874a02012-10-08 17:57:03 -07001500 // don't need to disable if GetNameAddressOnly is set,
1501 // service will be unbinded after Name and Address are saved
1502 if ((mBluetooth != null) && (!mConnection.isGetNameAddressOnly())) {
Matthew Xiecdce0b92012-07-12 19:06:15 -07001503 if (DBG) Log.d(TAG,"Sending off request.");
1504
1505 try {
1506 if(!mBluetooth.disable()) {
1507 Log.e(TAG,"IBluetooth.disable() returned false");
1508 }
1509 } catch (RemoteException e) {
1510 Log.e(TAG,"Unable to call disable()",e);
1511 }
1512 }
1513 }
1514 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001515
1516 private boolean checkIfCallerIsForegroundUser() {
1517 int foregroundUser;
1518 int callingUser = UserHandle.getCallingUserId();
Martijn Coenen8385c5a2012-11-29 10:14:16 -08001519 int callingUid = Binder.getCallingUid();
Zhihai Xu40874a02012-10-08 17:57:03 -07001520 long callingIdentity = Binder.clearCallingIdentity();
Benjamin Franze8b98922014-11-12 15:57:54 +00001521 UserManager um = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
1522 UserInfo ui = um.getProfileParent(callingUser);
1523 int parentUser = (ui != null) ? ui.id : UserHandle.USER_NULL;
Martijn Coenen8385c5a2012-11-29 10:14:16 -08001524 int callingAppId = UserHandle.getAppId(callingUid);
Zhihai Xu40874a02012-10-08 17:57:03 -07001525 boolean valid = false;
1526 try {
1527 foregroundUser = ActivityManager.getCurrentUser();
Martijn Coenen8385c5a2012-11-29 10:14:16 -08001528 valid = (callingUser == foregroundUser) ||
Benjamin Franze8b98922014-11-12 15:57:54 +00001529 parentUser == foregroundUser ||
Adrian Roosbd9a9a52014-08-18 15:31:57 +02001530 callingAppId == Process.NFC_UID ||
1531 callingAppId == mSystemUiUid;
Zhihai Xu40874a02012-10-08 17:57:03 -07001532 if (DBG) {
1533 Log.d(TAG, "checkIfCallerIsForegroundUser: valid=" + valid
1534 + " callingUser=" + callingUser
Benjamin Franze8b98922014-11-12 15:57:54 +00001535 + " parentUser=" + parentUser
Zhihai Xu40874a02012-10-08 17:57:03 -07001536 + " foregroundUser=" + foregroundUser);
1537 }
1538 } finally {
1539 Binder.restoreCallingIdentity(callingIdentity);
1540 }
1541 return valid;
1542 }
1543
Nitin Arorad055adb2015-03-02 15:03:51 -08001544 private void sendBleStateChanged(int prevState, int newState) {
1545 if (DBG) Log.d(TAG,"BLE State Change Intent: " + prevState + " -> " + newState);
1546 // Send broadcast message to everyone else
1547 Intent intent = new Intent(BluetoothAdapter.ACTION_BLE_STATE_CHANGED);
1548 intent.putExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE, prevState);
1549 intent.putExtra(BluetoothAdapter.EXTRA_STATE, newState);
1550 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1551 mContext.sendBroadcastAsUser(intent, UserHandle.ALL, BLUETOOTH_PERM);
1552 }
1553
Zhihai Xu40874a02012-10-08 17:57:03 -07001554 private void bluetoothStateChangeHandler(int prevState, int newState) {
Nitin Arorad055adb2015-03-02 15:03:51 -08001555 boolean isStandardBroadcast = true;
Zhihai Xu40874a02012-10-08 17:57:03 -07001556 if (prevState != newState) {
1557 //Notify all proxy objects first of adapter state change
Nitin Arorad055adb2015-03-02 15:03:51 -08001558 if (newState == BluetoothAdapter.STATE_BLE_ON
1559 || newState == BluetoothAdapter.STATE_OFF) {
1560 boolean intermediate_off = (prevState == BluetoothAdapter.STATE_TURNING_OFF
1561 && newState == BluetoothAdapter.STATE_BLE_ON);
Zhihai Xu40874a02012-10-08 17:57:03 -07001562
Nitin Arorad055adb2015-03-02 15:03:51 -08001563 if (newState == BluetoothAdapter.STATE_OFF) {
1564 // If Bluetooth is off, send service down event to proxy objects, and unbind
1565 if (DBG) Log.d(TAG, "Bluetooth is complete turn off");
1566 if (canUnbindBluetoothService()) {
1567 if (DBG) Log.d(TAG, "Good to unbind!");
Matthew Xieddf7e472013-03-01 18:41:02 -08001568 sendBluetoothServiceDownCallback();
1569 unbindAndFinish();
Nitin Arorad055adb2015-03-02 15:03:51 -08001570 sendBleStateChanged(prevState, newState);
1571 // Don't broadcast as it has already been broadcast before
1572 isStandardBroadcast = false;
Matthew Xieddf7e472013-03-01 18:41:02 -08001573 }
Nitin Arorad055adb2015-03-02 15:03:51 -08001574
1575 } else if (!intermediate_off) {
1576 // connect to GattService
1577 if (DBG) Log.d(TAG, "Bluetooth is in LE only mode");
1578 if (mBluetoothGatt != null) {
1579 if (DBG) Log.d(TAG, "Calling BluetoothGattServiceUp");
1580 onBluetoothGattServiceUp();
1581 } else {
1582 if (DBG) Log.d(TAG, "Binding Bluetooth GATT service");
1583 if (mContext.getPackageManager().hasSystemFeature(
1584 PackageManager.FEATURE_BLUETOOTH_LE)) {
1585 Intent i = new Intent(IBluetoothGatt.class.getName());
1586 doBind(i, mConnection, Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT, UserHandle.CURRENT);
1587 }
1588 }
1589 sendBleStateChanged(prevState, newState);
1590 //Don't broadcase this as std intent
1591 isStandardBroadcast = false;
1592
1593 } else if (intermediate_off){
1594 if (DBG) Log.d(TAG, "Intermediate off, back to LE only mode");
1595 // For LE only mode, broadcast as is
1596 sendBleStateChanged(prevState, newState);
1597 sendBluetoothStateCallback(false); // BT is OFF for general users
1598 // Broadcast as STATE_OFF
1599 newState = BluetoothAdapter.STATE_OFF;
1600 sendBrEdrDownCallback();
Zhihai Xu40874a02012-10-08 17:57:03 -07001601 }
Nitin Arorad055adb2015-03-02 15:03:51 -08001602 } else if (newState == BluetoothAdapter.STATE_ON) {
1603 boolean isUp = (newState==BluetoothAdapter.STATE_ON);
1604 sendBluetoothStateCallback(isUp);
1605 sendBleStateChanged(prevState, newState);
1606
1607 } else if (newState == BluetoothAdapter.STATE_BLE_TURNING_ON
1608 || newState == BluetoothAdapter.STATE_BLE_TURNING_OFF ) {
1609 sendBleStateChanged(prevState, newState);
1610 isStandardBroadcast = false;
1611
1612 } else if (newState == BluetoothAdapter.STATE_TURNING_ON
1613 || newState == BluetoothAdapter.STATE_TURNING_OFF) {
1614 sendBleStateChanged(prevState, newState);
Zhihai Xu40874a02012-10-08 17:57:03 -07001615 }
1616
Nitin Arorad055adb2015-03-02 15:03:51 -08001617 if (isStandardBroadcast) {
1618 if (prevState == BluetoothAdapter.STATE_BLE_ON) {
1619 // Show prevState of BLE_ON as OFF to standard users
1620 prevState = BluetoothAdapter.STATE_OFF;
1621 }
1622 Intent intent = new Intent(BluetoothAdapter.ACTION_STATE_CHANGED);
1623 intent.putExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE, prevState);
1624 intent.putExtra(BluetoothAdapter.EXTRA_STATE, newState);
1625 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1626 mContext.sendBroadcastAsUser(intent, UserHandle.ALL, BLUETOOTH_PERM);
1627 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001628 }
1629 }
1630
1631 /**
1632 * if on is true, wait for state become ON
1633 * if off is true, wait for state become OFF
1634 * if both on and off are false, wait for state not ON
1635 */
1636 private boolean waitForOnOff(boolean on, boolean off) {
1637 int i = 0;
1638 while (i < 10) {
1639 synchronized(mConnection) {
1640 try {
1641 if (mBluetooth == null) break;
1642 if (on) {
1643 if (mBluetooth.getState() == BluetoothAdapter.STATE_ON) return true;
1644 } else if (off) {
1645 if (mBluetooth.getState() == BluetoothAdapter.STATE_OFF) return true;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07001646 } else {
Zhihai Xu40874a02012-10-08 17:57:03 -07001647 if (mBluetooth.getState() != BluetoothAdapter.STATE_ON) return true;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07001648 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001649 } catch (RemoteException e) {
1650 Log.e(TAG, "getState()", e);
1651 break;
1652 }
1653 }
1654 if (on || off) {
1655 SystemClock.sleep(300);
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07001656 } else {
Zhihai Xu40874a02012-10-08 17:57:03 -07001657 SystemClock.sleep(50);
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07001658 }
Zhihai Xu40874a02012-10-08 17:57:03 -07001659 i++;
1660 }
1661 Log.e(TAG,"waitForOnOff time out");
1662 return false;
1663 }
Zhihai Xu681ae7f2012-11-12 15:14:18 -08001664
Zhihai Xu401202b2012-12-03 11:36:21 -08001665 private void sendDisableMsg() {
1666 mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_DISABLE));
1667 }
1668
1669 private void sendEnableMsg(boolean quietMode) {
1670 mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_ENABLE,
1671 quietMode ? 1 : 0, 0));
1672 }
1673
Zhihai Xu681ae7f2012-11-12 15:14:18 -08001674 private boolean canUnbindBluetoothService() {
1675 synchronized(mConnection) {
1676 //Only unbind with mEnable flag not set
1677 //For race condition: disable and enable back-to-back
1678 //Avoid unbind right after enable due to callback from disable
1679 //Only unbind with Bluetooth at OFF state
1680 //Only unbind without any MESSAGE_BLUETOOTH_STATE_CHANGE message
1681 try {
1682 if (mEnable || (mBluetooth == null)) return false;
1683 if (mHandler.hasMessages(MESSAGE_BLUETOOTH_STATE_CHANGE)) return false;
1684 return (mBluetooth.getState() == BluetoothAdapter.STATE_OFF);
1685 } catch (RemoteException e) {
1686 Log.e(TAG, "getState()", e);
1687 }
1688 }
1689 return false;
1690 }
Zhihai Xudd9d17d2013-01-08 17:05:58 -08001691
1692 private void recoverBluetoothServiceFromError() {
1693 Log.e(TAG,"recoverBluetoothServiceFromError");
1694 synchronized (mConnection) {
1695 if (mBluetooth != null) {
1696 //Unregister callback object
1697 try {
1698 mBluetooth.unregisterCallback(mBluetoothCallback);
1699 } catch (RemoteException re) {
1700 Log.e(TAG, "Unable to unregister",re);
1701 }
1702 }
1703 }
1704
1705 SystemClock.sleep(500);
1706
1707 // disable
1708 handleDisable();
1709
1710 waitForOnOff(false, true);
1711
1712 sendBluetoothServiceDownCallback();
1713 synchronized (mConnection) {
1714 if (mBluetooth != null) {
1715 mBluetooth = null;
1716 //Unbind
1717 mContext.unbindService(mConnection);
1718 }
1719 }
1720
1721 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
1722 mState = BluetoothAdapter.STATE_OFF;
1723
1724 mEnable = false;
1725
1726 if (mErrorRecoveryRetryCounter++ < MAX_ERROR_RESTART_RETRIES) {
1727 // Send a Bluetooth Restart message to reenable bluetooth
1728 Message restartMsg = mHandler.obtainMessage(
1729 MESSAGE_RESTART_BLUETOOTH_SERVICE);
1730 mHandler.sendMessageDelayed(restartMsg, ERROR_RESTART_TIME_MS);
1731 } else {
1732 // todo: notify user to power down and power up phone to make bluetooth work.
1733 }
1734 }
Mike Lockwood726d4de2014-10-28 14:06:28 -07001735
1736 @Override
1737 public void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Mike Lockwood75b52bb2014-12-18 14:16:36 -08001738 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DUMP, TAG);
1739
Mike Lockwood726d4de2014-10-28 14:06:28 -07001740 writer.println("enabled: " + mEnable);
1741 writer.println("state: " + mState);
1742 writer.println("address: " + mAddress);
1743 writer.println("name: " + mName);
1744 if (mBluetooth == null) {
1745 writer.println("Bluetooth Service not connected");
1746 } else {
1747 try {
1748 writer.println(mBluetooth.dump());
1749 } catch (RemoteException re) {
1750 writer.println("RemoteException while calling Bluetooth Service");
1751 }
1752 }
1753 }
fredc0f420372012-04-12 00:02:00 -07001754}