blob: beb22153010dee2cd0d228e8334fab35989e6940 [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;
21import android.bluetooth.IBluetooth;
fredcbf072a72012-05-09 16:52:50 -070022import android.bluetooth.IBluetoothCallback;
fredc0f420372012-04-12 00:02:00 -070023import android.bluetooth.IBluetoothManager;
24import android.bluetooth.IBluetoothManagerCallback;
25import android.bluetooth.IBluetoothStateChangeCallback;
fredc0f420372012-04-12 00:02:00 -070026import android.content.BroadcastReceiver;
27import android.content.ComponentName;
28import android.content.ContentResolver;
29import android.content.Context;
30import android.content.Intent;
31import android.content.IntentFilter;
32import android.content.ServiceConnection;
Zhihai Xu40874a02012-10-08 17:57:03 -070033import android.os.Binder;
fredc0f420372012-04-12 00:02:00 -070034import android.os.Handler;
Zhihai Xu40874a02012-10-08 17:57:03 -070035import android.os.HandlerThread;
fredc0f420372012-04-12 00:02:00 -070036import android.os.IBinder;
Zhihai Xu40874a02012-10-08 17:57:03 -070037import android.os.Looper;
fredc0f420372012-04-12 00:02:00 -070038import android.os.Message;
Zhihai Xu40874a02012-10-08 17:57:03 -070039import android.os.Process;
fredcd6883532012-04-25 17:46:13 -070040import android.os.RemoteCallbackList;
fredc0f420372012-04-12 00:02:00 -070041import android.os.RemoteException;
Zhihai Xu40874a02012-10-08 17:57:03 -070042import android.os.SystemClock;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070043import android.os.UserHandle;
fredc0f420372012-04-12 00:02:00 -070044import android.provider.Settings;
45import android.util.Log;
fredc0f420372012-04-12 00:02:00 -070046class BluetoothManagerService extends IBluetoothManager.Stub {
47 private static final String TAG = "BluetoothManagerService";
48 private static final boolean DBG = true;
49
fredc0f420372012-04-12 00:02:00 -070050 private static final String BLUETOOTH_ADMIN_PERM = android.Manifest.permission.BLUETOOTH_ADMIN;
51 private static final String BLUETOOTH_PERM = android.Manifest.permission.BLUETOOTH;
fredc0f420372012-04-12 00:02:00 -070052 private static final String ACTION_SERVICE_STATE_CHANGED="com.android.bluetooth.btservice.action.STATE_CHANGED";
53 private static final String EXTRA_ACTION="action";
Zhihai Xud31c3222012-10-31 16:08:57 -070054 private static final String SECURE_SETTINGS_BLUETOOTH_ADDR_VALID="bluetooth_addr_valid";
fredc0f420372012-04-12 00:02:00 -070055 private static final String SECURE_SETTINGS_BLUETOOTH_ADDRESS="bluetooth_address";
56 private static final String SECURE_SETTINGS_BLUETOOTH_NAME="bluetooth_name";
fredc0f420372012-04-12 00:02:00 -070057 private static final int TIMEOUT_BIND_MS = 3000; //Maximum msec to wait for a bind
58 private static final int TIMEOUT_SAVE_MS = 500; //Maximum msec to wait for a save
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +053059 //Maximum msec to wait for service restart
60 private static final int SERVICE_RESTART_TIME_MS = 200;
Zhihai Xu40874a02012-10-08 17:57:03 -070061 //Maximum msec to delay MESSAGE_USER_SWITCHED
62 private static final int USER_SWITCHED_TIME_MS = 200;
fredc0f420372012-04-12 00:02:00 -070063
64 private static final int MESSAGE_ENABLE = 1;
65 private static final int MESSAGE_DISABLE = 2;
fredc649fe492012-04-19 01:07:18 -070066 private static final int MESSAGE_REGISTER_ADAPTER = 20;
67 private static final int MESSAGE_UNREGISTER_ADAPTER = 21;
68 private static final int MESSAGE_REGISTER_STATE_CHANGE_CALLBACK = 30;
69 private static final int MESSAGE_UNREGISTER_STATE_CHANGE_CALLBACK = 31;
70 private static final int MESSAGE_BLUETOOTH_SERVICE_CONNECTED = 40;
71 private static final int MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED = 41;
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +053072 private static final int MESSAGE_RESTART_BLUETOOTH_SERVICE = 42;
fredcbf072a72012-05-09 16:52:50 -070073 private static final int MESSAGE_BLUETOOTH_STATE_CHANGE=60;
fredc0f420372012-04-12 00:02:00 -070074 private static final int MESSAGE_TIMEOUT_BIND =100;
75 private static final int MESSAGE_TIMEOUT_UNBIND =101;
76 private static final int MESSAGE_GET_NAME_AND_ADDRESS=200;
77 private static final int MESSAGE_SAVE_NAME_AND_ADDRESS=201;
Zhihai Xu40874a02012-10-08 17:57:03 -070078 private static final int MESSAGE_USER_SWITCHED = 300;
fredc0f420372012-04-12 00:02:00 -070079 private static final int MAX_SAVE_RETRIES=3;
80
81 private final Context mContext;
Matthew Xiecdce0b92012-07-12 19:06:15 -070082
83 // Locks are not provided for mName and mAddress.
84 // They are accessed in handler or broadcast receiver, same thread context.
fredc0f420372012-04-12 00:02:00 -070085 private String mAddress;
86 private String mName;
Matthew Xie6fde3092012-07-11 17:10:07 -070087 private final ContentResolver mContentResolver;
88 private final RemoteCallbackList<IBluetoothManagerCallback> mCallbacks;
89 private final RemoteCallbackList<IBluetoothStateChangeCallback> mStateChangeCallbacks;
fredc649fe492012-04-19 01:07:18 -070090 private IBluetooth mBluetooth;
91 private boolean mBinding;
92 private boolean mUnbinding;
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -070093 private boolean mQuietEnable = false;
Zhihai Xu40874a02012-10-08 17:57:03 -070094 private boolean mEnable;
95 private int mState;
96 private HandlerThread mThread;
97 private final BluetoothHandler mHandler;
fredc0f420372012-04-12 00:02:00 -070098
fredc649fe492012-04-19 01:07:18 -070099 private void registerForAirplaneMode(IntentFilter filter) {
100 final ContentResolver resolver = mContext.getContentResolver();
Christopher Tatec09cdce2012-09-10 16:50:14 -0700101 final String airplaneModeRadios = Settings.Global.getString(resolver,
102 Settings.Global.AIRPLANE_MODE_RADIOS);
103 final String toggleableRadios = Settings.Global.getString(resolver,
104 Settings.Global.AIRPLANE_MODE_TOGGLEABLE_RADIOS);
fredc649fe492012-04-19 01:07:18 -0700105 boolean mIsAirplaneSensitive = airplaneModeRadios == null ? true :
Christopher Tatec09cdce2012-09-10 16:50:14 -0700106 airplaneModeRadios.contains(Settings.Global.RADIO_BLUETOOTH);
fredc649fe492012-04-19 01:07:18 -0700107 if (mIsAirplaneSensitive) {
108 filter.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED);
109 }
110 }
111
fredcbf072a72012-05-09 16:52:50 -0700112 private final IBluetoothCallback mBluetoothCallback = new IBluetoothCallback.Stub() {
113 @Override
114 public void onBluetoothStateChange(int prevState, int newState) throws RemoteException {
115 Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_STATE_CHANGE,prevState,newState);
116 mHandler.sendMessage(msg);
117 }
118 };
119
120 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
fredc0f420372012-04-12 00:02:00 -0700121 @Override
122 public void onReceive(Context context, Intent intent) {
123 String action = intent.getAction();
fredcbf072a72012-05-09 16:52:50 -0700124 if (BluetoothAdapter.ACTION_LOCAL_NAME_CHANGED.equals(action)) {
fredc0f420372012-04-12 00:02:00 -0700125 String newName = intent.getStringExtra(BluetoothAdapter.EXTRA_LOCAL_NAME);
Freda8c6df02012-07-11 10:25:23 -0700126 if (DBG) Log.d(TAG, "Bluetooth Adapter name changed to " + newName);
fredc0f420372012-04-12 00:02:00 -0700127 if (newName != null) {
128 storeNameAndAddress(newName, null);
129 }
fredc649fe492012-04-19 01:07:18 -0700130 } else if (Intent.ACTION_AIRPLANE_MODE_CHANGED.equals(action)) {
131 if (isAirplaneModeOn()) {
Zhihai Xu40874a02012-10-08 17:57:03 -0700132 // disable without persisting the setting
133 mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_DISABLE,
134 0, 0));
135 } else if (isBluetoothPersistedStateOn()) {
136 // enable without persisting the setting
137 mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_ENABLE,
138 0, 0));
fredc649fe492012-04-19 01:07:18 -0700139 }
Zhihai Xu40874a02012-10-08 17:57:03 -0700140 } else if (Intent.ACTION_USER_SWITCHED.equals(action)) {
141 mHandler.sendMessage(mHandler.obtainMessage(MESSAGE_USER_SWITCHED,
142 intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0), 0));
fredc0f420372012-04-12 00:02:00 -0700143 }
144 }
145 };
146
147 BluetoothManagerService(Context context) {
Zhihai Xu40874a02012-10-08 17:57:03 -0700148 mThread = new HandlerThread("BluetoothManager");
149 mThread.start();
150 mHandler = new BluetoothHandler(mThread.getLooper());
151
fredc0f420372012-04-12 00:02:00 -0700152 mContext = context;
153 mBluetooth = null;
154 mBinding = false;
155 mUnbinding = false;
Zhihai Xu40874a02012-10-08 17:57:03 -0700156 mEnable = false;
157 mState = BluetoothAdapter.STATE_OFF;
fredc0f420372012-04-12 00:02:00 -0700158 mAddress = null;
159 mName = null;
160 mContentResolver = context.getContentResolver();
fredcd6883532012-04-25 17:46:13 -0700161 mCallbacks = new RemoteCallbackList<IBluetoothManagerCallback>();
162 mStateChangeCallbacks = new RemoteCallbackList<IBluetoothStateChangeCallback>();
Matthew Xie6fde3092012-07-11 17:10:07 -0700163 IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
164 filter.addAction(BluetoothAdapter.ACTION_LOCAL_NAME_CHANGED);
Zhihai Xu40874a02012-10-08 17:57:03 -0700165 filter.addAction(Intent.ACTION_USER_SWITCHED);
Matthew Xie6fde3092012-07-11 17:10:07 -0700166 registerForAirplaneMode(filter);
167 mContext.registerReceiver(mReceiver, filter);
fredc649fe492012-04-19 01:07:18 -0700168 boolean airplaneModeOn = isAirplaneModeOn();
169 boolean bluetoothOn = isBluetoothPersistedStateOn();
fredc0f420372012-04-12 00:02:00 -0700170 loadStoredNameAndAddress();
fredc649fe492012-04-19 01:07:18 -0700171 if (DBG) Log.d(TAG, "airplaneModeOn: " + airplaneModeOn + " bluetoothOn: " + bluetoothOn);
Andre Eisenbacha732ffd2012-05-02 00:39:24 -0700172 if (bluetoothOn) {
fredc0f420372012-04-12 00:02:00 -0700173 //Enable
fredc649fe492012-04-19 01:07:18 -0700174 if (DBG) Log.d(TAG, "Auto-enabling Bluetooth.");
Zhihai Xu40874a02012-10-08 17:57:03 -0700175 enableHelper();
Zhihai Xud31c3222012-10-31 16:08:57 -0700176 }
177
178 if (!isNameAndAddressSet()) {
fredc649fe492012-04-19 01:07:18 -0700179 //Sync the Bluetooth name and address from the Bluetooth Adapter
180 if (DBG) Log.d(TAG,"Retrieving Bluetooth Adapter name and address...");
fredc0f420372012-04-12 00:02:00 -0700181 getNameAndAddress();
182 }
183 }
184
fredc649fe492012-04-19 01:07:18 -0700185 /**
186 * Returns true if airplane mode is currently on
187 */
188 private final boolean isAirplaneModeOn() {
Christopher Tatec09cdce2012-09-10 16:50:14 -0700189 return Settings.Global.getInt(mContext.getContentResolver(),
190 Settings.Global.AIRPLANE_MODE_ON, 0) == 1;
fredc649fe492012-04-19 01:07:18 -0700191 }
192
193 /**
194 * Returns true if the Bluetooth saved state is "on"
195 */
196 private final boolean isBluetoothPersistedStateOn() {
Jeff Brownbf6f6f92012-09-25 15:03:20 -0700197 return Settings.Global.getInt(mContentResolver,
198 Settings.Global.BLUETOOTH_ON, 0) ==1;
fredc649fe492012-04-19 01:07:18 -0700199 }
200
201 /**
202 * Save the Bluetooth on/off state
203 *
204 */
205 private void persistBluetoothSetting(boolean setOn) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -0700206 Settings.Global.putInt(mContext.getContentResolver(),
207 Settings.Global.BLUETOOTH_ON,
fredc649fe492012-04-19 01:07:18 -0700208 setOn ? 1 : 0);
209 }
210
211 /**
212 * Returns true if the Bluetooth Adapter's name and address is
213 * locally cached
214 * @return
215 */
fredc0f420372012-04-12 00:02:00 -0700216 private boolean isNameAndAddressSet() {
217 return mName !=null && mAddress!= null && mName.length()>0 && mAddress.length()>0;
218 }
219
fredc649fe492012-04-19 01:07:18 -0700220 /**
221 * Retrieve the Bluetooth Adapter's name and address and save it in
222 * in the local cache
223 */
fredc0f420372012-04-12 00:02:00 -0700224 private void loadStoredNameAndAddress() {
225 if (DBG) Log.d(TAG, "Loading stored name and address");
Zhihai Xud31c3222012-10-31 16:08:57 -0700226 if (mContext.getResources().getBoolean
227 (com.android.internal.R.bool.config_bluetooth_address_validation) &&
228 Settings.Secure.getInt(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDR_VALID, 0) == 0) {
229 // if the valid flag is not set, don't load the address and name
230 if (DBG) Log.d(TAG, "invalid bluetooth name and address stored");
231 return;
232 }
fredc0f420372012-04-12 00:02:00 -0700233 mName = Settings.Secure.getString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_NAME);
234 mAddress = Settings.Secure.getString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDRESS);
Zhihai Xud31c3222012-10-31 16:08:57 -0700235 if (DBG) Log.d(TAG, "Stored bluetooth Name=" + mName + ",Address=" + mAddress);
fredc0f420372012-04-12 00:02:00 -0700236 }
237
fredc649fe492012-04-19 01:07:18 -0700238 /**
239 * Save the Bluetooth name and address in the persistent store.
240 * Only non-null values will be saved.
241 * @param name
242 * @param address
243 */
fredc0f420372012-04-12 00:02:00 -0700244 private void storeNameAndAddress(String name, String address) {
245 if (name != null) {
246 Settings.Secure.putString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_NAME, name);
fredc0f420372012-04-12 00:02:00 -0700247 mName = name;
fredc649fe492012-04-19 01:07:18 -0700248 if (DBG) Log.d(TAG,"Stored Bluetooth name: " +
249 Settings.Secure.getString(mContentResolver,SECURE_SETTINGS_BLUETOOTH_NAME));
fredc0f420372012-04-12 00:02:00 -0700250 }
251
252 if (address != null) {
253 Settings.Secure.putString(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDRESS, address);
fredc0f420372012-04-12 00:02:00 -0700254 mAddress=address;
fredc649fe492012-04-19 01:07:18 -0700255 if (DBG) Log.d(TAG,"Stored Bluetoothaddress: " +
256 Settings.Secure.getString(mContentResolver,SECURE_SETTINGS_BLUETOOTH_ADDRESS));
fredc0f420372012-04-12 00:02:00 -0700257 }
Zhihai Xud31c3222012-10-31 16:08:57 -0700258
259 if ((name != null) && (address != null)) {
260 Settings.Secure.putInt(mContentResolver, SECURE_SETTINGS_BLUETOOTH_ADDR_VALID, 1);
261 }
fredc0f420372012-04-12 00:02:00 -0700262 }
263
264 public IBluetooth registerAdapter(IBluetoothManagerCallback callback){
fredc0f420372012-04-12 00:02:00 -0700265 Message msg = mHandler.obtainMessage(MESSAGE_REGISTER_ADAPTER);
266 msg.obj = callback;
267 mHandler.sendMessage(msg);
268 synchronized(mConnection) {
269 return mBluetooth;
270 }
271 }
272
273 public void unregisterAdapter(IBluetoothManagerCallback callback) {
274 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
275 "Need BLUETOOTH permission");
276 Message msg = mHandler.obtainMessage(MESSAGE_UNREGISTER_ADAPTER);
277 msg.obj = callback;
278 mHandler.sendMessage(msg);
279 }
280
281 public void registerStateChangeCallback(IBluetoothStateChangeCallback callback) {
282 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
283 "Need BLUETOOTH permission");
284 Message msg = mHandler.obtainMessage(MESSAGE_REGISTER_STATE_CHANGE_CALLBACK);
285 msg.obj = callback;
286 mHandler.sendMessage(msg);
287 }
288
289 public void unregisterStateChangeCallback(IBluetoothStateChangeCallback callback) {
290 mContext.enforceCallingOrSelfPermission(BLUETOOTH_PERM,
291 "Need BLUETOOTH permission");
292 Message msg = mHandler.obtainMessage(MESSAGE_UNREGISTER_STATE_CHANGE_CALLBACK);
293 msg.obj = callback;
294 mHandler.sendMessage(msg);
295 }
296
297 public boolean isEnabled() {
Zhihai Xu40874a02012-10-08 17:57:03 -0700298 if (!checkIfCallerIsForegroundUser()) {
299 Log.w(TAG,"isEnabled(): not allowed for non-active user");
300 return false;
301 }
302
fredc0f420372012-04-12 00:02:00 -0700303 synchronized(mConnection) {
304 try {
305 return (mBluetooth != null && mBluetooth.isEnabled());
306 } catch (RemoteException e) {
307 Log.e(TAG, "isEnabled()", e);
308 }
309 }
310 return false;
311 }
312
313 public void getNameAndAddress() {
fredcf2458862012-04-16 15:18:27 -0700314 if (DBG) {
Matthew Xiecdce0b92012-07-12 19:06:15 -0700315 Log.d(TAG,"getNameAndAddress(): mBluetooth = " + mBluetooth +
316 " mBinding = " + mBinding);
fredcf2458862012-04-16 15:18:27 -0700317 }
fredc0f420372012-04-12 00:02:00 -0700318 Message msg = mHandler.obtainMessage(MESSAGE_GET_NAME_AND_ADDRESS);
319 mHandler.sendMessage(msg);
320 }
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700321 public boolean enableNoAutoConnect()
322 {
323 mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
324 "Need BLUETOOTH ADMIN permission");
Zhihai Xu40874a02012-10-08 17:57:03 -0700325
326 if (!checkIfCallerIsForegroundUser()) {
327 Log.w(TAG,"enableNoAutoConnect(): not allowed for non-active user");
328 return false;
329 }
330
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700331 if (DBG) {
332 Log.d(TAG,"enableNoAutoConnect(): mBluetooth =" + mBluetooth +
333 " mBinding = " + mBinding);
334 }
Martijn Coenen8385c5a2012-11-29 10:14:16 -0800335 int callingAppId = UserHandle.getAppId(Binder.getCallingUid());
336
337 if (callingAppId != Process.NFC_UID) {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700338 throw new SecurityException("no permission to enable Bluetooth quietly");
339 }
Martijn Coenen8385c5a2012-11-29 10:14:16 -0800340
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700341 Message msg = mHandler.obtainMessage(MESSAGE_ENABLE);
342 msg.arg1=0; //No persist
343 msg.arg2=1; //Quiet mode
344 mHandler.sendMessage(msg);
345 return true;
346
347 }
fredc0f420372012-04-12 00:02:00 -0700348 public boolean enable() {
Zhihai Xu40874a02012-10-08 17:57:03 -0700349 if (!checkIfCallerIsForegroundUser()) {
350 Log.w(TAG,"enable(): not allowed for non-active user");
351 return false;
fredcf2458862012-04-16 15:18:27 -0700352 }
353
Zhihai Xu40874a02012-10-08 17:57:03 -0700354 return enableHelper();
fredc0f420372012-04-12 00:02:00 -0700355 }
356
357 public boolean disable(boolean persist) {
358 mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
359 "Need BLUETOOTH ADMIN permissicacheNameAndAddresson");
Zhihai Xu40874a02012-10-08 17:57:03 -0700360
361 if (!checkIfCallerIsForegroundUser()) {
362 Log.w(TAG,"disable(): not allowed for non-active user");
363 return false;
364 }
365
fredcf2458862012-04-16 15:18:27 -0700366 if (DBG) {
Matthew Xiecdce0b92012-07-12 19:06:15 -0700367 Log.d(TAG,"disable(): mBluetooth = " + mBluetooth +
368 " mBinding = " + mBinding);
369 }
fredcf2458862012-04-16 15:18:27 -0700370
fredc0f420372012-04-12 00:02:00 -0700371 Message msg = mHandler.obtainMessage(MESSAGE_DISABLE);
fredc649fe492012-04-19 01:07:18 -0700372 msg.arg1=(persist?1:0);
fredc0f420372012-04-12 00:02:00 -0700373 mHandler.sendMessage(msg);
374 return true;
375 }
376
fredc649fe492012-04-19 01:07:18 -0700377 public void unbindAndFinish() {
fredcf2458862012-04-16 15:18:27 -0700378 if (DBG) {
Matthew Xiecdce0b92012-07-12 19:06:15 -0700379 Log.d(TAG,"unbindAndFinish(): " + mBluetooth +
380 " mBinding = " + mBinding);
fredcf2458862012-04-16 15:18:27 -0700381 }
382
fredc0f420372012-04-12 00:02:00 -0700383 synchronized (mConnection) {
384 if (mUnbinding) return;
385 mUnbinding = true;
Zhihai Xu40874a02012-10-08 17:57:03 -0700386 if (mBluetooth != null) {
fredcbf072a72012-05-09 16:52:50 -0700387 if (!mConnection.isGetNameAddressOnly()) {
388 //Unregister callback object
389 try {
390 mBluetooth.unregisterCallback(mBluetoothCallback);
391 } catch (RemoteException re) {
Zhihai Xu40874a02012-10-08 17:57:03 -0700392 Log.e(TAG, "Unable to unregister BluetoothCallback",re);
fredcbf072a72012-05-09 16:52:50 -0700393 }
394 }
fredc0f420372012-04-12 00:02:00 -0700395 if (DBG) Log.d(TAG, "Sending unbind request.");
fredcd6883532012-04-25 17:46:13 -0700396 mBluetooth = null;
397 //Unbind
fredc0f420372012-04-12 00:02:00 -0700398 mContext.unbindService(mConnection);
fredcd6883532012-04-25 17:46:13 -0700399 mUnbinding = false;
Zhihai Xu40874a02012-10-08 17:57:03 -0700400 mBinding = false;
fredcf2458862012-04-16 15:18:27 -0700401 } else {
402 mUnbinding=false;
fredc0f420372012-04-12 00:02:00 -0700403 }
404 }
405 }
406
fredcbf072a72012-05-09 16:52:50 -0700407 private void sendBluetoothStateCallback(boolean isUp) {
408 int n = mStateChangeCallbacks.beginBroadcast();
Freda8c6df02012-07-11 10:25:23 -0700409 if (DBG) Log.d(TAG,"Broadcasting onBluetoothStateChange("+isUp+") to " + n + " receivers.");
fredcbf072a72012-05-09 16:52:50 -0700410 for (int i=0; i <n;i++) {
411 try {
412 mStateChangeCallbacks.getBroadcastItem(i).onBluetoothStateChange(isUp);
413 } catch (RemoteException e) {
414 Log.e(TAG, "Unable to call onBluetoothStateChange() on callback #" + i , e);
415 }
416 }
417 mStateChangeCallbacks.finishBroadcast();
418 }
419
420 /**
Zhihai Xu40874a02012-10-08 17:57:03 -0700421 * Inform BluetoothAdapter instances that Adapter service is up
422 */
423 private void sendBluetoothServiceUpCallback() {
424 if (!mConnection.isGetNameAddressOnly()) {
425 if (DBG) Log.d(TAG,"Calling onBluetoothServiceUp callbacks");
426 int n = mCallbacks.beginBroadcast();
427 Log.d(TAG,"Broadcasting onBluetoothServiceUp() to " + n + " receivers.");
428 for (int i=0; i <n;i++) {
429 try {
430 mCallbacks.getBroadcastItem(i).onBluetoothServiceUp(mBluetooth);
431 } catch (RemoteException e) {
432 Log.e(TAG, "Unable to call onBluetoothServiceUp() on callback #" + i, e);
433 }
434 }
435 mCallbacks.finishBroadcast();
436 }
437 }
438 /**
fredcbf072a72012-05-09 16:52:50 -0700439 * Inform BluetoothAdapter instances that Adapter service is down
440 */
441 private void sendBluetoothServiceDownCallback() {
fredcd6883532012-04-25 17:46:13 -0700442 if (!mConnection.isGetNameAddressOnly()) {
443 if (DBG) Log.d(TAG,"Calling onBluetoothServiceDown callbacks");
444 int n = mCallbacks.beginBroadcast();
445 Log.d(TAG,"Broadcasting onBluetoothServiceDown() to " + n + " receivers.");
446 for (int i=0; i <n;i++) {
447 try {
448 mCallbacks.getBroadcastItem(i).onBluetoothServiceDown();
449 } catch (RemoteException e) {
450 Log.e(TAG, "Unable to call onBluetoothServiceDown() on callback #" + i, e);
451 }
452 }
453 mCallbacks.finishBroadcast();
454 }
455 }
fredc0f420372012-04-12 00:02:00 -0700456 public String getAddress() {
457 mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
458 "Need BLUETOOTH ADMIN permission");
Zhihai Xu40874a02012-10-08 17:57:03 -0700459
460 if (!checkIfCallerIsForegroundUser()) {
461 Log.w(TAG,"getAddress(): not allowed for non-active user");
462 return mAddress;
463 }
464
fredc116d1d462012-04-20 14:47:08 -0700465 synchronized(mConnection) {
466 if (mBluetooth != null) {
467 try {
468 return mBluetooth.getAddress();
469 } catch (RemoteException e) {
470 Log.e(TAG, "getAddress(): Unable to retrieve address remotely..Returning cached address",e);
471 }
472 }
473 }
Matthew Xiecdce0b92012-07-12 19:06:15 -0700474 // mAddress is accessed from outside.
475 // It is alright without a lock. Here, bluetooth is off, no other thread is
476 // changing mAddress
fredc0f420372012-04-12 00:02:00 -0700477 return mAddress;
478 }
fredc649fe492012-04-19 01:07:18 -0700479
fredc0f420372012-04-12 00:02:00 -0700480 public String getName() {
481 mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
482 "Need BLUETOOTH ADMIN permission");
Zhihai Xu40874a02012-10-08 17:57:03 -0700483
484 if (!checkIfCallerIsForegroundUser()) {
485 Log.w(TAG,"getName(): not allowed for non-active user");
486 return mName;
487 }
488
fredc116d1d462012-04-20 14:47:08 -0700489 synchronized(mConnection) {
490 if (mBluetooth != null) {
491 try {
492 return mBluetooth.getName();
493 } catch (RemoteException e) {
494 Log.e(TAG, "getName(): Unable to retrieve name remotely..Returning cached name",e);
495 }
496 }
497 }
Matthew Xiecdce0b92012-07-12 19:06:15 -0700498 // mName is accessed from outside.
499 // It alright without a lock. Here, bluetooth is off, no other thread is
500 // changing mName
fredc0f420372012-04-12 00:02:00 -0700501 return mName;
502 }
503
fredc0f420372012-04-12 00:02:00 -0700504 private class BluetoothServiceConnection implements ServiceConnection {
505
506 private boolean mGetNameAddressOnly;
507
508 public void setGetNameAddressOnly(boolean getOnly) {
509 mGetNameAddressOnly = getOnly;
510 }
511
512 public boolean isGetNameAddressOnly() {
513 return mGetNameAddressOnly;
514 }
515
516 public void onServiceConnected(ComponentName className, IBinder service) {
fredc649fe492012-04-19 01:07:18 -0700517 if (DBG) Log.d(TAG, "BluetoothServiceConnection: connected to AdapterService");
fredc0f420372012-04-12 00:02:00 -0700518 Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_SERVICE_CONNECTED);
519 msg.obj = service;
520 mHandler.sendMessage(msg);
521 }
522
523 public void onServiceDisconnected(ComponentName className) {
fredc0f420372012-04-12 00:02:00 -0700524 // Called if we unexpected disconnected.
fredc649fe492012-04-19 01:07:18 -0700525 if (DBG) Log.d(TAG, "BluetoothServiceConnection: disconnected from AdapterService");
fredc0f420372012-04-12 00:02:00 -0700526 Message msg = mHandler.obtainMessage(MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED);
527 mHandler.sendMessage(msg);
528 }
529 }
530
531 private BluetoothServiceConnection mConnection = new BluetoothServiceConnection();
532
Zhihai Xu40874a02012-10-08 17:57:03 -0700533 private class BluetoothHandler extends Handler {
534 public BluetoothHandler(Looper looper) {
535 super(looper);
536 }
537
fredc0f420372012-04-12 00:02:00 -0700538 @Override
539 public void handleMessage(Message msg) {
540 if (DBG) Log.d (TAG, "Message: " + msg.what);
fredc0f420372012-04-12 00:02:00 -0700541 switch (msg.what) {
542 case MESSAGE_GET_NAME_AND_ADDRESS: {
fredc649fe492012-04-19 01:07:18 -0700543 if (DBG) Log.d(TAG,"MESSAGE_GET_NAME_AND_ADDRESS");
Matthew Xiecdce0b92012-07-12 19:06:15 -0700544 synchronized(mConnection) {
fredc0f420372012-04-12 00:02:00 -0700545 //Start bind request
Zhihai Xu40874a02012-10-08 17:57:03 -0700546 if ((mBluetooth == null) && (!mBinding)) {
fredc0f420372012-04-12 00:02:00 -0700547 if (DBG) Log.d(TAG, "Binding to service to get name and address");
548 mConnection.setGetNameAddressOnly(true);
549 //Start bind timeout and bind
550 Message timeoutMsg = mHandler.obtainMessage(MESSAGE_TIMEOUT_BIND);
551 mHandler.sendMessageDelayed(timeoutMsg,TIMEOUT_BIND_MS);
552 Intent i = new Intent(IBluetooth.class.getName());
553 if (!mContext.bindService(i, mConnection,
Matthew Xiefca9d632012-10-04 12:25:28 -0700554 Context.BIND_AUTO_CREATE, UserHandle.USER_CURRENT)) {
fredc0f420372012-04-12 00:02:00 -0700555 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
556 Log.e(TAG, "fail to bind to: " + IBluetooth.class.getName());
Zhihai Xu40874a02012-10-08 17:57:03 -0700557 } else {
558 mBinding = true;
fredc0f420372012-04-12 00:02:00 -0700559 }
560 }
Matthew Xiecdce0b92012-07-12 19:06:15 -0700561 else {
562 Message saveMsg= mHandler.obtainMessage(MESSAGE_SAVE_NAME_AND_ADDRESS);
Zhihai Xu40874a02012-10-08 17:57:03 -0700563 saveMsg.arg1 = 0;
564 if (mBluetooth != null) {
565 mHandler.sendMessage(saveMsg);
566 } else {
567 // if enable is also called to bind the service
568 // wait for MESSAGE_BLUETOOTH_SERVICE_CONNECTED
569 mHandler.sendMessageDelayed(saveMsg, TIMEOUT_SAVE_MS);
570 }
Matthew Xiecdce0b92012-07-12 19:06:15 -0700571 }
fredc0f420372012-04-12 00:02:00 -0700572 }
fredc649fe492012-04-19 01:07:18 -0700573 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -0700574 }
fredc0f420372012-04-12 00:02:00 -0700575 case MESSAGE_SAVE_NAME_AND_ADDRESS: {
Zhihai Xud31c3222012-10-31 16:08:57 -0700576 boolean unbind = false;
fredc649fe492012-04-19 01:07:18 -0700577 if (DBG) Log.d(TAG,"MESSAGE_SAVE_NAME_AND_ADDRESS");
Matthew Xiecdce0b92012-07-12 19:06:15 -0700578 synchronized(mConnection) {
Zhihai Xud31c3222012-10-31 16:08:57 -0700579 if (!mEnable && mBluetooth != null) {
580 try {
581 mBluetooth.enable();
582 } catch (RemoteException e) {
583 Log.e(TAG,"Unable to call enable()",e);
584 }
585 }
586 }
587 if (mBluetooth != null) waitForOnOff(true, false);
588 synchronized(mConnection) {
Matthew Xiecdce0b92012-07-12 19:06:15 -0700589 if (mBluetooth != null) {
590 String name = null;
591 String address = null;
592 try {
593 name = mBluetooth.getName();
594 address = mBluetooth.getAddress();
595 } catch (RemoteException re) {
596 Log.e(TAG,"",re);
597 }
fredc0f420372012-04-12 00:02:00 -0700598
Matthew Xiecdce0b92012-07-12 19:06:15 -0700599 if (name != null && address != null) {
600 storeNameAndAddress(name,address);
Zhihai Xu40874a02012-10-08 17:57:03 -0700601 if (mConnection.isGetNameAddressOnly()) {
Zhihai Xud31c3222012-10-31 16:08:57 -0700602 unbind = true;
Zhihai Xu40874a02012-10-08 17:57:03 -0700603 }
Matthew Xiecdce0b92012-07-12 19:06:15 -0700604 } else {
605 if (msg.arg1 < MAX_SAVE_RETRIES) {
606 Message retryMsg = mHandler.obtainMessage(MESSAGE_SAVE_NAME_AND_ADDRESS);
607 retryMsg.arg1= 1+msg.arg1;
608 if (DBG) Log.d(TAG,"Retrying name/address remote retrieval and save.....Retry count =" + retryMsg.arg1);
609 mHandler.sendMessageDelayed(retryMsg, TIMEOUT_SAVE_MS);
610 } else {
611 Log.w(TAG,"Maximum name/address remote retrieval retry exceeded");
Zhihai Xu40874a02012-10-08 17:57:03 -0700612 if (mConnection.isGetNameAddressOnly()) {
Zhihai Xud31c3222012-10-31 16:08:57 -0700613 unbind = true;
Zhihai Xu40874a02012-10-08 17:57:03 -0700614 }
Matthew Xiecdce0b92012-07-12 19:06:15 -0700615 }
fredc0f420372012-04-12 00:02:00 -0700616 }
Zhihai Xud31c3222012-10-31 16:08:57 -0700617 if (!mEnable) {
618 try {
619 mBluetooth.disable();
620 } catch (RemoteException e) {
621 Log.e(TAG,"Unable to call disable()",e);
622 }
623 }
Zhihai Xu40874a02012-10-08 17:57:03 -0700624 } else {
625 // rebind service by Request GET NAME AND ADDRESS
626 // if service is unbinded by disable or
627 // MESSAGE_BLUETOOTH_SERVICE_CONNECTED is not received
628 Message getMsg = mHandler.obtainMessage(MESSAGE_GET_NAME_AND_ADDRESS);
629 mHandler.sendMessage(getMsg);
fredc0f420372012-04-12 00:02:00 -0700630 }
631 }
Zhihai Xud31c3222012-10-31 16:08:57 -0700632 if (!mEnable && mBluetooth != null) waitForOnOff(false, true);
633 if (unbind) {
634 unbindAndFinish();
635 }
fredc649fe492012-04-19 01:07:18 -0700636 break;
fredc649fe492012-04-19 01:07:18 -0700637 }
Matthew Xiecdce0b92012-07-12 19:06:15 -0700638 case MESSAGE_ENABLE:
fredcf2458862012-04-16 15:18:27 -0700639 if (DBG) {
Matthew Xiecdce0b92012-07-12 19:06:15 -0700640 Log.d(TAG, "MESSAGE_ENABLE: mBluetooth = " + mBluetooth);
fredc649fe492012-04-19 01:07:18 -0700641 }
Zhihai Xu40874a02012-10-08 17:57:03 -0700642 mHandler.removeMessages(MESSAGE_RESTART_BLUETOOTH_SERVICE);
643 mEnable = true;
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700644 handleEnable(msg.arg1 == 1, msg.arg2 ==1);
fredc649fe492012-04-19 01:07:18 -0700645 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -0700646
fredc0f420372012-04-12 00:02:00 -0700647 case MESSAGE_DISABLE:
Zhihai Xu40874a02012-10-08 17:57:03 -0700648 mHandler.removeMessages(MESSAGE_RESTART_BLUETOOTH_SERVICE);
649 if (mEnable && mBluetooth != null) {
650 waitForOnOff(true, false);
651 mEnable = false;
652 handleDisable(msg.arg1 == 1);
653 waitForOnOff(false, false);
654 } else {
655 mEnable = false;
656 handleDisable(msg.arg1 == 1);
657 }
fredc0f420372012-04-12 00:02:00 -0700658 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -0700659
fredc0f420372012-04-12 00:02:00 -0700660 case MESSAGE_REGISTER_ADAPTER:
661 {
662 IBluetoothManagerCallback callback = (IBluetoothManagerCallback) msg.obj;
fredcd6883532012-04-25 17:46:13 -0700663 boolean added = mCallbacks.register(callback);
664 Log.d(TAG,"Added callback: " + (callback == null? "null": callback) +":" +added );
fredc0f420372012-04-12 00:02:00 -0700665 }
666 break;
667 case MESSAGE_UNREGISTER_ADAPTER:
668 {
669 IBluetoothManagerCallback callback = (IBluetoothManagerCallback) msg.obj;
fredcd6883532012-04-25 17:46:13 -0700670 boolean removed = mCallbacks.unregister(callback);
671 Log.d(TAG,"Removed callback: " + (callback == null? "null": callback) +":" + removed);
fredc0f420372012-04-12 00:02:00 -0700672 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -0700673 }
fredc0f420372012-04-12 00:02:00 -0700674 case MESSAGE_REGISTER_STATE_CHANGE_CALLBACK:
675 {
676 IBluetoothStateChangeCallback callback = (IBluetoothStateChangeCallback) msg.obj;
fredcd6883532012-04-25 17:46:13 -0700677 mStateChangeCallbacks.register(callback);
fredc0f420372012-04-12 00:02:00 -0700678 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -0700679 }
fredc0f420372012-04-12 00:02:00 -0700680 case MESSAGE_UNREGISTER_STATE_CHANGE_CALLBACK:
681 {
682 IBluetoothStateChangeCallback callback = (IBluetoothStateChangeCallback) msg.obj;
fredcd6883532012-04-25 17:46:13 -0700683 mStateChangeCallbacks.unregister(callback);
fredc0f420372012-04-12 00:02:00 -0700684 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -0700685 }
fredc0f420372012-04-12 00:02:00 -0700686 case MESSAGE_BLUETOOTH_SERVICE_CONNECTED:
687 {
fredc649fe492012-04-19 01:07:18 -0700688 if (DBG) Log.d(TAG,"MESSAGE_BLUETOOTH_SERVICE_CONNECTED");
689
fredc0f420372012-04-12 00:02:00 -0700690 //Remove timeout
691 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
692
693 IBinder service = (IBinder) msg.obj;
694 synchronized(mConnection) {
fredc0f420372012-04-12 00:02:00 -0700695 mBinding = false;
696 mBluetooth = IBluetooth.Stub.asInterface(service);
fredc0f420372012-04-12 00:02:00 -0700697
Matthew Xiecdce0b92012-07-12 19:06:15 -0700698 if (mConnection.isGetNameAddressOnly()) {
699 //Request GET NAME AND ADDRESS
700 Message getMsg = mHandler.obtainMessage(MESSAGE_GET_NAME_AND_ADDRESS);
701 mHandler.sendMessage(getMsg);
Zhihai Xu40874a02012-10-08 17:57:03 -0700702 if (!mEnable) return;
Matthew Xiecdce0b92012-07-12 19:06:15 -0700703 }
fredc0f420372012-04-12 00:02:00 -0700704
Zhihai Xu40874a02012-10-08 17:57:03 -0700705 mConnection.setGetNameAddressOnly(false);
Matthew Xiecdce0b92012-07-12 19:06:15 -0700706 //Register callback object
fredcbf072a72012-05-09 16:52:50 -0700707 try {
Matthew Xiecdce0b92012-07-12 19:06:15 -0700708 mBluetooth.registerCallback(mBluetoothCallback);
709 } catch (RemoteException re) {
710 Log.e(TAG, "Unable to register BluetoothCallback",re);
fredcbf072a72012-05-09 16:52:50 -0700711 }
Matthew Xiecdce0b92012-07-12 19:06:15 -0700712 //Inform BluetoothAdapter instances that service is up
Zhihai Xu40874a02012-10-08 17:57:03 -0700713 sendBluetoothServiceUpCallback();
714
Matthew Xiecdce0b92012-07-12 19:06:15 -0700715 //Do enable request
716 try {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700717 if (mQuietEnable == false) {
718 if(!mBluetooth.enable()) {
719 Log.e(TAG,"IBluetooth.enable() returned false");
720 }
721 }
722 else
723 {
724 if(!mBluetooth.enableNoAutoConnect()) {
725 Log.e(TAG,"IBluetooth.enableNoAutoConnect() returned false");
726 }
Matthew Xiecdce0b92012-07-12 19:06:15 -0700727 }
728 } catch (RemoteException e) {
729 Log.e(TAG,"Unable to call enable()",e);
730 }
Freda8c6df02012-07-11 10:25:23 -0700731 }
Zhihai Xu40874a02012-10-08 17:57:03 -0700732
733 if (!mEnable) {
734 waitForOnOff(true, false);
735 handleDisable(false);
736 waitForOnOff(false, false);
737 }
fredc649fe492012-04-19 01:07:18 -0700738 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -0700739 }
fredc649fe492012-04-19 01:07:18 -0700740 case MESSAGE_TIMEOUT_BIND: {
741 Log.e(TAG, "MESSAGE_TIMEOUT_BIND");
fredc0f420372012-04-12 00:02:00 -0700742 synchronized(mConnection) {
743 mBinding = false;
744 }
fredc649fe492012-04-19 01:07:18 -0700745 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -0700746 }
fredcbf072a72012-05-09 16:52:50 -0700747 case MESSAGE_BLUETOOTH_STATE_CHANGE:
fredc0f420372012-04-12 00:02:00 -0700748 {
fredcbf072a72012-05-09 16:52:50 -0700749 int prevState = msg.arg1;
750 int newState = msg.arg2;
751 if (DBG) Log.d(TAG, "MESSAGE_BLUETOOTH_STATE_CHANGE: prevState = " + prevState + ", newState=" + newState);
Zhihai Xu40874a02012-10-08 17:57:03 -0700752 mState = newState;
753 bluetoothStateChangeHandler(prevState, newState);
fredc649fe492012-04-19 01:07:18 -0700754 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -0700755 }
fredc0f420372012-04-12 00:02:00 -0700756 case MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED:
757 {
Zhihai Xu40874a02012-10-08 17:57:03 -0700758 Log.e(TAG, "MESSAGE_BLUETOOTH_SERVICE_DISCONNECTED");
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +0530759 synchronized(mConnection) {
Zhihai Xu40874a02012-10-08 17:57:03 -0700760 // if service is unbinded already, do nothing and return
761 if (mBluetooth == null) return;
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +0530762 mBluetooth = null;
763 }
Zhihai Xu40874a02012-10-08 17:57:03 -0700764
765 if (mEnable) {
766 mEnable = false;
767 // Send a Bluetooth Restart message
768 Message restartMsg = mHandler.obtainMessage(
769 MESSAGE_RESTART_BLUETOOTH_SERVICE);
770 mHandler.sendMessageDelayed(restartMsg,
771 SERVICE_RESTART_TIME_MS);
772 }
773
774 if (!mConnection.isGetNameAddressOnly()) {
775 sendBluetoothServiceDownCallback();
776
777 // Send BT state broadcast to update
778 // the BT icon correctly
779 bluetoothStateChangeHandler(BluetoothAdapter.STATE_ON,
780 BluetoothAdapter.STATE_TURNING_OFF);
781 mState = BluetoothAdapter.STATE_OFF;
782 }
fredc649fe492012-04-19 01:07:18 -0700783 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -0700784 }
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +0530785 case MESSAGE_RESTART_BLUETOOTH_SERVICE:
786 {
787 Log.d(TAG, "MESSAGE_RESTART_BLUETOOTH_SERVICE:"
788 +" Restart IBluetooth service");
789 /* Enable without persisting the setting as
790 it doesnt change when IBluetooth
791 service restarts */
Zhihai Xu40874a02012-10-08 17:57:03 -0700792 mEnable = true;
Syed Ibrahim M1223e5a2012-08-29 18:07:26 +0530793 handleEnable(false, mQuietEnable);
794 break;
795 }
796
fredc0f420372012-04-12 00:02:00 -0700797 case MESSAGE_TIMEOUT_UNBIND:
798 {
fredc649fe492012-04-19 01:07:18 -0700799 Log.e(TAG, "MESSAGE_TIMEOUT_UNBIND");
fredc0f420372012-04-12 00:02:00 -0700800 synchronized(mConnection) {
801 mUnbinding = false;
802 }
fredc649fe492012-04-19 01:07:18 -0700803 break;
Matthew Xiecdce0b92012-07-12 19:06:15 -0700804 }
Zhihai Xu40874a02012-10-08 17:57:03 -0700805
806 case MESSAGE_USER_SWITCHED:
807 {
808 if (DBG) {
809 Log.d(TAG, "MESSAGE_USER_SWITCHED");
810 }
811 mHandler.removeMessages(MESSAGE_USER_SWITCHED);
812 /* disable and enable BT when detect a user switch */
813 if (mEnable && mBluetooth != null) {
814 synchronized (mConnection) {
815 if (mBluetooth != null) {
816 //Unregister callback object
817 try {
818 mBluetooth.unregisterCallback(mBluetoothCallback);
819 } catch (RemoteException re) {
820 Log.e(TAG, "Unable to unregister",re);
821 }
822 }
823 }
824 mHandler.removeMessages(MESSAGE_BLUETOOTH_STATE_CHANGE);
825
826 waitForOnOff(true, false);
827
828 bluetoothStateChangeHandler(mState, BluetoothAdapter.STATE_ON);
829
830 // disable
831 handleDisable(false);
832
833 waitForOnOff(false, true);
834
835 bluetoothStateChangeHandler(BluetoothAdapter.STATE_ON,
836 BluetoothAdapter.STATE_OFF);
837 mState = BluetoothAdapter.STATE_OFF;
838 sendBluetoothServiceDownCallback();
839 synchronized (mConnection) {
840 if (mBluetooth != null) {
841 mBluetooth = null;
842 //Unbind
843 mContext.unbindService(mConnection);
844 }
845 }
846 SystemClock.sleep(100);
847
848 // enable
849 handleEnable(false, mQuietEnable);
850 } else if (mBinding || mBluetooth != null) {
851 Message userMsg = mHandler.obtainMessage(MESSAGE_USER_SWITCHED);
852 userMsg.arg2 = 1 + msg.arg2;
853 // if user is switched when service is being binding
854 // delay sending MESSAGE_USER_SWITCHED
855 mHandler.sendMessageDelayed(userMsg, USER_SWITCHED_TIME_MS);
856 if (DBG) {
857 Log.d(TAG, "delay MESSAGE_USER_SWITCHED " + userMsg.arg2);
858 }
859 }
860 break;
861 }
fredc0f420372012-04-12 00:02:00 -0700862 }
863 }
Zhihai Xu40874a02012-10-08 17:57:03 -0700864 }
Matthew Xiecdce0b92012-07-12 19:06:15 -0700865
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700866 private void handleEnable(boolean persist, boolean quietMode) {
Matthew Xiecdce0b92012-07-12 19:06:15 -0700867 if (persist) {
868 persistBluetoothSetting(true);
869 }
870
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700871 mQuietEnable = quietMode;
872
Matthew Xiecdce0b92012-07-12 19:06:15 -0700873 synchronized(mConnection) {
Zhihai Xu40874a02012-10-08 17:57:03 -0700874 if ((mBluetooth == null) && (!mBinding)) {
Matthew Xiecdce0b92012-07-12 19:06:15 -0700875 //Start bind timeout and bind
876 Message timeoutMsg=mHandler.obtainMessage(MESSAGE_TIMEOUT_BIND);
877 mHandler.sendMessageDelayed(timeoutMsg,TIMEOUT_BIND_MS);
878 mConnection.setGetNameAddressOnly(false);
879 Intent i = new Intent(IBluetooth.class.getName());
Zhihai Xu40874a02012-10-08 17:57:03 -0700880 if (!mContext.bindService(i, mConnection,Context.BIND_AUTO_CREATE,
Matthew Xiefca9d632012-10-04 12:25:28 -0700881 UserHandle.USER_CURRENT)) {
Matthew Xiecdce0b92012-07-12 19:06:15 -0700882 mHandler.removeMessages(MESSAGE_TIMEOUT_BIND);
883 Log.e(TAG, "Fail to bind to: " + IBluetooth.class.getName());
Zhihai Xu40874a02012-10-08 17:57:03 -0700884 } else {
885 mBinding = true;
Matthew Xiecdce0b92012-07-12 19:06:15 -0700886 }
Zhihai Xu40874a02012-10-08 17:57:03 -0700887 } else if (mBluetooth != null) {
888 if (mConnection.isGetNameAddressOnly()) {
889 // if GetNameAddressOnly is set, we can clear this flag,
890 // so the service won't be unbind
891 // after name and address are saved
892 mConnection.setGetNameAddressOnly(false);
893 //Register callback object
894 try {
895 mBluetooth.registerCallback(mBluetoothCallback);
896 } catch (RemoteException re) {
897 Log.e(TAG, "Unable to register BluetoothCallback",re);
898 }
899 //Inform BluetoothAdapter instances that service is up
900 sendBluetoothServiceUpCallback();
901 }
902
Matthew Xiecdce0b92012-07-12 19:06:15 -0700903 //Enable bluetooth
904 try {
Ganesh Ganapathi Battafffa86b2012-08-08 15:35:49 -0700905 if (!mQuietEnable) {
906 if(!mBluetooth.enable()) {
907 Log.e(TAG,"IBluetooth.enable() returned false");
908 }
909 }
910 else {
911 if(!mBluetooth.enableNoAutoConnect()) {
912 Log.e(TAG,"IBluetooth.enableNoAutoConnect() returned false");
913 }
Matthew Xiecdce0b92012-07-12 19:06:15 -0700914 }
915 } catch (RemoteException e) {
916 Log.e(TAG,"Unable to call enable()",e);
917 }
918 }
919 }
920 }
921
922 private void handleDisable(boolean persist) {
Zhihai Xu40874a02012-10-08 17:57:03 -0700923 if (persist) {
924 persistBluetoothSetting(false);
925 }
926
Matthew Xiecdce0b92012-07-12 19:06:15 -0700927 synchronized(mConnection) {
Zhihai Xu40874a02012-10-08 17:57:03 -0700928 // don't need to disable if GetNameAddressOnly is set,
929 // service will be unbinded after Name and Address are saved
930 if ((mBluetooth != null) && (!mConnection.isGetNameAddressOnly())) {
Matthew Xiecdce0b92012-07-12 19:06:15 -0700931 if (DBG) Log.d(TAG,"Sending off request.");
932
933 try {
934 if(!mBluetooth.disable()) {
935 Log.e(TAG,"IBluetooth.disable() returned false");
936 }
937 } catch (RemoteException e) {
938 Log.e(TAG,"Unable to call disable()",e);
939 }
940 }
941 }
942 }
Zhihai Xu40874a02012-10-08 17:57:03 -0700943
944 private boolean checkIfCallerIsForegroundUser() {
945 int foregroundUser;
946 int callingUser = UserHandle.getCallingUserId();
Martijn Coenen8385c5a2012-11-29 10:14:16 -0800947 int callingUid = Binder.getCallingUid();
Zhihai Xu40874a02012-10-08 17:57:03 -0700948 long callingIdentity = Binder.clearCallingIdentity();
Martijn Coenen8385c5a2012-11-29 10:14:16 -0800949 int callingAppId = UserHandle.getAppId(callingUid);
Zhihai Xu40874a02012-10-08 17:57:03 -0700950 boolean valid = false;
951 try {
952 foregroundUser = ActivityManager.getCurrentUser();
Martijn Coenen8385c5a2012-11-29 10:14:16 -0800953 valid = (callingUser == foregroundUser) ||
954 callingAppId == Process.NFC_UID;
Zhihai Xu40874a02012-10-08 17:57:03 -0700955 if (DBG) {
956 Log.d(TAG, "checkIfCallerIsForegroundUser: valid=" + valid
957 + " callingUser=" + callingUser
958 + " foregroundUser=" + foregroundUser);
959 }
960 } finally {
961 Binder.restoreCallingIdentity(callingIdentity);
962 }
963 return valid;
964 }
965
966 private boolean enableHelper() {
967 mContext.enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM,
968 "Need BLUETOOTH ADMIN permission");
969 if (DBG) {
970 Log.d(TAG,"enable(): mBluetooth =" + mBluetooth +
971 " mBinding = " + mBinding);
972 }
973
974 Message msg = mHandler.obtainMessage(MESSAGE_ENABLE);
975 msg.arg1=1; //persist
976 msg.arg2=0; //No Quiet Mode
977 mHandler.sendMessage(msg);
978 return true;
979 }
980
981 private void bluetoothStateChangeHandler(int prevState, int newState) {
982 if (prevState != newState) {
983 //Notify all proxy objects first of adapter state change
984 if (newState == BluetoothAdapter.STATE_ON || newState == BluetoothAdapter.STATE_OFF) {
985 boolean isUp = (newState==BluetoothAdapter.STATE_ON);
986 sendBluetoothStateCallback(isUp);
987
988 //If Bluetooth is off, send service down event to proxy objects, and unbind
989 if (!isUp) {
990 //Only unbind with mEnable flag not set
991 //For race condition: disable and enable back-to-back
992 //Avoid unbind right after enable due to callback from disable
993 if ((!mEnable) && (mBluetooth != null)) {
994 sendBluetoothServiceDownCallback();
995 unbindAndFinish();
996 }
997 }
998 }
999
1000 //Send broadcast message to everyone else
1001 Intent intent = new Intent(BluetoothAdapter.ACTION_STATE_CHANGED);
1002 intent.putExtra(BluetoothAdapter.EXTRA_PREVIOUS_STATE, prevState);
1003 intent.putExtra(BluetoothAdapter.EXTRA_STATE, newState);
1004 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1005 if (DBG) Log.d(TAG,"Bluetooth State Change Intent: " + prevState + " -> " + newState);
1006 mContext.sendBroadcastAsUser(intent, UserHandle.ALL,
1007 BLUETOOTH_PERM);
1008 }
1009 }
1010
1011 /**
1012 * if on is true, wait for state become ON
1013 * if off is true, wait for state become OFF
1014 * if both on and off are false, wait for state not ON
1015 */
1016 private boolean waitForOnOff(boolean on, boolean off) {
1017 int i = 0;
1018 while (i < 10) {
1019 synchronized(mConnection) {
1020 try {
1021 if (mBluetooth == null) break;
1022 if (on) {
1023 if (mBluetooth.getState() == BluetoothAdapter.STATE_ON) return true;
1024 } else if (off) {
1025 if (mBluetooth.getState() == BluetoothAdapter.STATE_OFF) return true;
1026 } else {
1027 if (mBluetooth.getState() != BluetoothAdapter.STATE_ON) return true;
1028 }
1029 } catch (RemoteException e) {
1030 Log.e(TAG, "getState()", e);
1031 break;
1032 }
1033 }
1034 if (on || off) {
1035 SystemClock.sleep(300);
1036 } else {
1037 SystemClock.sleep(50);
1038 }
1039 i++;
1040 }
1041 Log.e(TAG,"waitForOnOff time out");
1042 return false;
1043 }
fredc0f420372012-04-12 00:02:00 -07001044}