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