AdapterService.java revision b03b1ce32fe4f39139d9f62b002cf329a0cd72aa
1/* 2 * 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. 15 */ 16 17/** 18 * @hide 19 */ 20 21package com.android.bluetooth.btservice; 22 23import android.app.AlarmManager; 24import android.app.Application; 25import android.app.PendingIntent; 26import android.app.Service; 27import android.bluetooth.BluetoothAdapter; 28import android.bluetooth.BluetoothDevice; 29import android.bluetooth.BluetoothProfile; 30import android.bluetooth.BluetoothUuid; 31import android.bluetooth.IBluetooth; 32import android.bluetooth.IBluetoothCallback; 33import android.bluetooth.IBluetoothManager; 34import android.bluetooth.IBluetoothManagerCallback; 35import android.bluetooth.BluetoothActivityEnergyInfo; 36import android.bluetooth.OobData; 37import android.bluetooth.UidTraffic; 38import android.content.BroadcastReceiver; 39import android.content.ContentResolver; 40import android.content.Context; 41import android.content.Intent; 42import android.content.IntentFilter; 43import android.content.SharedPreferences; 44import android.os.BatteryStats; 45import android.os.Binder; 46import android.os.Bundle; 47import android.os.Handler; 48import android.os.IBinder; 49import android.os.Message; 50import android.os.ParcelFileDescriptor; 51import android.os.ParcelUuid; 52import android.os.PowerManager; 53import android.os.Process; 54import android.os.RemoteCallbackList; 55import android.os.RemoteException; 56import android.os.SystemClock; 57import android.provider.Settings; 58import android.text.TextUtils; 59import android.util.Base64; 60import android.util.EventLog; 61import android.util.Log; 62import android.util.Pair; 63 64import android.util.SparseArray; 65import com.android.bluetooth.a2dp.A2dpService; 66import com.android.bluetooth.a2dp.A2dpSinkService; 67import com.android.bluetooth.hid.HidService; 68import com.android.bluetooth.hfp.HeadsetService; 69import com.android.bluetooth.hfpclient.HeadsetClientService; 70import com.android.bluetooth.hdp.HealthService; 71import com.android.bluetooth.pan.PanService; 72import com.android.bluetooth.sdp.SdpManager; 73import com.android.internal.R; 74import com.android.bluetooth.Utils; 75import com.android.bluetooth.btservice.RemoteDevices.DeviceProperties; 76 77import java.io.FileDescriptor; 78import java.io.FileOutputStream; 79import java.io.FileWriter; 80import java.io.IOException; 81import java.io.PrintWriter; 82import java.nio.charset.StandardCharsets; 83import java.util.ArrayList; 84import java.util.Arrays; 85import java.util.HashMap; 86import java.util.Set; 87import java.util.Map; 88import java.util.Iterator; 89import java.util.Map.Entry; 90import java.util.List; 91 92import android.content.pm.PackageManager; 93import android.os.ServiceManager; 94import com.android.internal.app.IBatteryStats; 95 96public class AdapterService extends Service { 97 private static final String TAG = "BluetoothAdapterService"; 98 private static final boolean DBG = false; 99 private static final boolean TRACE_REF = false; 100 private static final int MIN_ADVT_INSTANCES_FOR_MA = 5; 101 private static final int MIN_OFFLOADED_FILTERS = 10; 102 private static final int MIN_OFFLOADED_SCAN_STORAGE_BYTES = 1024; 103 //For Debugging only 104 private static int sRefCount = 0; 105 private long mBluetoothStartTime = 0; 106 107 private final Object mEnergyInfoLock = new Object(); 108 private int mStackReportedState; 109 private int mTxTimeTotalMs; 110 private int mRxTimeTotalMs; 111 private int mIdleTimeTotalMs; 112 private int mEnergyUsedTotalVoltAmpSecMicro; 113 private SparseArray<UidTraffic> mUidTraffic = new SparseArray<>(); 114 115 private final ArrayList<ProfileService> mProfiles = new ArrayList<ProfileService>(); 116 117 public static final String ACTION_LOAD_ADAPTER_PROPERTIES = 118 "com.android.bluetooth.btservice.action.LOAD_ADAPTER_PROPERTIES"; 119 public static final String ACTION_SERVICE_STATE_CHANGED = 120 "com.android.bluetooth.btservice.action.STATE_CHANGED"; 121 public static final String EXTRA_ACTION="action"; 122 public static final int PROFILE_CONN_CONNECTED = 1; 123 public static final int PROFILE_CONN_REJECTED = 2; 124 125 private static final String ACTION_ALARM_WAKEUP = 126 "com.android.bluetooth.btservice.action.ALARM_WAKEUP"; 127 128 public static final String BLUETOOTH_ADMIN_PERM = 129 android.Manifest.permission.BLUETOOTH_ADMIN; 130 public static final String BLUETOOTH_PRIVILEGED = 131 android.Manifest.permission.BLUETOOTH_PRIVILEGED; 132 static final String BLUETOOTH_PERM = android.Manifest.permission.BLUETOOTH; 133 static final String RECEIVE_MAP_PERM = android.Manifest.permission.RECEIVE_BLUETOOTH_MAP; 134 135 private static final String PHONEBOOK_ACCESS_PERMISSION_PREFERENCE_FILE = 136 "phonebook_access_permission"; 137 private static final String MESSAGE_ACCESS_PERMISSION_PREFERENCE_FILE = 138 "message_access_permission"; 139 private static final String SIM_ACCESS_PERMISSION_PREFERENCE_FILE = 140 "sim_access_permission"; 141 142 private static final int ADAPTER_SERVICE_TYPE=Service.START_STICKY; 143 144 private static final String[] DEVICE_TYPE_NAMES = new String[] { 145 "???", 146 "BR/EDR", 147 "LE", 148 "DUAL" 149 }; 150 151 static { 152 classInitNative(); 153 } 154 155 private static AdapterService sAdapterService; 156 public static synchronized AdapterService getAdapterService(){ 157 if (sAdapterService != null && !sAdapterService.mCleaningUp) { 158 Log.d(TAG, "getAdapterService() - returning " + sAdapterService); 159 return sAdapterService; 160 } 161 if (DBG) { 162 if (sAdapterService == null) { 163 Log.d(TAG, "getAdapterService() - Service not available"); 164 } else if (sAdapterService.mCleaningUp) { 165 Log.d(TAG,"getAdapterService() - Service is cleaning up"); 166 } 167 } 168 return null; 169 } 170 171 private static synchronized void setAdapterService(AdapterService instance) { 172 if (instance != null && !instance.mCleaningUp) { 173 if (DBG) Log.d(TAG, "setAdapterService() - set to: " + sAdapterService); 174 sAdapterService = instance; 175 } else { 176 if (DBG) { 177 if (sAdapterService == null) { 178 Log.d(TAG, "setAdapterService() - Service not available"); 179 } else if (sAdapterService.mCleaningUp) { 180 Log.d(TAG,"setAdapterService() - Service is cleaning up"); 181 } 182 } 183 } 184 } 185 186 private static synchronized void clearAdapterService() { 187 sAdapterService = null; 188 } 189 190 private AdapterProperties mAdapterProperties; 191 private AdapterState mAdapterStateMachine; 192 private BondStateMachine mBondStateMachine; 193 private JniCallbacks mJniCallbacks; 194 private RemoteDevices mRemoteDevices; 195 196 /* TODO: Consider to remove the search API from this class, if changed to use call-back */ 197 private SdpManager mSdpManager = null; 198 199 private boolean mProfilesStarted; 200 private boolean mNativeAvailable; 201 private boolean mCleaningUp; 202 private HashMap<String,Integer> mProfileServicesState = new HashMap<String,Integer>(); 203 //Only BluetoothManagerService should be registered 204 private RemoteCallbackList<IBluetoothCallback> mCallbacks; 205 private int mCurrentRequestId; 206 private boolean mQuietmode = false; 207 208 private AlarmManager mAlarmManager; 209 private PendingIntent mPendingAlarm; 210 private IBatteryStats mBatteryStats; 211 private PowerManager mPowerManager; 212 private PowerManager.WakeLock mWakeLock; 213 private String mWakeLockName; 214 215 private ProfileObserver mProfileObserver; 216 217 public AdapterService() { 218 super(); 219 if (TRACE_REF) { 220 synchronized (AdapterService.class) { 221 sRefCount++; 222 debugLog("AdapterService() - REFCOUNT: CREATED. INSTANCE_COUNT" + sRefCount); 223 } 224 } 225 226 // This is initialized at the beginning in order to prevent 227 // NullPointerException from happening if AdapterService 228 // functions are called before BLE is turned on due to 229 // |mRemoteDevices| being null. 230 mRemoteDevices = new RemoteDevices(this); 231 } 232 233 public void onProfileConnectionStateChanged(BluetoothDevice device, int profileId, int newState, int prevState) { 234 Message m = mHandler.obtainMessage(MESSAGE_PROFILE_CONNECTION_STATE_CHANGED); 235 m.obj = device; 236 m.arg1 = profileId; 237 m.arg2 = newState; 238 Bundle b = new Bundle(1); 239 b.putInt("prevState", prevState); 240 m.setData(b); 241 mHandler.sendMessage(m); 242 } 243 244 public void initProfilePriorities(BluetoothDevice device, ParcelUuid[] mUuids) { 245 if(mUuids == null) return; 246 Message m = mHandler.obtainMessage(MESSAGE_PROFILE_INIT_PRIORITIES); 247 m.obj = device; 248 m.arg1 = mUuids.length; 249 Bundle b = new Bundle(1); 250 for(int i=0; i<mUuids.length; i++) { 251 b.putParcelable("uuids" + i, mUuids[i]); 252 } 253 m.setData(b); 254 mHandler.sendMessage(m); 255 } 256 257 private void processInitProfilePriorities (BluetoothDevice device, ParcelUuid[] uuids){ 258 HidService hidService = HidService.getHidService(); 259 A2dpService a2dpService = A2dpService.getA2dpService(); 260 A2dpSinkService a2dpSinkService = A2dpSinkService.getA2dpSinkService(); 261 HeadsetService headsetService = HeadsetService.getHeadsetService(); 262 HeadsetClientService headsetClientService = HeadsetClientService.getHeadsetClientService(); 263 264 // Set profile priorities only for the profiles discovered on the remote device. 265 // This avoids needless auto-connect attempts to profiles non-existent on the remote device 266 if ((hidService != null) && 267 (BluetoothUuid.isUuidPresent(uuids, BluetoothUuid.Hid) || 268 BluetoothUuid.isUuidPresent(uuids, BluetoothUuid.Hogp)) && 269 (hidService.getPriority(device) == BluetoothProfile.PRIORITY_UNDEFINED)){ 270 hidService.setPriority(device,BluetoothProfile.PRIORITY_ON); 271 } 272 273 // If we do not have a stored priority for HFP/A2DP (all roles) then default to on. 274 if ((headsetService != null) && 275 ((BluetoothUuid.isUuidPresent(uuids, BluetoothUuid.HSP) || 276 BluetoothUuid.isUuidPresent(uuids, BluetoothUuid.Handsfree)) && 277 (headsetService.getPriority(device) == BluetoothProfile.PRIORITY_UNDEFINED))) { 278 headsetService.setPriority(device,BluetoothProfile.PRIORITY_ON); 279 } 280 281 if ((a2dpService != null) && 282 (BluetoothUuid.isUuidPresent(uuids, BluetoothUuid.AudioSink) || 283 BluetoothUuid.isUuidPresent(uuids, BluetoothUuid.AdvAudioDist)) && 284 (a2dpService.getPriority(device) == BluetoothProfile.PRIORITY_UNDEFINED)){ 285 a2dpService.setPriority(device,BluetoothProfile.PRIORITY_ON); 286 } 287 288 if ((headsetClientService != null) && 289 ((BluetoothUuid.isUuidPresent(uuids, BluetoothUuid.Handsfree_AG) || 290 BluetoothUuid.isUuidPresent(uuids, BluetoothUuid.HSP_AG)) && 291 (headsetClientService.getPriority(device) == BluetoothProfile.PRIORITY_UNDEFINED))) { 292 headsetClientService.setPriority(device, BluetoothProfile.PRIORITY_ON); 293 } 294 295 if ((a2dpSinkService != null) && 296 (BluetoothUuid.isUuidPresent(uuids, BluetoothUuid.AudioSource) && 297 (a2dpSinkService.getPriority(device) == BluetoothProfile.PRIORITY_UNDEFINED))) { 298 a2dpSinkService.setPriority(device, BluetoothProfile.PRIORITY_ON); 299 } 300 301 } 302 303 private void processProfileStateChanged(BluetoothDevice device, int profileId, int newState, int prevState) { 304 // Profiles relevant to phones. 305 if (((profileId == BluetoothProfile.A2DP) || (profileId == BluetoothProfile.HEADSET)) && 306 (newState == BluetoothProfile.STATE_CONNECTED)){ 307 debugLog( "Profile connected. Schedule missing profile connection if any"); 308 connectOtherProfile(device, PROFILE_CONN_CONNECTED); 309 setProfileAutoConnectionPriority(device, profileId); 310 } 311 312 // Profiles relevant to Car Kitts. 313 if (((profileId == BluetoothProfile.A2DP_SINK) || 314 (profileId == BluetoothProfile.HEADSET_CLIENT)) && 315 (newState == BluetoothProfile.STATE_CONNECTED)) { 316 debugLog( "Profile connected. Schedule missing profile connection if any"); 317 connectOtherProfile(device, PROFILE_CONN_CONNECTED); 318 setProfileAutoConnectionPriority(device, profileId); 319 } 320 321 IBluetooth.Stub binder = mBinder; 322 if (binder != null) { 323 try { 324 binder.sendConnectionStateChange(device, profileId, newState,prevState); 325 } catch (RemoteException re) { 326 errorLog("" + re); 327 } 328 } 329 } 330 331 public void addProfile(ProfileService profile) { 332 synchronized (mProfiles) { 333 mProfiles.add(profile); 334 } 335 } 336 337 public void removeProfile(ProfileService profile) { 338 synchronized (mProfiles) { 339 mProfiles.remove(profile); 340 } 341 } 342 343 public void onProfileServiceStateChanged(String serviceName, int state) { 344 Message m = mHandler.obtainMessage(MESSAGE_PROFILE_SERVICE_STATE_CHANGED); 345 m.obj=serviceName; 346 m.arg1 = state; 347 mHandler.sendMessage(m); 348 } 349 350 private void processProfileServiceStateChanged(String serviceName, int state) { 351 boolean doUpdate=false; 352 boolean isBleTurningOn; 353 boolean isBleTurningOff; 354 boolean isTurningOn; 355 boolean isTurningOff; 356 357 synchronized (mProfileServicesState) { 358 Integer prevState = mProfileServicesState.get(serviceName); 359 if (prevState != null && prevState != state) { 360 mProfileServicesState.put(serviceName,state); 361 doUpdate=true; 362 } 363 } 364 debugLog("processProfileServiceStateChanged() serviceName=" + serviceName 365 + ", state=" + state +", doUpdate=" + doUpdate); 366 367 if (!doUpdate) { 368 return; 369 } 370 371 synchronized (mAdapterStateMachine) { 372 isTurningOff = mAdapterStateMachine.isTurningOff(); 373 isTurningOn = mAdapterStateMachine.isTurningOn(); 374 isBleTurningOn = mAdapterStateMachine.isBleTurningOn(); 375 isBleTurningOff = mAdapterStateMachine.isBleTurningOff(); 376 } 377 378 debugLog("processProfileServiceStateChanged() - serviceName=" + serviceName + 379 " isTurningOn=" + isTurningOn + " isTurningOff=" + isTurningOff + 380 " isBleTurningOn=" + isBleTurningOn + " isBleTurningOff=" + isBleTurningOff); 381 382 if (isBleTurningOn) { 383 if (serviceName.equals("com.android.bluetooth.gatt.GattService")) { 384 debugLog("GattService is started"); 385 mAdapterStateMachine.sendMessage(mAdapterStateMachine.obtainMessage(AdapterState.BLE_STARTED)); 386 return; 387 } 388 389 } else if(isBleTurningOff) { 390 if (serviceName.equals("com.android.bluetooth.gatt.GattService")) { 391 debugLog("GattService stopped"); 392 mAdapterStateMachine.sendMessage(mAdapterStateMachine.obtainMessage(AdapterState.BLE_STOPPED)); 393 return; 394 } 395 396 } else if (isTurningOff) { 397 //On to BLE_ON 398 //Process stop or disable pending 399 //Check if all services are stopped if so, do cleanup 400 synchronized (mProfileServicesState) { 401 Iterator<Map.Entry<String,Integer>> i = mProfileServicesState.entrySet().iterator(); 402 while (i.hasNext()) { 403 Map.Entry<String,Integer> entry = i.next(); 404 debugLog("Service: " + entry.getKey()); 405 if (entry.getKey().equals("com.android.bluetooth.gatt.GattService")) { 406 debugLog("Skip GATT service - already started before"); 407 continue; 408 } 409 if (BluetoothAdapter.STATE_OFF != entry.getValue()) { 410 debugLog("onProfileServiceStateChange() - Profile still running: " 411 + entry.getKey()); 412 return; 413 } 414 } 415 } 416 debugLog("onProfileServiceStateChange() - All profile services stopped..."); 417 //Send message to state machine 418 mProfilesStarted=false; 419 mAdapterStateMachine.sendMessage(mAdapterStateMachine.obtainMessage(AdapterState.BREDR_STOPPED)); 420 421 } else if (isTurningOn) { 422 updateInteropDatabase(); 423 424 //Process start pending 425 //Check if all services are started if so, update state 426 synchronized (mProfileServicesState) { 427 Iterator<Map.Entry<String,Integer>> i = mProfileServicesState.entrySet().iterator(); 428 while (i.hasNext()) { 429 Map.Entry<String,Integer> entry = i.next(); 430 debugLog("Service: " + entry.getKey()); 431 if (entry.getKey().equals("com.android.bluetooth.gatt.GattService")) { 432 debugLog("Skip GATT service - already started before"); 433 continue; 434 } 435 if (BluetoothAdapter.STATE_ON != entry.getValue()) { 436 debugLog("onProfileServiceStateChange() - Profile still not running:" 437 + entry.getKey()); 438 return; 439 } 440 } 441 } 442 debugLog("onProfileServiceStateChange() - All profile services started."); 443 mProfilesStarted=true; 444 //Send message to state machine 445 mAdapterStateMachine.sendMessage(mAdapterStateMachine.obtainMessage(AdapterState.BREDR_STARTED)); 446 } 447 } 448 449 private void updateInteropDatabase() { 450 interopDatabaseClearNative(); 451 452 String interop_string = Settings.Global.getString(getContentResolver(), 453 Settings.Global.BLUETOOTH_INTEROPERABILITY_LIST); 454 if (interop_string == null) return; 455 Log.d(TAG, "updateInteropDatabase: [" + interop_string + "]"); 456 457 String[] entries = interop_string.split(";"); 458 for (String entry : entries) { 459 String[] tokens = entry.split(","); 460 if (tokens.length != 2) continue; 461 462 // Get feature 463 int feature = 0; 464 try { 465 feature = Integer.parseInt(tokens[1]); 466 } catch (NumberFormatException e) { 467 Log.e(TAG, "updateInteropDatabase: Invalid feature '" + tokens[1] + "'"); 468 continue; 469 } 470 471 // Get address bytes and length 472 int length = (tokens[0].length() + 1) / 3; 473 if (length < 1 || length > 6) { 474 Log.e(TAG, "updateInteropDatabase: Malformed address string '" + tokens[0] + "'"); 475 continue; 476 } 477 478 byte[] addr = new byte[6]; 479 int offset = 0; 480 for (int i = 0; i < tokens[0].length(); ) { 481 if (tokens[0].charAt(i) == ':') { 482 i += 1; 483 } else { 484 try { 485 addr[offset++] = (byte) Integer.parseInt(tokens[0].substring(i, i + 2), 16); 486 } catch (NumberFormatException e) { 487 offset = 0; 488 break; 489 } 490 i += 2; 491 } 492 } 493 494 // Check if address was parsed ok, otherwise, move on... 495 if (offset == 0) continue; 496 497 // Add entry 498 interopDatabaseAddNative(feature, addr, length); 499 } 500 } 501 502 @Override 503 public void onCreate() { 504 super.onCreate(); 505 debugLog("onCreate()"); 506 mBinder = new AdapterServiceBinder(this); 507 mAdapterProperties = new AdapterProperties(this); 508 mAdapterStateMachine = AdapterState.make(this, mAdapterProperties); 509 mJniCallbacks = new JniCallbacks(mAdapterStateMachine, mAdapterProperties); 510 initNative(); 511 mNativeAvailable=true; 512 mCallbacks = new RemoteCallbackList<IBluetoothCallback>(); 513 //Load the name and address 514 getAdapterPropertyNative(AbstractionLayer.BT_PROPERTY_BDADDR); 515 getAdapterPropertyNative(AbstractionLayer.BT_PROPERTY_BDNAME); 516 mAlarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); 517 mPowerManager = (PowerManager) getSystemService(Context.POWER_SERVICE); 518 mBatteryStats = IBatteryStats.Stub.asInterface(ServiceManager.getService( 519 BatteryStats.SERVICE_NAME)); 520 521 mSdpManager = SdpManager.init(this); 522 registerReceiver(mAlarmBroadcastReceiver, new IntentFilter(ACTION_ALARM_WAKEUP)); 523 mProfileObserver = new ProfileObserver(getApplicationContext(), this, new Handler()); 524 mProfileObserver.start(); 525 } 526 527 @Override 528 public IBinder onBind(Intent intent) { 529 debugLog("onBind()"); 530 return mBinder; 531 } 532 public boolean onUnbind(Intent intent) { 533 debugLog("onUnbind() - calling cleanup"); 534 cleanup(); 535 return super.onUnbind(intent); 536 } 537 538 public void onDestroy() { 539 debugLog("onDestroy()"); 540 mProfileObserver.stop(); 541 } 542 543 void BleOnProcessStart() { 544 debugLog("BleOnProcessStart()"); 545 546 if (getApplicationContext().getResources().getBoolean( 547 R.bool.config_bluetooth_reload_supported_profiles_when_enabled)) { 548 Config.init(getApplicationContext()); 549 } 550 551 Class[] supportedProfileServices = Config.getSupportedProfiles(); 552 //Initialize data objects 553 for (int i=0; i < supportedProfileServices.length;i++) { 554 mProfileServicesState.put(supportedProfileServices[i].getName(),BluetoothAdapter.STATE_OFF); 555 } 556 557 // Reset |mRemoteDevices| whenever BLE is turned off then on 558 // This is to replace the fact that |mRemoteDevices| was 559 // reinitialized in previous code. 560 // 561 // TODO(apanicke): The reason is unclear but 562 // I believe it is to clear the variable every time BLE was 563 // turned off then on. The same effect can be achieved by 564 // calling cleanup but this may not be necessary at all 565 // We should figure out why this is needed later 566 mRemoteDevices.cleanup(); 567 mAdapterProperties.init(mRemoteDevices); 568 569 debugLog("BleOnProcessStart() - Make Bond State Machine"); 570 mBondStateMachine = BondStateMachine.make(this, mAdapterProperties, mRemoteDevices); 571 572 mJniCallbacks.init(mBondStateMachine,mRemoteDevices); 573 574 try { 575 mBatteryStats.noteResetBleScan(); 576 } catch (RemoteException e) { 577 // Ignore. 578 } 579 580 //FIXME: Set static instance here??? 581 setAdapterService(this); 582 583 //Start Gatt service 584 setGattProfileServiceState(supportedProfileServices,BluetoothAdapter.STATE_ON); 585 } 586 587 void startCoreServices() 588 { 589 debugLog("startCoreServices()"); 590 Class[] supportedProfileServices = Config.getSupportedProfiles(); 591 592 //Start profile services 593 if (!mProfilesStarted && supportedProfileServices.length >0) { 594 //Startup all profile services 595 setProfileServiceState(supportedProfileServices,BluetoothAdapter.STATE_ON); 596 }else { 597 debugLog("startCoreProfiles(): Profile Services alreay started"); 598 mAdapterStateMachine.sendMessage(mAdapterStateMachine.obtainMessage(AdapterState.BREDR_STARTED)); 599 } 600 } 601 602 void startBluetoothDisable() { 603 mAdapterStateMachine.sendMessage(mAdapterStateMachine.obtainMessage(AdapterState.BEGIN_DISABLE)); 604 } 605 606 boolean stopProfileServices() { 607 Class[] supportedProfileServices = Config.getSupportedProfiles(); 608 if (mProfilesStarted && supportedProfileServices.length>0) { 609 setProfileServiceState(supportedProfileServices,BluetoothAdapter.STATE_OFF); 610 return true; 611 } 612 debugLog("stopProfileServices() - No profiles services to stop or already stopped."); 613 return false; 614 } 615 616 boolean stopGattProfileService() { 617 //TODO: can optimize this instead of looping around all supported profiles 618 debugLog("stopGattProfileService()"); 619 Class[] supportedProfileServices = Config.getSupportedProfiles(); 620 621 setGattProfileServiceState(supportedProfileServices,BluetoothAdapter.STATE_OFF); 622 return true; 623 } 624 625 626 void updateAdapterState(int prevState, int newState){ 627 if (mCallbacks !=null) { 628 int n=mCallbacks.beginBroadcast(); 629 debugLog("updateAdapterState() - Broadcasting state to " + n + " receivers."); 630 for (int i=0; i <n;i++) { 631 try { 632 mCallbacks.getBroadcastItem(i).onBluetoothStateChange(prevState,newState); 633 } catch (RemoteException e) { 634 debugLog("updateAdapterState() - Callback #" + i + " failed (" + e + ")"); 635 } 636 } 637 mCallbacks.finishBroadcast(); 638 } 639 } 640 641 void cleanup () { 642 debugLog("cleanup()"); 643 if (mCleaningUp) { 644 errorLog("cleanup() - Service already starting to cleanup, ignoring request..."); 645 return; 646 } 647 648 mCleaningUp = true; 649 650 unregisterReceiver(mAlarmBroadcastReceiver); 651 652 if (mPendingAlarm != null) { 653 mAlarmManager.cancel(mPendingAlarm); 654 mPendingAlarm = null; 655 } 656 657 // This wake lock release may also be called concurrently by 658 // {@link #releaseWakeLock(String lockName)}, so a synchronization is needed here. 659 synchronized (this) { 660 if (mWakeLock != null) { 661 mWakeLock.release(); 662 mWakeLock = null; 663 } 664 } 665 666 if (mAdapterStateMachine != null) { 667 mAdapterStateMachine.doQuit(); 668 mAdapterStateMachine.cleanup(); 669 } 670 671 if (mBondStateMachine != null) { 672 mBondStateMachine.doQuit(); 673 mBondStateMachine.cleanup(); 674 } 675 676 if (mRemoteDevices != null) { 677 mRemoteDevices.cleanup(); 678 } 679 680 if(mSdpManager != null) { 681 mSdpManager.cleanup(); 682 mSdpManager = null; 683 } 684 685 if (mNativeAvailable) { 686 debugLog("cleanup() - Cleaning up adapter native"); 687 cleanupNative(); 688 mNativeAvailable=false; 689 } 690 691 if (mAdapterProperties != null) { 692 mAdapterProperties.cleanup(); 693 } 694 695 if (mJniCallbacks != null) { 696 mJniCallbacks.cleanup(); 697 } 698 699 if (mProfileServicesState != null) { 700 mProfileServicesState.clear(); 701 } 702 703 clearAdapterService(); 704 705 if (mBinder != null) { 706 mBinder.cleanup(); 707 mBinder = null; //Do not remove. Otherwise Binder leak! 708 } 709 710 if (mCallbacks !=null) { 711 mCallbacks.kill(); 712 } 713 714 System.exit(0); 715 } 716 717 private static final int MESSAGE_PROFILE_SERVICE_STATE_CHANGED =1; 718 private static final int MESSAGE_PROFILE_CONNECTION_STATE_CHANGED=20; 719 private static final int MESSAGE_CONNECT_OTHER_PROFILES = 30; 720 private static final int MESSAGE_PROFILE_INIT_PRIORITIES=40; 721 private static final int CONNECT_OTHER_PROFILES_TIMEOUT= 6000; 722 723 private final Handler mHandler = new Handler() { 724 @Override 725 public void handleMessage(Message msg) { 726 debugLog("handleMessage() - Message: " + msg.what); 727 728 switch (msg.what) { 729 case MESSAGE_PROFILE_SERVICE_STATE_CHANGED: { 730 debugLog("handleMessage() - MESSAGE_PROFILE_SERVICE_STATE_CHANGED"); 731 processProfileServiceStateChanged((String) msg.obj, msg.arg1); 732 } 733 break; 734 case MESSAGE_PROFILE_CONNECTION_STATE_CHANGED: { 735 debugLog( "handleMessage() - MESSAGE_PROFILE_CONNECTION_STATE_CHANGED"); 736 processProfileStateChanged((BluetoothDevice) msg.obj, msg.arg1,msg.arg2, msg.getData().getInt("prevState",BluetoothAdapter.ERROR)); 737 } 738 break; 739 case MESSAGE_PROFILE_INIT_PRIORITIES: { 740 debugLog( "handleMessage() - MESSAGE_PROFILE_INIT_PRIORITIES"); 741 ParcelUuid[] mUuids = new ParcelUuid[msg.arg1]; 742 for(int i=0; i<mUuids.length; i++) { 743 mUuids[i] = msg.getData().getParcelable("uuids" + i); 744 } 745 processInitProfilePriorities((BluetoothDevice) msg.obj, mUuids); 746 } 747 break; 748 case MESSAGE_CONNECT_OTHER_PROFILES: { 749 debugLog( "handleMessage() - MESSAGE_CONNECT_OTHER_PROFILES"); 750 processConnectOtherProfiles((BluetoothDevice) msg.obj,msg.arg1); 751 } 752 break; 753 } 754 } 755 }; 756 757 @SuppressWarnings("rawtypes") 758 private void setGattProfileServiceState(Class[] services, int state) { 759 if (state != BluetoothAdapter.STATE_ON && state != BluetoothAdapter.STATE_OFF) { 760 Log.w(TAG,"setGattProfileServiceState(): invalid state...Leaving..."); 761 return; 762 } 763 764 int expectedCurrentState= BluetoothAdapter.STATE_OFF; 765 int pendingState = BluetoothAdapter.STATE_TURNING_ON; 766 767 if (state == BluetoothAdapter.STATE_OFF) { 768 expectedCurrentState= BluetoothAdapter.STATE_ON; 769 pendingState = BluetoothAdapter.STATE_TURNING_OFF; 770 } 771 772 for (int i=0; i <services.length;i++) { 773 String serviceName = services[i].getName(); 774 String simpleName = services[i].getSimpleName(); 775 776 if (simpleName.equals("GattService")) { 777 Integer serviceState = mProfileServicesState.get(serviceName); 778 779 if(serviceState != null && serviceState != expectedCurrentState) { 780 debugLog("setProfileServiceState() - Unable to " 781 + (state == BluetoothAdapter.STATE_OFF ? "start" : "stop" ) 782 + " service " + serviceName 783 + ". Invalid state: " + serviceState); 784 continue; 785 } 786 debugLog("setProfileServiceState() - " 787 + (state == BluetoothAdapter.STATE_OFF ? "Stopping" : "Starting") 788 + " service " + serviceName); 789 790 mProfileServicesState.put(serviceName,pendingState); 791 Intent intent = new Intent(this,services[i]); 792 intent.putExtra(EXTRA_ACTION,ACTION_SERVICE_STATE_CHANGED); 793 intent.putExtra(BluetoothAdapter.EXTRA_STATE,state); 794 startService(intent); 795 return; 796 } 797 } 798 } 799 800 801 @SuppressWarnings("rawtypes") 802 private void setProfileServiceState(Class[] services, int state) { 803 if (state != BluetoothAdapter.STATE_ON && state != BluetoothAdapter.STATE_OFF) { 804 debugLog("setProfileServiceState() - Invalid state, leaving..."); 805 return; 806 } 807 808 int expectedCurrentState= BluetoothAdapter.STATE_OFF; 809 int pendingState = BluetoothAdapter.STATE_TURNING_ON; 810 if (state == BluetoothAdapter.STATE_OFF) { 811 expectedCurrentState= BluetoothAdapter.STATE_ON; 812 pendingState = BluetoothAdapter.STATE_TURNING_OFF; 813 } 814 815 for (int i=0; i <services.length;i++) { 816 String serviceName = services[i].getName(); 817 String simpleName = services[i].getSimpleName(); 818 819 if (simpleName.equals("GattService")) continue; 820 821 Integer serviceState = mProfileServicesState.get(serviceName); 822 if(serviceState != null && serviceState != expectedCurrentState) { 823 debugLog("setProfileServiceState() - Unable to " 824 + (state == BluetoothAdapter.STATE_OFF ? "start" : "stop" ) 825 + " service " + serviceName 826 + ". Invalid state: " + serviceState); 827 continue; 828 } 829 830 debugLog("setProfileServiceState() - " 831 + (state == BluetoothAdapter.STATE_OFF ? "Stopping" : "Starting") 832 + " service " + serviceName); 833 834 mProfileServicesState.put(serviceName,pendingState); 835 Intent intent = new Intent(this,services[i]); 836 intent.putExtra(EXTRA_ACTION,ACTION_SERVICE_STATE_CHANGED); 837 intent.putExtra(BluetoothAdapter.EXTRA_STATE,state); 838 startService(intent); 839 } 840 } 841 842 private boolean isAvailable() { 843 return !mCleaningUp; 844 } 845 846 /** 847 * Handlers for incoming service calls 848 */ 849 private AdapterServiceBinder mBinder; 850 851 /** 852 * The Binder implementation must be declared to be a static class, with 853 * the AdapterService instance passed in the constructor. Furthermore, 854 * when the AdapterService shuts down, the reference to the AdapterService 855 * must be explicitly removed. 856 * 857 * Otherwise, a memory leak can occur from repeated starting/stopping the 858 * service...Please refer to android.os.Binder for further details on 859 * why an inner instance class should be avoided. 860 * 861 */ 862 private static class AdapterServiceBinder extends IBluetooth.Stub { 863 private AdapterService mService; 864 865 public AdapterServiceBinder(AdapterService svc) { 866 mService = svc; 867 } 868 public boolean cleanup() { 869 mService = null; 870 return true; 871 } 872 873 public AdapterService getService() { 874 if (mService != null && mService.isAvailable()) { 875 return mService; 876 } 877 return null; 878 } 879 public boolean isEnabled() { 880 // don't check caller, may be called from system UI 881 AdapterService service = getService(); 882 if (service == null) return false; 883 return service.isEnabled(); 884 } 885 886 public int getState() { 887 // don't check caller, may be called from system UI 888 AdapterService service = getService(); 889 if (service == null) return BluetoothAdapter.STATE_OFF; 890 return service.getState(); 891 } 892 893 public boolean enable() { 894 if ((Binder.getCallingUid() != Process.SYSTEM_UID) && 895 (!Utils.checkCaller())) { 896 Log.w(TAG, "enable() - Not allowed for non-active user and non system user"); 897 return false; 898 } 899 AdapterService service = getService(); 900 if (service == null) return false; 901 return service.enable(); 902 } 903 904 public boolean enableNoAutoConnect() { 905 if ((Binder.getCallingUid() != Process.SYSTEM_UID) && 906 (!Utils.checkCaller())) { 907 Log.w(TAG, "enableNoAuto() - Not allowed for non-active user and non system user"); 908 return false; 909 } 910 911 AdapterService service = getService(); 912 if (service == null) return false; 913 return service.enableNoAutoConnect(); 914 } 915 916 public boolean disable() { 917 if ((Binder.getCallingUid() != Process.SYSTEM_UID) && 918 (!Utils.checkCaller())) { 919 Log.w(TAG, "disable() - Not allowed for non-active user and non system user"); 920 return false; 921 } 922 923 AdapterService service = getService(); 924 if (service == null) return false; 925 return service.disable(); 926 } 927 928 public String getAddress() { 929 if ((Binder.getCallingUid() != Process.SYSTEM_UID) && 930 (!Utils.checkCallerAllowManagedProfiles(mService))) { 931 Log.w(TAG, "getAddress() - Not allowed for non-active user and non system user"); 932 return null; 933 } 934 935 AdapterService service = getService(); 936 if (service == null) return null; 937 return service.getAddress(); 938 } 939 940 public ParcelUuid[] getUuids() { 941 if (!Utils.checkCaller()) { 942 Log.w(TAG, "getUuids() - Not allowed for non-active user"); 943 return new ParcelUuid[0]; 944 } 945 946 AdapterService service = getService(); 947 if (service == null) return new ParcelUuid[0]; 948 return service.getUuids(); 949 } 950 951 public String getName() { 952 if ((Binder.getCallingUid() != Process.SYSTEM_UID) && 953 (!Utils.checkCaller())) { 954 Log.w(TAG, "getName() - Not allowed for non-active user and non system user"); 955 return null; 956 } 957 958 AdapterService service = getService(); 959 if (service == null) return null; 960 return service.getName(); 961 } 962 963 public boolean setName(String name) { 964 if (!Utils.checkCaller()) { 965 Log.w(TAG, "setName() - Not allowed for non-active user"); 966 return false; 967 } 968 969 AdapterService service = getService(); 970 if (service == null) return false; 971 return service.setName(name); 972 } 973 974 public int getScanMode() { 975 if (!Utils.checkCallerAllowManagedProfiles(mService)) { 976 Log.w(TAG, "getScanMode() - Not allowed for non-active user"); 977 return BluetoothAdapter.SCAN_MODE_NONE; 978 } 979 980 AdapterService service = getService(); 981 if (service == null) return BluetoothAdapter.SCAN_MODE_NONE; 982 return service.getScanMode(); 983 } 984 985 public boolean setScanMode(int mode, int duration) { 986 if (!Utils.checkCaller()) { 987 Log.w(TAG, "setScanMode() - Not allowed for non-active user"); 988 return false; 989 } 990 991 AdapterService service = getService(); 992 if (service == null) return false; 993 return service.setScanMode(mode,duration); 994 } 995 996 public int getDiscoverableTimeout() { 997 if (!Utils.checkCaller()) { 998 Log.w(TAG, "getDiscoverableTimeout() - Not allowed for non-active user"); 999 return 0; 1000 } 1001 1002 AdapterService service = getService(); 1003 if (service == null) return 0; 1004 return service.getDiscoverableTimeout(); 1005 } 1006 1007 public boolean setDiscoverableTimeout(int timeout) { 1008 if (!Utils.checkCaller()) { 1009 Log.w(TAG, "setDiscoverableTimeout() - Not allowed for non-active user"); 1010 return false; 1011 } 1012 1013 AdapterService service = getService(); 1014 if (service == null) return false; 1015 return service.setDiscoverableTimeout(timeout); 1016 } 1017 1018 public boolean startDiscovery() { 1019 if (!Utils.checkCaller()) { 1020 Log.w(TAG, "startDiscovery() - Not allowed for non-active user"); 1021 return false; 1022 } 1023 1024 AdapterService service = getService(); 1025 if (service == null) return false; 1026 return service.startDiscovery(); 1027 } 1028 1029 public boolean cancelDiscovery() { 1030 if (!Utils.checkCaller()) { 1031 Log.w(TAG, "cancelDiscovery() - Not allowed for non-active user"); 1032 return false; 1033 } 1034 1035 AdapterService service = getService(); 1036 if (service == null) return false; 1037 return service.cancelDiscovery(); 1038 } 1039 public boolean isDiscovering() { 1040 if (!Utils.checkCallerAllowManagedProfiles(mService)) { 1041 Log.w(TAG, "isDiscovering() - Not allowed for non-active user"); 1042 return false; 1043 } 1044 1045 AdapterService service = getService(); 1046 if (service == null) return false; 1047 return service.isDiscovering(); 1048 } 1049 1050 public BluetoothDevice[] getBondedDevices() { 1051 // don't check caller, may be called from system UI 1052 AdapterService service = getService(); 1053 if (service == null) return new BluetoothDevice[0]; 1054 return service.getBondedDevices(); 1055 } 1056 1057 public int getAdapterConnectionState() { 1058 // don't check caller, may be called from system UI 1059 AdapterService service = getService(); 1060 if (service == null) return BluetoothAdapter.STATE_DISCONNECTED; 1061 return service.getAdapterConnectionState(); 1062 } 1063 1064 public int getProfileConnectionState(int profile) { 1065 if (!Utils.checkCallerAllowManagedProfiles(mService)) { 1066 Log.w(TAG, "getProfileConnectionState- Not allowed for non-active user"); 1067 return BluetoothProfile.STATE_DISCONNECTED; 1068 } 1069 1070 AdapterService service = getService(); 1071 if (service == null) return BluetoothProfile.STATE_DISCONNECTED; 1072 return service.getProfileConnectionState(profile); 1073 } 1074 1075 public boolean createBond(BluetoothDevice device, int transport) { 1076 if (!Utils.checkCaller()) { 1077 Log.w(TAG, "createBond() - Not allowed for non-active user"); 1078 return false; 1079 } 1080 1081 AdapterService service = getService(); 1082 if (service == null) return false; 1083 return service.createBond(device, transport, null); 1084 } 1085 1086 public boolean createBondOutOfBand(BluetoothDevice device, int transport, OobData oobData) { 1087 if (!Utils.checkCaller()) { 1088 Log.w(TAG, "createBondOutOfBand() - Not allowed for non-active user"); 1089 return false; 1090 } 1091 1092 AdapterService service = getService(); 1093 if (service == null) return false; 1094 return service.createBond(device, transport, oobData); 1095 } 1096 1097 public boolean cancelBondProcess(BluetoothDevice device) { 1098 if (!Utils.checkCaller()) { 1099 Log.w(TAG, "cancelBondProcess() - Not allowed for non-active user"); 1100 return false; 1101 } 1102 1103 AdapterService service = getService(); 1104 if (service == null) return false; 1105 return service.cancelBondProcess(device); 1106 } 1107 1108 public boolean removeBond(BluetoothDevice device) { 1109 if (!Utils.checkCaller()) { 1110 Log.w(TAG, "removeBond() - Not allowed for non-active user"); 1111 return false; 1112 } 1113 1114 AdapterService service = getService(); 1115 if (service == null) return false; 1116 return service.removeBond(device); 1117 } 1118 1119 public int getBondState(BluetoothDevice device) { 1120 // don't check caller, may be called from system UI 1121 AdapterService service = getService(); 1122 if (service == null) return BluetoothDevice.BOND_NONE; 1123 return service.getBondState(device); 1124 } 1125 1126 public int getConnectionState(BluetoothDevice device) { 1127 AdapterService service = getService(); 1128 if (service == null) return 0; 1129 return service.getConnectionState(device); 1130 } 1131 1132 public String getRemoteName(BluetoothDevice device) { 1133 if (!Utils.checkCallerAllowManagedProfiles(mService)) { 1134 Log.w(TAG, "getRemoteName() - Not allowed for non-active user"); 1135 return null; 1136 } 1137 1138 AdapterService service = getService(); 1139 if (service == null) return null; 1140 return service.getRemoteName(device); 1141 } 1142 1143 public int getRemoteType(BluetoothDevice device) { 1144 if (!Utils.checkCallerAllowManagedProfiles(mService)) { 1145 Log.w(TAG, "getRemoteType() - Not allowed for non-active user"); 1146 return BluetoothDevice.DEVICE_TYPE_UNKNOWN; 1147 } 1148 1149 AdapterService service = getService(); 1150 if (service == null) return BluetoothDevice.DEVICE_TYPE_UNKNOWN; 1151 return service.getRemoteType(device); 1152 } 1153 1154 public String getRemoteAlias(BluetoothDevice device) { 1155 if (!Utils.checkCallerAllowManagedProfiles(mService)) { 1156 Log.w(TAG, "getRemoteAlias() - Not allowed for non-active user"); 1157 return null; 1158 } 1159 1160 AdapterService service = getService(); 1161 if (service == null) return null; 1162 return service.getRemoteAlias(device); 1163 } 1164 1165 public boolean setRemoteAlias(BluetoothDevice device, String name) { 1166 if (!Utils.checkCaller()) { 1167 Log.w(TAG, "setRemoteAlias() - Not allowed for non-active user"); 1168 return false; 1169 } 1170 1171 AdapterService service = getService(); 1172 if (service == null) return false; 1173 return service.setRemoteAlias(device, name); 1174 } 1175 1176 public int getRemoteClass(BluetoothDevice device) { 1177 if (!Utils.checkCallerAllowManagedProfiles(mService)) { 1178 Log.w(TAG, "getRemoteClass() - Not allowed for non-active user"); 1179 return 0; 1180 } 1181 1182 AdapterService service = getService(); 1183 if (service == null) return 0; 1184 return service.getRemoteClass(device); 1185 } 1186 1187 public ParcelUuid[] getRemoteUuids(BluetoothDevice device) { 1188 if (!Utils.checkCallerAllowManagedProfiles(mService)) { 1189 Log.w(TAG, "getRemoteUuids() - Not allowed for non-active user"); 1190 return new ParcelUuid[0]; 1191 } 1192 1193 AdapterService service = getService(); 1194 if (service == null) return new ParcelUuid[0]; 1195 return service.getRemoteUuids(device); 1196 } 1197 1198 public boolean fetchRemoteUuids(BluetoothDevice device) { 1199 if (!Utils.checkCallerAllowManagedProfiles(mService)) { 1200 Log.w(TAG, "fetchRemoteUuids() - Not allowed for non-active user"); 1201 return false; 1202 } 1203 1204 AdapterService service = getService(); 1205 if (service == null) return false; 1206 return service.fetchRemoteUuids(device); 1207 } 1208 1209 1210 1211 public boolean setPin(BluetoothDevice device, boolean accept, int len, byte[] pinCode) { 1212 if (!Utils.checkCaller()) { 1213 Log.w(TAG, "setPin() - Not allowed for non-active user"); 1214 return false; 1215 } 1216 1217 AdapterService service = getService(); 1218 if (service == null) return false; 1219 return service.setPin(device, accept, len, pinCode); 1220 } 1221 1222 public boolean setPasskey(BluetoothDevice device, boolean accept, int len, byte[] passkey) { 1223 if (!Utils.checkCaller()) { 1224 Log.w(TAG, "setPasskey() - Not allowed for non-active user"); 1225 return false; 1226 } 1227 1228 AdapterService service = getService(); 1229 if (service == null) return false; 1230 return service.setPasskey(device, accept, len, passkey); 1231 } 1232 1233 public boolean setPairingConfirmation(BluetoothDevice device, boolean accept) { 1234 if (!Utils.checkCaller()) { 1235 Log.w(TAG, "setPairingConfirmation() - Not allowed for non-active user"); 1236 return false; 1237 } 1238 1239 AdapterService service = getService(); 1240 if (service == null) return false; 1241 return service.setPairingConfirmation(device, accept); 1242 } 1243 1244 public int getPhonebookAccessPermission(BluetoothDevice device) { 1245 if (!Utils.checkCaller()) { 1246 Log.w(TAG, "getPhonebookAccessPermission() - Not allowed for non-active user"); 1247 return BluetoothDevice.ACCESS_UNKNOWN; 1248 } 1249 1250 AdapterService service = getService(); 1251 if (service == null) return BluetoothDevice.ACCESS_UNKNOWN; 1252 return service.getPhonebookAccessPermission(device); 1253 } 1254 1255 public boolean setPhonebookAccessPermission(BluetoothDevice device, int value) { 1256 if (!Utils.checkCaller()) { 1257 Log.w(TAG, "setPhonebookAccessPermission() - Not allowed for non-active user"); 1258 return false; 1259 } 1260 1261 AdapterService service = getService(); 1262 if (service == null) return false; 1263 return service.setPhonebookAccessPermission(device, value); 1264 } 1265 1266 public int getMessageAccessPermission(BluetoothDevice device) { 1267 if (!Utils.checkCaller()) { 1268 Log.w(TAG, "getMessageAccessPermission() - Not allowed for non-active user"); 1269 return BluetoothDevice.ACCESS_UNKNOWN; 1270 } 1271 1272 AdapterService service = getService(); 1273 if (service == null) return BluetoothDevice.ACCESS_UNKNOWN; 1274 return service.getMessageAccessPermission(device); 1275 } 1276 1277 public boolean setMessageAccessPermission(BluetoothDevice device, int value) { 1278 if (!Utils.checkCaller()) { 1279 Log.w(TAG, "setMessageAccessPermission() - Not allowed for non-active user"); 1280 return false; 1281 } 1282 1283 AdapterService service = getService(); 1284 if (service == null) return false; 1285 return service.setMessageAccessPermission(device, value); 1286 } 1287 1288 public int getSimAccessPermission(BluetoothDevice device) { 1289 if (!Utils.checkCaller()) { 1290 Log.w(TAG, "getSimAccessPermission() - Not allowed for non-active user"); 1291 return BluetoothDevice.ACCESS_UNKNOWN; 1292 } 1293 1294 AdapterService service = getService(); 1295 if (service == null) return BluetoothDevice.ACCESS_UNKNOWN; 1296 return service.getSimAccessPermission(device); 1297 } 1298 1299 public boolean setSimAccessPermission(BluetoothDevice device, int value) { 1300 if (!Utils.checkCaller()) { 1301 Log.w(TAG, "setSimAccessPermission() - Not allowed for non-active user"); 1302 return false; 1303 } 1304 1305 AdapterService service = getService(); 1306 if (service == null) return false; 1307 return service.setSimAccessPermission(device, value); 1308 } 1309 1310 public void sendConnectionStateChange(BluetoothDevice 1311 device, int profile, int state, int prevState) { 1312 AdapterService service = getService(); 1313 if (service == null) return; 1314 service.sendConnectionStateChange(device, profile, state, prevState); 1315 } 1316 1317 public ParcelFileDescriptor connectSocket(BluetoothDevice device, int type, 1318 ParcelUuid uuid, int port, int flag) { 1319 if (!Utils.checkCallerAllowManagedProfiles(mService)) { 1320 Log.w(TAG, "connectSocket() - Not allowed for non-active user"); 1321 return null; 1322 } 1323 1324 AdapterService service = getService(); 1325 if (service == null) return null; 1326 return service.connectSocket(device, type, uuid, port, flag); 1327 } 1328 1329 public ParcelFileDescriptor createSocketChannel(int type, String serviceName, 1330 ParcelUuid uuid, int port, int flag) { 1331 if (!Utils.checkCallerAllowManagedProfiles(mService)) { 1332 Log.w(TAG, "createSocketChannel() - Not allowed for non-active user"); 1333 return null; 1334 } 1335 1336 AdapterService service = getService(); 1337 if (service == null) return null; 1338 return service.createSocketChannel(type, serviceName, uuid, port, flag); 1339 } 1340 public boolean sdpSearch(BluetoothDevice device, ParcelUuid uuid) { 1341 if (!Utils.checkCaller()) { 1342 Log.w(TAG,"sdpSea(): not allowed for non-active user"); 1343 return false; 1344 } 1345 1346 AdapterService service = getService(); 1347 if (service == null) return false; 1348 return service.sdpSearch(device,uuid); 1349 } 1350 1351 public boolean configHciSnoopLog(boolean enable) { 1352 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 1353 EventLog.writeEvent(0x534e4554 /* SNET */, "Bluetooth", Binder.getCallingUid(), 1354 "configHciSnoopLog() - Not allowed for non-active user b/18643224"); 1355 return false; 1356 } 1357 1358 AdapterService service = getService(); 1359 if (service == null) return false; 1360 return service.configHciSnoopLog(enable); 1361 } 1362 1363 public boolean factoryReset() { 1364 AdapterService service = getService(); 1365 if (service == null) return false; 1366 service.disable(); 1367 return service.factoryReset(); 1368 1369 } 1370 1371 public void registerCallback(IBluetoothCallback cb) { 1372 AdapterService service = getService(); 1373 if (service == null) return ; 1374 service.registerCallback(cb); 1375 } 1376 1377 public void unregisterCallback(IBluetoothCallback cb) { 1378 AdapterService service = getService(); 1379 if (service == null) return ; 1380 service.unregisterCallback(cb); 1381 } 1382 1383 public boolean isMultiAdvertisementSupported() { 1384 AdapterService service = getService(); 1385 if (service == null) return false; 1386 return service.isMultiAdvertisementSupported(); 1387 } 1388 1389 public boolean isPeripheralModeSupported() { 1390 AdapterService service = getService(); 1391 if (service == null) return false; 1392 return service.isPeripheralModeSupported(); 1393 } 1394 1395 public boolean isOffloadedFilteringSupported() { 1396 AdapterService service = getService(); 1397 if (service == null) return false; 1398 int val = service.getNumOfOffloadedScanFilterSupported(); 1399 return (val >= MIN_OFFLOADED_FILTERS); 1400 } 1401 1402 public boolean isOffloadedScanBatchingSupported() { 1403 AdapterService service = getService(); 1404 if (service == null) return false; 1405 int val = service.getOffloadedScanResultStorage(); 1406 return (val >= MIN_OFFLOADED_SCAN_STORAGE_BYTES); 1407 } 1408 1409 public boolean isActivityAndEnergyReportingSupported() { 1410 AdapterService service = getService(); 1411 if (service == null) return false; 1412 return service.isActivityAndEnergyReportingSupported(); 1413 } 1414 1415 public void getActivityEnergyInfoFromController() { 1416 AdapterService service = getService(); 1417 if (service == null) return; 1418 service.getActivityEnergyInfoFromController(); 1419 } 1420 1421 public BluetoothActivityEnergyInfo reportActivityInfo() { 1422 AdapterService service = getService(); 1423 if (service == null) return null; 1424 return service.reportActivityInfo(); 1425 } 1426 1427 public void onLeServiceUp(){ 1428 AdapterService service = getService(); 1429 if (service == null) return; 1430 service.onLeServiceUp(); 1431 } 1432 1433 public void onBrEdrDown(){ 1434 AdapterService service = getService(); 1435 if (service == null) return; 1436 service.onBrEdrDown(); 1437 } 1438 1439 public void dump(FileDescriptor fd, String[] args) { 1440 PrintWriter writer = new PrintWriter(new FileOutputStream(fd)); 1441 AdapterService service = getService(); 1442 if (service == null) return; 1443 service.dump(fd, writer, args); 1444 } 1445 }; 1446 1447 // ----API Methods-------- 1448 1449 boolean isEnabled() { 1450 enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission"); 1451 return mAdapterProperties.getState() == BluetoothAdapter.STATE_ON; 1452 } 1453 1454 int getState() { 1455 enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission"); 1456 if (mAdapterProperties != null) return mAdapterProperties.getState(); 1457 return BluetoothAdapter.STATE_OFF; 1458 } 1459 1460 boolean enable() { 1461 return enable (false); 1462 } 1463 1464 public boolean enableNoAutoConnect() { 1465 return enable (true); 1466 } 1467 1468 public synchronized boolean enable(boolean quietMode) { 1469 enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM, "Need BLUETOOTH ADMIN permission"); 1470 1471 debugLog("enable() - Enable called with quiet mode status = " + mQuietmode); 1472 mQuietmode = quietMode; 1473 Message m = mAdapterStateMachine.obtainMessage(AdapterState.BLE_TURN_ON); 1474 mAdapterStateMachine.sendMessage(m); 1475 mBluetoothStartTime = System.currentTimeMillis(); 1476 return true; 1477 } 1478 1479 boolean disable() { 1480 enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM, "Need BLUETOOTH ADMIN permission"); 1481 1482 debugLog("disable() called..."); 1483 Message m = mAdapterStateMachine.obtainMessage(AdapterState.BLE_TURN_OFF); 1484 mAdapterStateMachine.sendMessage(m); 1485 return true; 1486 } 1487 1488 String getAddress() { 1489 enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission"); 1490 1491 String addrString = null; 1492 byte[] address = mAdapterProperties.getAddress(); 1493 return Utils.getAddressStringFromByte(address); 1494 } 1495 1496 ParcelUuid[] getUuids() { 1497 enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission"); 1498 1499 return mAdapterProperties.getUuids(); 1500 } 1501 1502 String getName() { 1503 enforceCallingOrSelfPermission(BLUETOOTH_PERM, 1504 "Need BLUETOOTH permission"); 1505 1506 try { 1507 return mAdapterProperties.getName(); 1508 } catch (Throwable t) { 1509 debugLog("getName() - Unexpected exception (" + t + ")"); 1510 } 1511 return null; 1512 } 1513 1514 boolean setName(String name) { 1515 enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM, 1516 "Need BLUETOOTH ADMIN permission"); 1517 1518 return mAdapterProperties.setName(name); 1519 } 1520 1521 int getScanMode() { 1522 enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission"); 1523 1524 return mAdapterProperties.getScanMode(); 1525 } 1526 1527 boolean setScanMode(int mode, int duration) { 1528 enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission"); 1529 1530 setDiscoverableTimeout(duration); 1531 1532 int newMode = convertScanModeToHal(mode); 1533 return mAdapterProperties.setScanMode(newMode); 1534 } 1535 1536 int getDiscoverableTimeout() { 1537 enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission"); 1538 1539 return mAdapterProperties.getDiscoverableTimeout(); 1540 } 1541 1542 boolean setDiscoverableTimeout(int timeout) { 1543 enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission"); 1544 1545 return mAdapterProperties.setDiscoverableTimeout(timeout); 1546 } 1547 1548 boolean startDiscovery() { 1549 enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM, 1550 "Need BLUETOOTH ADMIN permission"); 1551 1552 return startDiscoveryNative(); 1553 } 1554 1555 boolean cancelDiscovery() { 1556 enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM, 1557 "Need BLUETOOTH ADMIN permission"); 1558 1559 return cancelDiscoveryNative(); 1560 } 1561 1562 boolean isDiscovering() { 1563 enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission"); 1564 1565 return mAdapterProperties.isDiscovering(); 1566 } 1567 1568 BluetoothDevice[] getBondedDevices() { 1569 enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission"); 1570 return mAdapterProperties.getBondedDevices(); 1571 } 1572 1573 int getAdapterConnectionState() { 1574 enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission"); 1575 return mAdapterProperties.getConnectionState(); 1576 } 1577 1578 int getProfileConnectionState(int profile) { 1579 enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission"); 1580 1581 return mAdapterProperties.getProfileConnectionState(profile); 1582 } 1583 boolean sdpSearch(BluetoothDevice device,ParcelUuid uuid) { 1584 enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission"); 1585 if(mSdpManager != null) { 1586 mSdpManager.sdpSearch(device,uuid); 1587 return true; 1588 } else { 1589 return false; 1590 } 1591 } 1592 1593 boolean createBond(BluetoothDevice device, int transport, OobData oobData) { 1594 enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM, 1595 "Need BLUETOOTH ADMIN permission"); 1596 DeviceProperties deviceProp = mRemoteDevices.getDeviceProperties(device); 1597 if (deviceProp != null && deviceProp.getBondState() != BluetoothDevice.BOND_NONE) { 1598 return false; 1599 } 1600 1601 // Pairing is unreliable while scanning, so cancel discovery 1602 // Note, remove this when native stack improves 1603 cancelDiscoveryNative(); 1604 1605 Message msg = mBondStateMachine.obtainMessage(BondStateMachine.CREATE_BOND); 1606 msg.obj = device; 1607 msg.arg1 = transport; 1608 1609 if (oobData != null) { 1610 Bundle oobDataBundle = new Bundle(); 1611 oobDataBundle.putParcelable(BondStateMachine.OOBDATA, oobData); 1612 msg.setData(oobDataBundle); 1613 } 1614 mBondStateMachine.sendMessage(msg); 1615 return true; 1616 } 1617 1618 public boolean isQuietModeEnabled() { 1619 debugLog("isQuetModeEnabled() - Enabled = " + mQuietmode); 1620 return mQuietmode; 1621 } 1622 1623 public void autoConnect(){ 1624 if (getState() != BluetoothAdapter.STATE_ON){ 1625 errorLog("autoConnect() - BT is not ON. Exiting autoConnect"); 1626 return; 1627 } 1628 if (isQuietModeEnabled() == false) { 1629 debugLog( "autoConnect() - Initiate auto connection on BT on..."); 1630 // Phone profiles. 1631 autoConnectHeadset(); 1632 autoConnectA2dp(); 1633 1634 // Car Kitt profiles. 1635 autoConnectHeadsetClient(); 1636 autoConnectA2dpSink(); 1637 } 1638 else { 1639 debugLog( "autoConnect() - BT is in quiet mode. Not initiating auto connections"); 1640 } 1641 } 1642 1643 private void autoConnectHeadset(){ 1644 HeadsetService hsService = HeadsetService.getHeadsetService(); 1645 1646 BluetoothDevice bondedDevices[] = getBondedDevices(); 1647 if ((bondedDevices == null) ||(hsService == null)) { 1648 return; 1649 } 1650 for (BluetoothDevice device : bondedDevices) { 1651 if (hsService.getPriority(device) == BluetoothProfile.PRIORITY_AUTO_CONNECT ){ 1652 debugLog("autoConnectHeadset() - Connecting HFP with " + device.toString()); 1653 hsService.connect(device); 1654 } 1655 } 1656 } 1657 1658 private void autoConnectA2dp(){ 1659 A2dpService a2dpSservice = A2dpService.getA2dpService(); 1660 BluetoothDevice bondedDevices[] = getBondedDevices(); 1661 if ((bondedDevices == null) ||(a2dpSservice == null)) { 1662 return; 1663 } 1664 for (BluetoothDevice device : bondedDevices) { 1665 if (a2dpSservice.getPriority(device) == BluetoothProfile.PRIORITY_AUTO_CONNECT ){ 1666 debugLog("autoConnectA2dp() - Connecting A2DP with " + device.toString()); 1667 a2dpSservice.connect(device); 1668 } 1669 } 1670 } 1671 1672 private void autoConnectHeadsetClient() { 1673 HeadsetClientService headsetClientService = HeadsetClientService.getHeadsetClientService(); 1674 BluetoothDevice bondedDevices[] = getBondedDevices(); 1675 if ((bondedDevices == null) || (headsetClientService == null)) { 1676 return; 1677 } 1678 1679 for (BluetoothDevice device : bondedDevices) { 1680 debugLog("autoConnectHeadsetClient() - Connecting Headset Client with " + 1681 device.toString()); 1682 headsetClientService.connect(device); 1683 } 1684 } 1685 1686 private void autoConnectA2dpSink() { 1687 A2dpSinkService a2dpSinkService = A2dpSinkService.getA2dpSinkService(); 1688 BluetoothDevice bondedDevices[] = getBondedDevices(); 1689 if ((bondedDevices == null) || (a2dpSinkService == null)) { 1690 return; 1691 } 1692 1693 for (BluetoothDevice device : bondedDevices) { 1694 debugLog("autoConnectA2dpSink() - Connecting A2DP Sink with " + device.toString()); 1695 a2dpSinkService.connect(device); 1696 } 1697 } 1698 1699 public void connectOtherProfile(BluetoothDevice device, int firstProfileStatus){ 1700 if ((mHandler.hasMessages(MESSAGE_CONNECT_OTHER_PROFILES) == false) && 1701 (isQuietModeEnabled()== false)){ 1702 Message m = mHandler.obtainMessage(MESSAGE_CONNECT_OTHER_PROFILES); 1703 m.obj = device; 1704 m.arg1 = (int)firstProfileStatus; 1705 mHandler.sendMessageDelayed(m,CONNECT_OTHER_PROFILES_TIMEOUT); 1706 } 1707 } 1708 1709 private void processConnectOtherProfiles (BluetoothDevice device, int firstProfileStatus){ 1710 if (getState()!= BluetoothAdapter.STATE_ON){ 1711 return; 1712 } 1713 HeadsetService hsService = HeadsetService.getHeadsetService(); 1714 A2dpService a2dpService = A2dpService.getA2dpService(); 1715 1716 // if any of the profile service is null, second profile connection not required 1717 if ((hsService == null) ||(a2dpService == null )){ 1718 return; 1719 } 1720 List<BluetoothDevice> a2dpConnDevList= a2dpService.getConnectedDevices(); 1721 List<BluetoothDevice> hfConnDevList= hsService.getConnectedDevices(); 1722 // Check if the device is in disconnected state and if so return 1723 // We ned to connect other profile only if one of the profile is still in connected state 1724 // This is required to avoide a race condition in which profiles would 1725 // automaticlly connect if the disconnection is initiated within 6 seconds of connection 1726 //First profile connection being rejected is an exception 1727 if((hfConnDevList.isEmpty() && a2dpConnDevList.isEmpty())&& 1728 (PROFILE_CONN_CONNECTED == firstProfileStatus)){ 1729 return; 1730 } 1731 if((hfConnDevList.isEmpty()) && 1732 (hsService.getPriority(device) >= BluetoothProfile.PRIORITY_ON)){ 1733 hsService.connect(device); 1734 } 1735 else if((a2dpConnDevList.isEmpty()) && 1736 (a2dpService.getPriority(device) >= BluetoothProfile.PRIORITY_ON)){ 1737 a2dpService.connect(device); 1738 } 1739 } 1740 1741 private void adjustOtherHeadsetPriorities(HeadsetService hsService, 1742 List<BluetoothDevice> connectedDeviceList) { 1743 for (BluetoothDevice device : getBondedDevices()) { 1744 if (hsService.getPriority(device) >= BluetoothProfile.PRIORITY_AUTO_CONNECT && 1745 !connectedDeviceList.contains(device)) { 1746 hsService.setPriority(device, BluetoothProfile.PRIORITY_ON); 1747 } 1748 } 1749 } 1750 1751 private void adjustOtherSinkPriorities(A2dpService a2dpService, 1752 BluetoothDevice connectedDevice) { 1753 for (BluetoothDevice device : getBondedDevices()) { 1754 if (a2dpService.getPriority(device) >= BluetoothProfile.PRIORITY_AUTO_CONNECT && 1755 !device.equals(connectedDevice)) { 1756 a2dpService.setPriority(device, BluetoothProfile.PRIORITY_ON); 1757 } 1758 } 1759 } 1760 1761 void setProfileAutoConnectionPriority (BluetoothDevice device, int profileId){ 1762 if (profileId == BluetoothProfile.HEADSET) { 1763 HeadsetService hsService = HeadsetService.getHeadsetService(); 1764 List<BluetoothDevice> deviceList = hsService.getConnectedDevices(); 1765 if ((hsService != null) && 1766 (BluetoothProfile.PRIORITY_AUTO_CONNECT != hsService.getPriority(device))){ 1767 adjustOtherHeadsetPriorities(hsService, deviceList); 1768 hsService.setPriority(device,BluetoothProfile.PRIORITY_AUTO_CONNECT); 1769 } 1770 } 1771 } 1772 1773 boolean cancelBondProcess(BluetoothDevice device) { 1774 enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM, "Need BLUETOOTH ADMIN permission"); 1775 byte[] addr = Utils.getBytesFromAddress(device.getAddress()); 1776 return cancelBondNative(addr); 1777 } 1778 1779 boolean removeBond(BluetoothDevice device) { 1780 enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM, "Need BLUETOOTH ADMIN permission"); 1781 DeviceProperties deviceProp = mRemoteDevices.getDeviceProperties(device); 1782 if (deviceProp == null || deviceProp.getBondState() != BluetoothDevice.BOND_BONDED) { 1783 return false; 1784 } 1785 Message msg = mBondStateMachine.obtainMessage(BondStateMachine.REMOVE_BOND); 1786 msg.obj = device; 1787 mBondStateMachine.sendMessage(msg); 1788 return true; 1789 } 1790 1791 int getBondState(BluetoothDevice device) { 1792 enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission"); 1793 DeviceProperties deviceProp = mRemoteDevices.getDeviceProperties(device); 1794 if (deviceProp == null) { 1795 return BluetoothDevice.BOND_NONE; 1796 } 1797 return deviceProp.getBondState(); 1798 } 1799 1800 int getConnectionState(BluetoothDevice device) { 1801 enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission"); 1802 byte[] addr = Utils.getBytesFromAddress(device.getAddress()); 1803 return getConnectionStateNative(addr); 1804 } 1805 1806 String getRemoteName(BluetoothDevice device) { 1807 enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission"); 1808 if (mRemoteDevices == null) return null; 1809 DeviceProperties deviceProp = mRemoteDevices.getDeviceProperties(device); 1810 if (deviceProp == null) return null; 1811 return deviceProp.getName(); 1812 } 1813 1814 int getRemoteType(BluetoothDevice device) { 1815 enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission"); 1816 DeviceProperties deviceProp = mRemoteDevices.getDeviceProperties(device); 1817 if (deviceProp == null) return BluetoothDevice.DEVICE_TYPE_UNKNOWN; 1818 return deviceProp.getDeviceType(); 1819 } 1820 1821 String getRemoteAlias(BluetoothDevice device) { 1822 enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission"); 1823 DeviceProperties deviceProp = mRemoteDevices.getDeviceProperties(device); 1824 if (deviceProp == null) return null; 1825 return deviceProp.getAlias(); 1826 } 1827 1828 boolean setRemoteAlias(BluetoothDevice device, String name) { 1829 enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission"); 1830 DeviceProperties deviceProp = mRemoteDevices.getDeviceProperties(device); 1831 if (deviceProp == null) return false; 1832 deviceProp.setAlias(device, name); 1833 return true; 1834 } 1835 1836 int getRemoteClass(BluetoothDevice device) { 1837 enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission"); 1838 DeviceProperties deviceProp = mRemoteDevices.getDeviceProperties(device); 1839 if (deviceProp == null) return 0; 1840 1841 return deviceProp.getBluetoothClass(); 1842 } 1843 1844 ParcelUuid[] getRemoteUuids(BluetoothDevice device) { 1845 enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission"); 1846 DeviceProperties deviceProp = mRemoteDevices.getDeviceProperties(device); 1847 if (deviceProp == null) return null; 1848 return deviceProp.getUuids(); 1849 } 1850 1851 boolean fetchRemoteUuids(BluetoothDevice device) { 1852 enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission"); 1853 mRemoteDevices.fetchUuids(device); 1854 return true; 1855 } 1856 1857 1858 boolean setPin(BluetoothDevice device, boolean accept, int len, byte[] pinCode) { 1859 enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM, 1860 "Need BLUETOOTH ADMIN permission"); 1861 DeviceProperties deviceProp = mRemoteDevices.getDeviceProperties(device); 1862 // Only allow setting a pin in bonding state, or bonded state in case of security upgrade. 1863 if (deviceProp == null || 1864 (deviceProp.getBondState() != BluetoothDevice.BOND_BONDING && 1865 deviceProp.getBondState() != BluetoothDevice.BOND_BONDED)) { 1866 return false; 1867 } 1868 1869 byte[] addr = Utils.getBytesFromAddress(device.getAddress()); 1870 return pinReplyNative(addr, accept, len, pinCode); 1871 } 1872 1873 boolean setPasskey(BluetoothDevice device, boolean accept, int len, byte[] passkey) { 1874 enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission"); 1875 DeviceProperties deviceProp = mRemoteDevices.getDeviceProperties(device); 1876 if (deviceProp == null || deviceProp.getBondState() != BluetoothDevice.BOND_BONDING) { 1877 return false; 1878 } 1879 1880 byte[] addr = Utils.getBytesFromAddress(device.getAddress()); 1881 return sspReplyNative(addr, AbstractionLayer.BT_SSP_VARIANT_PASSKEY_ENTRY, accept, 1882 Utils.byteArrayToInt(passkey)); 1883 } 1884 1885 boolean setPairingConfirmation(BluetoothDevice device, boolean accept) { 1886 enforceCallingOrSelfPermission(BLUETOOTH_ADMIN_PERM, 1887 "Need BLUETOOTH ADMIN permission"); 1888 DeviceProperties deviceProp = mRemoteDevices.getDeviceProperties(device); 1889 if (deviceProp == null || deviceProp.getBondState() != BluetoothDevice.BOND_BONDING) { 1890 return false; 1891 } 1892 1893 byte[] addr = Utils.getBytesFromAddress(device.getAddress()); 1894 return sspReplyNative(addr, AbstractionLayer.BT_SSP_VARIANT_PASSKEY_CONFIRMATION, 1895 accept, 0); 1896 } 1897 1898 int getPhonebookAccessPermission(BluetoothDevice device) { 1899 enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission"); 1900 SharedPreferences pref = getSharedPreferences(PHONEBOOK_ACCESS_PERMISSION_PREFERENCE_FILE, 1901 Context.MODE_PRIVATE); 1902 if (!pref.contains(device.getAddress())) { 1903 return BluetoothDevice.ACCESS_UNKNOWN; 1904 } 1905 return pref.getBoolean(device.getAddress(), false) 1906 ? BluetoothDevice.ACCESS_ALLOWED : BluetoothDevice.ACCESS_REJECTED; 1907 } 1908 1909 boolean setPhonebookAccessPermission(BluetoothDevice device, int value) { 1910 enforceCallingOrSelfPermission(BLUETOOTH_PRIVILEGED, 1911 "Need BLUETOOTH PRIVILEGED permission"); 1912 SharedPreferences pref = getSharedPreferences(PHONEBOOK_ACCESS_PERMISSION_PREFERENCE_FILE, 1913 Context.MODE_PRIVATE); 1914 SharedPreferences.Editor editor = pref.edit(); 1915 if (value == BluetoothDevice.ACCESS_UNKNOWN) { 1916 editor.remove(device.getAddress()); 1917 } else { 1918 editor.putBoolean(device.getAddress(), value == BluetoothDevice.ACCESS_ALLOWED); 1919 } 1920 return editor.commit(); 1921 } 1922 1923 int getMessageAccessPermission(BluetoothDevice device) { 1924 enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission"); 1925 SharedPreferences pref = getSharedPreferences(MESSAGE_ACCESS_PERMISSION_PREFERENCE_FILE, 1926 Context.MODE_PRIVATE); 1927 if (!pref.contains(device.getAddress())) { 1928 return BluetoothDevice.ACCESS_UNKNOWN; 1929 } 1930 return pref.getBoolean(device.getAddress(), false) 1931 ? BluetoothDevice.ACCESS_ALLOWED : BluetoothDevice.ACCESS_REJECTED; 1932 } 1933 1934 boolean setMessageAccessPermission(BluetoothDevice device, int value) { 1935 enforceCallingOrSelfPermission(BLUETOOTH_PRIVILEGED, 1936 "Need BLUETOOTH PRIVILEGED permission"); 1937 SharedPreferences pref = getSharedPreferences(MESSAGE_ACCESS_PERMISSION_PREFERENCE_FILE, 1938 Context.MODE_PRIVATE); 1939 SharedPreferences.Editor editor = pref.edit(); 1940 if (value == BluetoothDevice.ACCESS_UNKNOWN) { 1941 editor.remove(device.getAddress()); 1942 } else { 1943 editor.putBoolean(device.getAddress(), value == BluetoothDevice.ACCESS_ALLOWED); 1944 } 1945 return editor.commit(); 1946 } 1947 1948 int getSimAccessPermission(BluetoothDevice device) { 1949 enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission"); 1950 SharedPreferences pref = getSharedPreferences(SIM_ACCESS_PERMISSION_PREFERENCE_FILE, 1951 Context.MODE_PRIVATE); 1952 if (!pref.contains(device.getAddress())) { 1953 return BluetoothDevice.ACCESS_UNKNOWN; 1954 } 1955 return pref.getBoolean(device.getAddress(), false) 1956 ? BluetoothDevice.ACCESS_ALLOWED : BluetoothDevice.ACCESS_REJECTED; 1957 } 1958 1959 boolean setSimAccessPermission(BluetoothDevice device, int value) { 1960 enforceCallingOrSelfPermission(BLUETOOTH_PRIVILEGED, 1961 "Need BLUETOOTH PRIVILEGED permission"); 1962 SharedPreferences pref = getSharedPreferences(SIM_ACCESS_PERMISSION_PREFERENCE_FILE, 1963 Context.MODE_PRIVATE); 1964 SharedPreferences.Editor editor = pref.edit(); 1965 if (value == BluetoothDevice.ACCESS_UNKNOWN) { 1966 editor.remove(device.getAddress()); 1967 } else { 1968 editor.putBoolean(device.getAddress(), value == BluetoothDevice.ACCESS_ALLOWED); 1969 } 1970 return editor.commit(); 1971 } 1972 1973 void sendConnectionStateChange(BluetoothDevice 1974 device, int profile, int state, int prevState) { 1975 // TODO(BT) permission check? 1976 // Since this is a binder call check if Bluetooth is on still 1977 if (getState() == BluetoothAdapter.STATE_OFF) return; 1978 1979 mAdapterProperties.sendConnectionStateChange(device, profile, state, prevState); 1980 1981 } 1982 1983 ParcelFileDescriptor connectSocket(BluetoothDevice device, int type, 1984 ParcelUuid uuid, int port, int flag) { 1985 enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission"); 1986 int fd = connectSocketNative(Utils.getBytesFromAddress(device.getAddress()), 1987 type, Utils.uuidToByteArray(uuid), port, flag, Binder.getCallingUid()); 1988 if (fd < 0) { 1989 errorLog("Failed to connect socket"); 1990 return null; 1991 } 1992 return ParcelFileDescriptor.adoptFd(fd); 1993 } 1994 1995 ParcelFileDescriptor createSocketChannel(int type, String serviceName, 1996 ParcelUuid uuid, int port, int flag) { 1997 enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission"); 1998 int fd = createSocketChannelNative(type, serviceName, 1999 Utils.uuidToByteArray(uuid), port, flag, Binder.getCallingUid()); 2000 if (fd < 0) { 2001 errorLog("Failed to create socket channel"); 2002 return null; 2003 } 2004 return ParcelFileDescriptor.adoptFd(fd); 2005 } 2006 2007 boolean configHciSnoopLog(boolean enable) { 2008 enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission"); 2009 return configHciSnoopLogNative(enable); 2010 } 2011 2012 boolean factoryReset() { 2013 enforceCallingOrSelfPermission(BLUETOOTH_PRIVILEGED, "Need BLUETOOTH permission"); 2014 return factoryResetNative(); 2015 } 2016 2017 void registerCallback(IBluetoothCallback cb) { 2018 mCallbacks.register(cb); 2019 } 2020 2021 void unregisterCallback(IBluetoothCallback cb) { 2022 mCallbacks.unregister(cb); 2023 } 2024 2025 public int getNumOfAdvertisementInstancesSupported() { 2026 enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission"); 2027 return mAdapterProperties.getNumOfAdvertisementInstancesSupported(); 2028 } 2029 2030 public boolean isMultiAdvertisementSupported() { 2031 enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission"); 2032 return getNumOfAdvertisementInstancesSupported() >= MIN_ADVT_INSTANCES_FOR_MA; 2033 } 2034 2035 public boolean isRpaOffloadSupported() { 2036 enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission"); 2037 return mAdapterProperties.isRpaOffloadSupported(); 2038 } 2039 2040 public int getNumOfOffloadedIrkSupported() { 2041 enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission"); 2042 return mAdapterProperties.getNumOfOffloadedIrkSupported(); 2043 } 2044 2045 public int getNumOfOffloadedScanFilterSupported() { 2046 enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission"); 2047 return mAdapterProperties.getNumOfOffloadedScanFilterSupported(); 2048 } 2049 2050 public boolean isPeripheralModeSupported() { 2051 return getResources().getBoolean(R.bool.config_bluetooth_le_peripheral_mode_supported); 2052 } 2053 2054 public int getOffloadedScanResultStorage() { 2055 enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission"); 2056 return mAdapterProperties.getOffloadedScanResultStorage(); 2057 } 2058 2059 private boolean isActivityAndEnergyReportingSupported() { 2060 enforceCallingOrSelfPermission(BLUETOOTH_PRIVILEGED, "Need BLUETOOTH permission"); 2061 return mAdapterProperties.isActivityAndEnergyReportingSupported(); 2062 } 2063 2064 private void getActivityEnergyInfoFromController() { 2065 enforceCallingOrSelfPermission(BLUETOOTH_PRIVILEGED, "Need BLUETOOTH permission"); 2066 if (isActivityAndEnergyReportingSupported()) { 2067 readEnergyInfo(); 2068 } 2069 } 2070 2071 private BluetoothActivityEnergyInfo reportActivityInfo() { 2072 enforceCallingOrSelfPermission(BLUETOOTH_PRIVILEGED, "Need BLUETOOTH permission"); 2073 synchronized (mEnergyInfoLock) { 2074 final BluetoothActivityEnergyInfo info = new BluetoothActivityEnergyInfo( 2075 SystemClock.elapsedRealtime(), 2076 mStackReportedState, 2077 mTxTimeTotalMs, mRxTimeTotalMs, mIdleTimeTotalMs, 2078 mEnergyUsedTotalVoltAmpSecMicro); 2079 2080 // Count the number of entries that have byte counts > 0 2081 int arrayLen = 0; 2082 for (int i = 0; i < mUidTraffic.size(); i++) { 2083 final UidTraffic traffic = mUidTraffic.valueAt(i); 2084 if (traffic.getTxBytes() != 0 || traffic.getRxBytes() != 0) { 2085 arrayLen++; 2086 } 2087 } 2088 2089 // Copy the traffic objects whose byte counts are > 0 and reset the originals. 2090 final UidTraffic[] result = arrayLen > 0 ? new UidTraffic[arrayLen] : null; 2091 int putIdx = 0; 2092 for (int i = 0; i < mUidTraffic.size(); i++) { 2093 final UidTraffic traffic = mUidTraffic.valueAt(i); 2094 if (traffic.getTxBytes() != 0 || traffic.getRxBytes() != 0) { 2095 result[putIdx++] = traffic.clone(); 2096 traffic.setRxBytes(0); 2097 traffic.setTxBytes(0); 2098 } 2099 } 2100 2101 info.setUidTraffic(result); 2102 2103 // Read on clear values; a record of data is created with 2104 // timstamp and new samples are collected until read again 2105 mStackReportedState = 0; 2106 mTxTimeTotalMs = 0; 2107 mRxTimeTotalMs = 0; 2108 mIdleTimeTotalMs = 0; 2109 mEnergyUsedTotalVoltAmpSecMicro = 0; 2110 return info; 2111 } 2112 } 2113 2114 public int getTotalNumOfTrackableAdvertisements() { 2115 enforceCallingOrSelfPermission(BLUETOOTH_PERM, "Need BLUETOOTH permission"); 2116 return mAdapterProperties.getTotalNumOfTrackableAdvertisements(); 2117 } 2118 2119 public void onLeServiceUp() { 2120 Message m = mAdapterStateMachine.obtainMessage(AdapterState.USER_TURN_ON); 2121 mAdapterStateMachine.sendMessage(m); 2122 } 2123 2124 public void onBrEdrDown() { 2125 Message m = mAdapterStateMachine.obtainMessage(AdapterState.USER_TURN_OFF); 2126 mAdapterStateMachine.sendMessage(m); 2127 } 2128 2129 private static int convertScanModeToHal(int mode) { 2130 switch (mode) { 2131 case BluetoothAdapter.SCAN_MODE_NONE: 2132 return AbstractionLayer.BT_SCAN_MODE_NONE; 2133 case BluetoothAdapter.SCAN_MODE_CONNECTABLE: 2134 return AbstractionLayer.BT_SCAN_MODE_CONNECTABLE; 2135 case BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE: 2136 return AbstractionLayer.BT_SCAN_MODE_CONNECTABLE_DISCOVERABLE; 2137 } 2138 // errorLog("Incorrect scan mode in convertScanModeToHal"); 2139 return -1; 2140 } 2141 2142 static int convertScanModeFromHal(int mode) { 2143 switch (mode) { 2144 case AbstractionLayer.BT_SCAN_MODE_NONE: 2145 return BluetoothAdapter.SCAN_MODE_NONE; 2146 case AbstractionLayer.BT_SCAN_MODE_CONNECTABLE: 2147 return BluetoothAdapter.SCAN_MODE_CONNECTABLE; 2148 case AbstractionLayer.BT_SCAN_MODE_CONNECTABLE_DISCOVERABLE: 2149 return BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE; 2150 } 2151 //errorLog("Incorrect scan mode in convertScanModeFromHal"); 2152 return -1; 2153 } 2154 2155 // This function is called from JNI. It allows native code to set a single wake 2156 // alarm. If an alarm is already pending and a new request comes in, the alarm 2157 // will be rescheduled (i.e. the previously set alarm will be cancelled). 2158 private boolean setWakeAlarm(long delayMillis, boolean shouldWake) { 2159 synchronized (this) { 2160 if (mPendingAlarm != null) { 2161 mAlarmManager.cancel(mPendingAlarm); 2162 } 2163 2164 long wakeupTime = SystemClock.elapsedRealtime() + delayMillis; 2165 int type = shouldWake 2166 ? AlarmManager.ELAPSED_REALTIME_WAKEUP 2167 : AlarmManager.ELAPSED_REALTIME; 2168 2169 Intent intent = new Intent(ACTION_ALARM_WAKEUP); 2170 mPendingAlarm = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_ONE_SHOT); 2171 mAlarmManager.setExact(type, wakeupTime, mPendingAlarm); 2172 return true; 2173 } 2174 } 2175 2176 // This function is called from JNI. It allows native code to acquire a single wake lock. 2177 // If the wake lock is already held, this function returns success. Although this function 2178 // only supports acquiring a single wake lock at a time right now, it will eventually be 2179 // extended to allow acquiring an arbitrary number of wake locks. The current interface 2180 // takes |lockName| as a parameter in anticipation of that implementation. 2181 private boolean acquireWakeLock(String lockName) { 2182 if (mWakeLock != null) { 2183 if (!lockName.equals(mWakeLockName)) { 2184 errorLog("Multiple wake lock acquisition attempted; aborting: " + lockName); 2185 return false; 2186 } 2187 2188 // We're already holding the desired wake lock so return success. 2189 if (mWakeLock.isHeld()) { 2190 return true; 2191 } 2192 } 2193 2194 mWakeLockName = lockName; 2195 mWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, lockName); 2196 mWakeLock.acquire(); 2197 return true; 2198 } 2199 2200 // This function is called from JNI. It allows native code to release a wake lock acquired 2201 // by |acquireWakeLock|. If the wake lock is not held, this function returns failure. 2202 // Note that the release() call is also invoked by {@link #cleanup()} so a synchronization is 2203 // needed here. See the comment for |acquireWakeLock| for an explanation of the interface. 2204 private boolean releaseWakeLock(String lockName) { 2205 synchronized (this) { 2206 if (mWakeLock == null) { 2207 errorLog("Repeated wake lock release; aborting release: " + lockName); 2208 return false; 2209 } 2210 2211 mWakeLock.release(); 2212 mWakeLock = null; 2213 mWakeLockName = null; 2214 } 2215 return true; 2216 } 2217 2218 private void energyInfoCallback(int status, int ctrl_state, long tx_time, long rx_time, 2219 long idle_time, long energy_used, UidTraffic[] data) 2220 throws RemoteException { 2221 if (ctrl_state >= BluetoothActivityEnergyInfo.BT_STACK_STATE_INVALID && 2222 ctrl_state <= BluetoothActivityEnergyInfo.BT_STACK_STATE_STATE_IDLE) { 2223 // Energy is product of mA, V and ms. If the chipset doesn't 2224 // report it, we have to compute it from time 2225 if (energy_used == 0) { 2226 energy_used = (long)((tx_time * getTxCurrentMa() 2227 + rx_time * getRxCurrentMa() 2228 + idle_time * getIdleCurrentMa()) * getOperatingVolt()); 2229 } 2230 2231 synchronized (mEnergyInfoLock) { 2232 mStackReportedState = ctrl_state; 2233 mTxTimeTotalMs += tx_time; 2234 mRxTimeTotalMs += rx_time; 2235 mIdleTimeTotalMs += idle_time; 2236 mEnergyUsedTotalVoltAmpSecMicro += energy_used; 2237 2238 for (UidTraffic traffic : data) { 2239 UidTraffic existingTraffic = mUidTraffic.get(traffic.getUid()); 2240 if (existingTraffic == null) { 2241 mUidTraffic.put(traffic.getUid(), traffic); 2242 } else { 2243 existingTraffic.addRxBytes(traffic.getRxBytes()); 2244 existingTraffic.addTxBytes(traffic.getTxBytes()); 2245 } 2246 } 2247 } 2248 } 2249 2250 debugLog("energyInfoCallback() status = " + status + 2251 "tx_time = " + tx_time + "rx_time = " + rx_time + 2252 "idle_time = " + idle_time + "energy_used = " + energy_used + 2253 "ctrl_state = " + ctrl_state + 2254 "traffic = " + Arrays.toString(data)); 2255 } 2256 2257 private int getIdleCurrentMa() { 2258 return getResources().getInteger(R.integer.config_bluetooth_idle_cur_ma); 2259 } 2260 2261 private int getTxCurrentMa() { 2262 return getResources().getInteger(R.integer.config_bluetooth_tx_cur_ma); 2263 } 2264 2265 private int getRxCurrentMa() { 2266 return getResources().getInteger(R.integer.config_bluetooth_rx_cur_ma); 2267 } 2268 2269 private double getOperatingVolt() { 2270 return getResources().getInteger(R.integer.config_bluetooth_operating_voltage_mv) / 1000.0; 2271 } 2272 2273 @Override 2274 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) { 2275 enforceCallingOrSelfPermission(android.Manifest.permission.DUMP, TAG); 2276 2277 if (args.length > 0) { 2278 debugLog("dumpsys arguments, check for protobuf output: " + 2279 TextUtils.join(" ", args)); 2280 if (args[0].startsWith("--proto")) { 2281 if (args[0].equals("--proto-java-bin")) { 2282 dumpJava(fd); 2283 } else { 2284 dumpNative(fd, args); 2285 } 2286 return; 2287 } 2288 } 2289 2290 long onDuration = System.currentTimeMillis() - mBluetoothStartTime; 2291 String onDurationString = String.format("%02d:%02d:%02d.%03d", 2292 (int)(onDuration / (1000 * 60 * 60)), 2293 (int)((onDuration / (1000 * 60)) % 60), 2294 (int)((onDuration / 1000) % 60), 2295 (int)(onDuration % 1000)); 2296 2297 writer.println("Bluetooth Status"); 2298 writer.println(" enabled: " + isEnabled()); 2299 writer.println(" state: " + getState()); 2300 writer.println(" address: " + getAddress()); 2301 writer.println(" name: " + getName()); 2302 writer.println(" time since enabled: " + onDurationString + "\n"); 2303 2304 writer.println("Bonded devices:"); 2305 for (BluetoothDevice device : getBondedDevices()) { 2306 writer.println(" " + device.getAddress() + 2307 " [" + DEVICE_TYPE_NAMES[device.getType()] + "] " + 2308 device.getName()); 2309 } 2310 2311 // Dump profile information 2312 StringBuilder sb = new StringBuilder(); 2313 synchronized (mProfiles) { 2314 for (ProfileService profile : mProfiles) { 2315 profile.dump(sb); 2316 } 2317 } 2318 2319 writer.write(sb.toString()); 2320 writer.flush(); 2321 2322 dumpNative(fd, args); 2323 } 2324 2325 private void dumpJava(FileDescriptor fd) { 2326 BluetoothProto.BluetoothLog log = new BluetoothProto.BluetoothLog(); 2327 2328 for (ProfileService profile : mProfiles) { 2329 profile.dumpProto(log); 2330 } 2331 2332 try { 2333 FileOutputStream protoOut = new FileOutputStream(fd); 2334 String protoOutString = 2335 Base64.encodeToString(log.toByteArray(), Base64.DEFAULT); 2336 protoOut.write(protoOutString.getBytes(StandardCharsets.UTF_8)); 2337 protoOut.close(); 2338 } catch (IOException e) { 2339 errorLog("Unable to write Java protobuf to file descriptor."); 2340 } 2341 } 2342 2343 private void debugLog(String msg) { 2344 if (DBG) Log.d(TAG, msg); 2345 } 2346 2347 private void errorLog(String msg) { 2348 Log.e(TAG, msg); 2349 } 2350 2351 private final BroadcastReceiver mAlarmBroadcastReceiver = new BroadcastReceiver() { 2352 @Override 2353 public void onReceive(Context context, Intent intent) { 2354 synchronized (AdapterService.this) { 2355 mPendingAlarm = null; 2356 alarmFiredNative(); 2357 } 2358 } 2359 }; 2360 2361 private native static void classInitNative(); 2362 private native boolean initNative(); 2363 private native void cleanupNative(); 2364 /*package*/ native boolean enableNative(); 2365 /*package*/ native boolean disableNative(); 2366 /*package*/ native boolean setAdapterPropertyNative(int type, byte[] val); 2367 /*package*/ native boolean getAdapterPropertiesNative(); 2368 /*package*/ native boolean getAdapterPropertyNative(int type); 2369 /*package*/ native boolean setAdapterPropertyNative(int type); 2370 /*package*/ native boolean 2371 setDevicePropertyNative(byte[] address, int type, byte[] val); 2372 /*package*/ native boolean getDevicePropertyNative(byte[] address, int type); 2373 2374 /*package*/ native boolean createBondNative(byte[] address, int transport); 2375 /*package*/ native boolean createBondOutOfBandNative(byte[] address, int transport, OobData oobData); 2376 /*package*/ native boolean removeBondNative(byte[] address); 2377 /*package*/ native boolean cancelBondNative(byte[] address); 2378 /*package*/ native boolean sdpSearchNative(byte[] address, byte[] uuid); 2379 2380 /*package*/ native int getConnectionStateNative(byte[] address); 2381 2382 private native boolean startDiscoveryNative(); 2383 private native boolean cancelDiscoveryNative(); 2384 2385 private native boolean pinReplyNative(byte[] address, boolean accept, int len, byte[] pin); 2386 private native boolean sspReplyNative(byte[] address, int type, boolean 2387 accept, int passkey); 2388 2389 /*package*/ native boolean getRemoteServicesNative(byte[] address); 2390 /*package*/ native boolean getRemoteMasInstancesNative(byte[] address); 2391 2392 private native int readEnergyInfo(); 2393 // TODO(BT) move this to ../btsock dir 2394 private native int connectSocketNative(byte[] address, int type, 2395 byte[] uuid, int port, int flag, int callingUid); 2396 private native int createSocketChannelNative(int type, String serviceName, 2397 byte[] uuid, int port, int flag, int callingUid); 2398 2399 /*package*/ native boolean configHciSnoopLogNative(boolean enable); 2400 /*package*/ native boolean factoryResetNative(); 2401 2402 private native void alarmFiredNative(); 2403 private native void dumpNative(FileDescriptor fd, String[] arguments); 2404 2405 private native void interopDatabaseClearNative(); 2406 private native void interopDatabaseAddNative(int feature, byte[] address, int length); 2407 2408 protected void finalize() { 2409 cleanup(); 2410 if (TRACE_REF) { 2411 synchronized (AdapterService.class) { 2412 sRefCount--; 2413 debugLog("finalize() - REFCOUNT: FINALIZED. INSTANCE_COUNT= " + sRefCount); 2414 } 2415 } 2416 } 2417} 2418