Here are the examples of the java api class android.bluetooth.BluetoothAdapter taken from open source projects.
1. SimpleBT#scanBluetooth()
Project: Protocoder
File: SimpleBT.java
File: SimpleBT.java
public void scanBluetooth(PBluetooth.onBluetoothListener onBluetoothListener2) { onBluetoothListener = onBluetoothListener2; BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); mBluetoothAdapter.startDiscovery(); BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (BluetoothDevice.ACTION_FOUND.equals(action)) { BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); int rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI, Short.MIN_VALUE); onBluetoothListener.onDeviceFound(device.getName(), device.getAddress(), rssi); //Log.d(TAG, device.getName() + "\n" + device.getAddress() + " " + rssi); } } }; IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); mContext.registerReceiver(mReceiver, filter); }
2. BluetoothServerConnectionHelper#setDiscoverable()
Project: tilt-game-android
File: BluetoothServerConnectionHelper.java
File: BluetoothServerConnectionHelper.java
public void setDiscoverable() { BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter(); if (adapter == null) { return; } // change name if necessary String originalName = adapter.getName(); if (originalName.lastIndexOf(_deviceNamePostFix) != originalName.length() - _deviceNamePostFix.length()) { if (_connectionHelperListener != null) { _connectionHelperListener.onAdapterNameChange(originalName); } Log.d(TAG, "setDiscoverable: Bluetooth device name set to " + (originalName + _deviceNamePostFix)); adapter.setName(originalName + _deviceNamePostFix); } // set discoverable if necessary if (adapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) { Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300); _activity.startActivity(discoverableIntent); } }
3. HomeActivity#onMultiPlayerButtonClick()
Project: tilt-game-android
File: HomeActivity.java
File: HomeActivity.java
@OnClick(R.id.multi_player_button) protected void onMultiPlayerButtonClick() { SoundManager.getInstance().play(R.raw.tap); Prefs.putInt(PrefKeys.GAME_TYPE, GameType.MULTI_PLAYER.ordinal()); BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter(); if (adapter == null) { AlertUtils.showAlert(this, R.string.no_bluetooth_message, R.string.no_bluetooth_title, R.string.btn_ok); } else if (!adapter.isEnabled()) { startActivityForResult(new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE), ActivityRequestCode.REQUEST_ENABLE_BT); } else { startMultiplayer(); } }
4. ServerLobbyFragment#setDiscoverable()
Project: tilt-game-android
File: ServerLobbyFragment.java
File: ServerLobbyFragment.java
private void setDiscoverable() { Log.d(TAG, "setDiscoverable: "); BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter(); if (adapter == null) { return; } // change name if necessary String originalName = adapter.getName(); if (originalName.lastIndexOf(GoogleFlipGameApplication.DEVICE_POSTFIX) != originalName.length() - GoogleFlipGameApplication.DEVICE_POSTFIX.length()) { GoogleFlipGameApplication.setOriginalBluetoothDeviceName(originalName); Log.d(TAG, "setDiscoverable: Bluetooth device name set to " + (originalName + GoogleFlipGameApplication.DEVICE_POSTFIX)); adapter.setName(originalName + GoogleFlipGameApplication.DEVICE_POSTFIX); } // set discoverable if necessary if (adapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) { Log.d(TAG, "setDiscoverable: scan mode is not discoverable, starting activity with code " + ActivityRequestCode.REQUEST_ENABLE_SCAN); Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 120); getActivity().startActivityForResult(discoverableIntent, ActivityRequestCode.REQUEST_ENABLE_SCAN); } }
5. DiscoveryActivity#checkBluetoothAvailable()
Project: Gadgetbridge
File: DiscoveryActivity.java
File: DiscoveryActivity.java
private boolean checkBluetoothAvailable() { BluetoothManager bluetoothService = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE); if (bluetoothService == null) { LOG.warn("No bluetooth available"); this.adapter = null; return false; } BluetoothAdapter adapter = bluetoothService.getAdapter(); if (adapter == null) { LOG.warn("No bluetooth available"); this.adapter = null; return false; } if (!adapter.isEnabled()) { LOG.warn("Bluetooth not enabled"); Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivity(enableBtIntent); this.adapter = null; return false; } this.adapter = adapter; return true; }
6. BluetoothStateReceiver#onReceive()
Project: BleSensorTag
File: BluetoothStateReceiver.java
File: BluetoothStateReceiver.java
@Override public void onReceive(Context context, Intent intent) { if (!AppConfig.ENABLE_RECORD_SERVICE) { return; } final BluetoothAdapter adapter = BleUtils.getBluetoothAdapter(context); final Intent gattServiceIntent = new Intent(context, BleSensorsRecordService.class); if (adapter != null && adapter.isEnabled()) { context.startService(gattServiceIntent); } else { context.stopService(gattServiceIntent); } }
7. SimpleLeScanner#startScan()
Project: beacon-keeper
File: SimpleLeScanner.java
File: SimpleLeScanner.java
public boolean startScan(LeScanCallback callback) { BluetoothAdapter ba = U.getBluetoothAdapter(mContext); if (ba != null && ba.isEnabled() && !mIsScanning && callback != null) { if (ba.startLeScan(callback)) { mIsScanning = true; onStartScan(); return true; } } L.wtf(TAG, "Failed to startScan"); return false; }
8. MainActivity#onDestroy()
Project: android-obd-reader
File: MainActivity.java
File: MainActivity.java
@Override protected void onDestroy() { super.onDestroy(); if (mLocService != null) { mLocService.removeGpsStatusListener(this); mLocService.removeUpdates(this); } releaseWakeLockIfHeld(); if (isServiceBound) { doUnbindService(); } endTrip(); final BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter(); if (btAdapter != null && btAdapter.isEnabled() && !bluetoothDefaultIsEnable) btAdapter.disable(); }
9. MainActivity#onCreate()
Project: android-obd-reader
File: MainActivity.java
File: MainActivity.java
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter(); if (btAdapter != null) bluetoothDefaultIsEnable = btAdapter.isEnabled(); // get Orientation sensor List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ORIENTATION); if (sensors.size() > 0) orientSensor = sensors.get(0); else showDialog(NO_ORIENTATION_SENSOR); // create a log instance for use by this application triplog = TripLog.getInstance(this.getApplicationContext()); }
10. BleProfileService#onStartCommand()
Project: Android-nRF-Toolbox
File: BleProfileService.java
File: BleProfileService.java
@Override public int onStartCommand(final Intent intent, final int flags, final int startId) { if (intent == null || !intent.hasExtra(EXTRA_DEVICE_ADDRESS)) throw new UnsupportedOperationException("No device address at EXTRA_DEVICE_ADDRESS key"); mDeviceAddress = intent.getStringExtra(EXTRA_DEVICE_ADDRESS); // notify user about changing the state to CONNECTING final Intent broadcast = new Intent(BROADCAST_CONNECTION_STATE); broadcast.putExtra(EXTRA_CONNECTION_STATE, STATE_CONNECTING); LocalBroadcastManager.getInstance(BleProfileService.this).sendBroadcast(broadcast); final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE); final BluetoothAdapter adapter = bluetoothManager.getAdapter(); final BluetoothDevice device = adapter.getRemoteDevice(mDeviceAddress); mDeviceName = device.getName(); mBleManager.connect(device); return START_REDELIVER_INTENT; }
11. BleProfileService#onStartCommand()
Project: Android-nRF-Toolbox
File: BleProfileService.java
File: BleProfileService.java
@Override public int onStartCommand(final Intent intent, final int flags, final int startId) { if (intent == null || !intent.hasExtra(EXTRA_DEVICE_ADDRESS)) throw new UnsupportedOperationException("No device address at EXTRA_DEVICE_ADDRESS key"); final Uri logUri = intent.getParcelableExtra(EXTRA_LOG_URI); mLogSession = Logger.openSession(getApplicationContext(), logUri); mDeviceAddress = intent.getStringExtra(EXTRA_DEVICE_ADDRESS); Logger.i(mLogSession, "Service started"); // notify user about changing the state to CONNECTING final Intent broadcast = new Intent(BROADCAST_CONNECTION_STATE); broadcast.putExtra(EXTRA_CONNECTION_STATE, STATE_CONNECTING); LocalBroadcastManager.getInstance(BleProfileService.this).sendBroadcast(broadcast); final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE); final BluetoothAdapter adapter = bluetoothManager.getAdapter(); final BluetoothDevice device = adapter.getRemoteDevice(mDeviceAddress); mDeviceName = device.getName(); onServiceStarted(); mBleManager.connect(device); return START_REDELIVER_INTENT; }
12. SystemLib#isBluetoothEnabled()
Project: Cafe
File: SystemLib.java
File: SystemLib.java
/** * check bluetooth enabled or not * * @return true enabled false disabled * */ public boolean isBluetoothEnabled() { BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter(); if (bluetooth == null) //"device not BT capable"; return false; return bluetooth.isEnabled(); }
13. ConnectProtocolFragment#onBluetootButtonClicked()
Project: tilt-game-android
File: ConnectProtocolFragment.java
File: ConnectProtocolFragment.java
@OnClick(R.id.btn_bluetooth) protected void onBluetootButtonClicked() { BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter(); if (adapter == null) { AlertUtils.showAlert(getActivity(), R.string.no_bluetooth_message, R.string.no_bluetooth_title, R.string.btn_ok); } else if (!adapter.isEnabled()) { startActivityForResult(new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE), ActivityRequestCode.REQUEST_ENABLE_BT); } else { goNextScreen(MultiplayerProtocol.BLUETOOTH); } }
14. GoogleFlipGameApplication#restoreBluetoothDeviceName()
Project: tilt-game-android
File: GoogleFlipGameApplication.java
File: GoogleFlipGameApplication.java
public static void restoreBluetoothDeviceName() { BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter(); if (adapter != null && sBluetoothDeviceName != null) { // restore bluetooth device name adapter.setName(sBluetoothDeviceName); } }
15. BleConnectionCompat#getIBluetoothManager()
Project: RxAndroidBle
File: BleConnectionCompat.java
File: BleConnectionCompat.java
private Object getIBluetoothManager() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (bluetoothAdapter == null) { return null; } Method getBluetoothManagerMethod = getMethodFromClass(bluetoothAdapter.getClass(), "getBluetoothManager"); return getBluetoothManagerMethod.invoke(bluetoothAdapter); }
16. BroadcastActivity#checkIfBluetoothIsEnabled()
Project: physical-web
File: BroadcastActivity.java
File: BroadcastActivity.java
// Check if bluetooth is on private boolean checkIfBluetoothIsEnabled() { BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); BluetoothAdapter bluetoothAdapter = bluetoothManager.getAdapter(); if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()) { Log.d(TAG, "not enabled"); return false; } Log.d(TAG, "enabled"); return true; }
17. Setup#setBluetooth()
Project: mHealthDroid
File: Setup.java
File: Setup.java
/** * Set the bluetooth connection ON/OFF * @param bluetooth boolean representing the desired bluetooth status */ public void setBluetooth(boolean bluetooth) { BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (bluetooth) mBluetoothAdapter.enable(); else mBluetoothAdapter.disable(); }
18. MainActivity#onCreate()
Project: inode-client
File: MainActivity.java
File: MainActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Prompt for permissions if (Build.VERSION.SDK_INT >= 23) { if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { Log.w("BleActivity", "Location access not granted!"); ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.ACCESS_COARSE_LOCATION }, MY_PERMISSION_RESPONSE); } } // selectively disable BLE-related features. if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) { Toast.makeText(this, "BLE not supported", Toast.LENGTH_SHORT).show(); finish(); } // Initializes a Bluetooth adapter. For API level 18 and above, get a reference to // BluetoothAdapter through BluetoothManager. final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); BluetoothAdapter mBluetoothAdapter = bluetoothManager.getAdapter(); // Checks if Bluetooth is supported on the device. if (mBluetoothAdapter == null) { Toast.makeText(this, "Bluetooth not supported", Toast.LENGTH_SHORT).show(); finish(); return; } Intent gattServiceIntent = new Intent(this, INodeService.class); bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE); }
19. GB#isBluetoothEnabled()
Project: Gadgetbridge
File: GB.java
File: GB.java
public static boolean isBluetoothEnabled() { BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter(); return adapter != null && adapter.isEnabled(); }
20. DeviceHelper#getAvailableDevices()
Project: Gadgetbridge
File: DeviceHelper.java
File: DeviceHelper.java
/** * Returns the list of all available devices that are supported by Gadgetbridge. * Note that no state is known about the returned devices. Even if one of those * devices is connected, it will report the default not-connected state. * * Clients interested in the "live" devices being managed should use the class * DeviceManager. * @param context * @return */ public Set<GBDevice> getAvailableDevices(Context context) { BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter(); Set<GBDevice> availableDevices = new LinkedHashSet<GBDevice>(); if (btAdapter == null) { GB.toast(context, context.getString(R.string.bluetooth_is_not_supported_), Toast.LENGTH_SHORT, GB.WARN); } else if (!btAdapter.isEnabled()) { GB.toast(context, context.getString(R.string.bluetooth_is_disabled_), Toast.LENGTH_SHORT, GB.WARN); } else { Set<BluetoothDevice> pairedDevices = btAdapter.getBondedDevices(); DeviceHelper deviceHelper = DeviceHelper.getInstance(); for (BluetoothDevice pairedDevice : pairedDevices) { GBDevice device = deviceHelper.toSupportedDevice(pairedDevice); if (device != null) { availableDevices.add(device); } } Prefs prefs = GBApplication.getPrefs(); String miAddr = prefs.getString(MiBandConst.PREF_MIBAND_ADDRESS, ""); if (miAddr.length() > 0) { GBDevice miDevice = new GBDevice(miAddr, "MI", DeviceType.MIBAND); if (!availableDevices.contains(miDevice)) { availableDevices.add(miDevice); } } String pebbleEmuAddr = prefs.getString("pebble_emu_addr", ""); String pebbleEmuPort = prefs.getString("pebble_emu_port", ""); if (pebbleEmuAddr.length() >= 7 && pebbleEmuPort.length() > 0) { GBDevice pebbleEmuDevice = new GBDevice(pebbleEmuAddr + ":" + pebbleEmuPort, "Pebble qemu", DeviceType.PEBBLE); availableDevices.add(pebbleEmuDevice); } } return availableDevices; }
21. BluetoothTestActivity#onCreate()
Project: CtsVerifier
File: BluetoothTestActivity.java
File: BluetoothTestActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.pass_fail_list); setPassFailButtonClickListeners(); setInfoResources(R.string.bluetooth_test, R.string.bluetooth_test_info, -1); BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (bluetoothAdapter == null) { Toast.makeText(this, "bluetooth not supported", Toast.LENGTH_SHORT); return; } List<String> disabledTestArray = new ArrayList<String>(); for (String s : this.getResources().getStringArray(R.array.disabled_tests)) { disabledTestArray.add(s); } if (!this.getPackageManager().hasSystemFeature("android.hardware.bluetooth_le")) { disabledTestArray.add("com.android.cts.verifier.bluetooth.BleAdvertiserTestActivity"); disabledTestArray.add("com.android.cts.verifier.bluetooth.BleScannerTestActivity"); disabledTestArray.add("com.android.cts.verifier.bluetooth.BleClientTestActivity"); disabledTestArray.add("com.android.cts.verifier.bluetooth.BleServerStartActivity"); } else if (!bluetoothAdapter.isMultipleAdvertisementSupported()) { disabledTestArray.add("com.android.cts.verifier.bluetooth.BleAdvertiserTestActivity"); disabledTestArray.add("com.android.cts.verifier.bluetooth.BleServerStartActivity"); } setTestListAdapter(new ManifestTestListAdapter(this, getClass().getName(), disabledTestArray.toArray(new String[disabledTestArray.size()]))); }
22. BluetoothUtil#setBluetooth()
Project: Commandr-Android
File: BluetoothUtil.java
File: BluetoothUtil.java
public static boolean setBluetooth(boolean enable) { BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); boolean isEnabled = bluetoothAdapter.isEnabled(); if (enable && !isEnabled) { return bluetoothAdapter.enable(); } else if (!enable && isEnabled) { return bluetoothAdapter.disable(); } // No need to change bluetooth state return true; }
23. AudioManagerAndroid#hasBluetoothHeadset()
Project: chromium_webview
File: AudioManagerAndroid.java
File: AudioManagerAndroid.java
/** * Gets the current Bluetooth headset state. * android.bluetooth.BluetoothAdapter.getProfileConnectionState() requires * the BLUETOOTH permission. */ private boolean hasBluetoothHeadset() { if (!mHasBluetoothPermission) { Log.wtf(TAG, "hasBluetoothHeadset() requires BLUETOOTH permission!"); return false; } // To get a BluetoothAdapter representing the local Bluetooth adapter, // when running on JELLY_BEAN_MR1 (4.2) and below, call the static // getDefaultAdapter() method; when running on JELLY_BEAN_MR2 (4.3) and // higher, retrieve it through getSystemService(String) with // BLUETOOTH_SERVICE. BluetoothAdapter btAdapter = null; if (runningOnJellyBeanMR2OrHigher()) { // Android 4.3 and above. try { BluetoothManager btManager = (BluetoothManager) mContext.getSystemService(Context.BLUETOOTH_SERVICE); btAdapter = btManager.getAdapter(); } catch (Exception e) { Log.wtf(TAG, "BluetoothManager.getAdapter exception", e); return false; } } else { // BluetoothAdapter. try { btAdapter = BluetoothAdapter.getDefaultAdapter(); } catch (Exception e) { Log.wtf(TAG, "BluetoothAdapter.getDefaultAdapter exception", e); return false; } } int profileConnectionState; try { profileConnectionState = btAdapter.getProfileConnectionState(android.bluetooth.BluetoothProfile.HEADSET); } catch (Exception e) { Log.wtf(TAG, "BluetoothAdapter.getProfileConnectionState exception", e); profileConnectionState = android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; } // redundant. It might be sufficient to only check the profile state. return btAdapter.isEnabled() && profileConnectionState == android.bluetooth.BluetoothProfile.STATE_CONNECTED; }
24. SystemLib#setBluetoothState()
Project: Cafe
File: SystemLib.java
File: SystemLib.java
/** * set bluetooth state * * @param true enabled false disabled * */ public void setBluetoothState(boolean enabled) { BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter(); if (bluetooth == null) //"device not BT capable"; return; if (enabled) { bluetooth.enable(); } else { bluetooth.disable(); } }
25. SystemLib#getBlueToothAddress()
Project: Cafe
File: SystemLib.java
File: SystemLib.java
/** * get bluetooth address * * @return 1. string of bluetooth addresss<br/> * 2. "device not BT capable"<br/> * 3. "Unavailable"<br/> */ public String getBlueToothAddress() { BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter(); if (bluetooth == null) { return "device not BT capable"; } String address = bluetooth.isEnabled() ? bluetooth.getAddress() : null; return TextUtils.isEmpty(address) ? "Unavailable" : address; }
26. DeviceFinder#findDevices()
Project: brailleback
File: DeviceFinder.java
File: DeviceFinder.java
/** * Returns a list of bonded and supported devices in the order they * should be tried. */ public List<DeviceInfo> findDevices() { BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter(); if (adapter == null) { return Collections.emptyList(); } List<DeviceInfo> ret = new ArrayList<DeviceInfo>(); Set<BluetoothDevice> bondedDevices = adapter.getBondedDevices(); for (BluetoothDevice dev : bondedDevices) { for (SupportedDevice matcher : SUPPORTED_DEVICES) { DeviceInfo matched = matcher.match(dev); if (matched != null) { ret.add(matched); } } } String lastAddress = mSharedPreferences.getString(LAST_CONNECTED_DEVICE_KEY, null); if (lastAddress != null) { // (Hence, the 1 below is intentional). for (int i = 1; i < ret.size(); ++i) { if (ret.get(i).getBluetoothDevice().getAddress().equals(lastAddress)) { Collections.swap(ret, 0, i); } } } return ret; }
27. BleSensorsRecordService#onCreate()
Project: BleSensorTag
File: BleSensorsRecordService.java
File: BleSensorsRecordService.java
@Override public void onCreate() { super.onCreate(); //noinspection PointlessBooleanExpression if (!AppConfig.ENABLE_RECORD_SERVICE) { stopSelf(); return; } final int bleStatus = BleUtils.getBleStatus(getBaseContext()); switch(bleStatus) { case BleUtils.STATUS_BLE_NOT_AVAILABLE: Toast.makeText(getApplicationContext(), R.string.dialog_error_no_ble, Toast.LENGTH_SHORT).show(); stopSelf(); return; case BleUtils.STATUS_BLUETOOTH_NOT_AVAILABLE: Toast.makeText(getApplicationContext(), R.string.dialog_error_no_bluetooth, Toast.LENGTH_SHORT).show(); stopSelf(); return; default: break; } // initialize scanner final BluetoothAdapter bluetoothAdapter = BleUtils.getBluetoothAdapter(getBaseContext()); scanner = new BleScanCompat(bluetoothAdapter, new BleScanCompat.BleDevicesScannerListener() { @Override public void onScanStarted() { } @Override public void onScanRepeat() { } @Override public void onScanStopped() { } @Override public void onLeScan(BluetoothDevice device, int i, byte[] bytes) { Log.d(TAG, "Device discovered: " + device.getName()); if (RECORD_DEVICE_NAME.equals(device.getName())) { scanner.stop(); getBleManager().connect(getBaseContext(), device.getAddress()); } } }); setServiceListener(this); }
28. SimpleLeScanner#stopScan()
Project: beacon-keeper
File: SimpleLeScanner.java
File: SimpleLeScanner.java
public void stopScan(LeScanCallback callback) { BluetoothAdapter ba = U.getBluetoothAdapter(mContext); if (ba != null && mIsScanning && callback != null) { ba.stopLeScan(callback); mIsScanning = false; onStopScan(); } else { L.wtf(TAG, "Failed to stopScan"); } }
29. DeviceUtil#bluetoothMAC()
Project: AndroidStudyDemo
File: DeviceUtil.java
File: DeviceUtil.java
/** * ??MAC?? * ???? <uses-permission android:name="android.permission.BLUETOOTH "/> * @param context * @return */ private static String bluetoothMAC(Context context) { String bluetoothMACStr = ""; BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); bluetoothMACStr = bluetoothAdapter.getAddress(); return bluetoothMACStr; }
30. DeviceStatusUtil#getBluetoothState()
Project: AndroidStudyDemo
File: DeviceStatusUtil.java
File: DeviceStatusUtil.java
/** * ??????? * * @return ???BluetoothAdapter????????STATE_OFF, STATE_TURNING_OFF, * STATE_ON, STATE_TURNING_ON * @throws Exception * ???????? */ public static int getBluetoothState() throws Exception { BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (bluetoothAdapter == null) { throw new Exception("bluetooth device not found!"); } else { return bluetoothAdapter.getState(); } }
31. MainActivity#startSyncProxyService()
Project: AndroidDemoProjects
File: MainActivity.java
File: MainActivity.java
private void startSyncProxyService() { boolean isPaired = false; BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter(); if (btAdapter != null) { if (btAdapter.isEnabled() && btAdapter.getBondedDevices() != null && !btAdapter.getBondedDevices().isEmpty()) { for (BluetoothDevice device : btAdapter.getBondedDevices()) { if (device.getName() != null && device.getName().contains(getString(R.string.device_name))) { isPaired = true; break; } } } if (isPaired) { if (AppLinkService.getInstance() == null) { Intent appLinkServiceIntent = new Intent(this, AppLinkService.class); startService(appLinkServiceIntent); } else { SyncProxyALM proxyInstance = AppLinkService.getInstance().getProxy(); if (proxyInstance == null) { AppLinkService.getInstance().startProxy(); } } } } }
32. LocalUnitTest#mockFinalClass()
Project: android-testing-templates
File: LocalUnitTest.java
File: LocalUnitTest.java
@Test public void mockFinalClass() { BluetoothAdapter adapter = mock(BluetoothAdapter.class); when(adapter.isEnabled()).thenReturn(true); assertTrue(adapter.isEnabled()); verify(adapter).isEnabled(); verifyNoMoreInteractions(adapter); }
33. MainActivity#onResume()
Project: android-obd-reader
File: MainActivity.java
File: MainActivity.java
protected void onResume() { super.onResume(); Log.d(TAG, "Resuming.."); sensorManager.registerListener(orientListener, orientSensor, SensorManager.SENSOR_DELAY_UI); wakeLock = powerManager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "ObdReader"); // get Bluetooth device final BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter(); preRequisites = btAdapter != null && btAdapter.isEnabled(); if (!preRequisites && prefs.getBoolean(ConfigActivity.ENABLE_BT_KEY, false)) { preRequisites = btAdapter != null && btAdapter.enable(); } gpsInit(); if (!preRequisites) { showDialog(BLUETOOTH_DISABLED); btStatusTextView.setText(getString(R.string.status_bluetooth_disabled)); } else { btStatusTextView.setText(getString(R.string.status_bluetooth_ok)); } }
34. ConfigActivity#onCreate()
Project: android-obd-reader
File: ConfigActivity.java
File: ConfigActivity.java
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); /* * Read preferences resources available at res/xml/preferences.xml */ addPreferencesFromResource(R.xml.preferences); checkGps(); ArrayList<CharSequence> pairedDeviceStrings = new ArrayList<>(); ArrayList<CharSequence> vals = new ArrayList<>(); ListPreference listBtDevices = (ListPreference) getPreferenceScreen().findPreference(BLUETOOTH_LIST_KEY); ArrayList<CharSequence> protocolStrings = new ArrayList<>(); ListPreference listProtocols = (ListPreference) getPreferenceScreen().findPreference(PROTOCOLS_LIST_KEY); String[] prefKeys = new String[] { ENGINE_DISPLACEMENT_KEY, VOLUMETRIC_EFFICIENCY_KEY, OBD_UPDATE_PERIOD_KEY, MAX_FUEL_ECON_KEY }; for (String prefKey : prefKeys) { EditTextPreference txtPref = (EditTextPreference) getPreferenceScreen().findPreference(prefKey); txtPref.setOnPreferenceChangeListener(this); } /* * Available OBD commands * * TODO This should be read from preferences database */ ArrayList<ObdCommand> cmds = ObdConfig.getCommands(); PreferenceScreen cmdScr = (PreferenceScreen) getPreferenceScreen().findPreference(COMMANDS_SCREEN_KEY); for (ObdCommand cmd : cmds) { CheckBoxPreference cpref = new CheckBoxPreference(this); cpref.setTitle(cmd.getName()); cpref.setKey(cmd.getName()); cpref.setChecked(true); cmdScr.addPreference(cpref); } /* * Available OBD protocols * */ for (ObdProtocols protocol : ObdProtocols.values()) { protocolStrings.add(protocol.name()); } listProtocols.setEntries(protocolStrings.toArray(new CharSequence[0])); listProtocols.setEntryValues(protocolStrings.toArray(new CharSequence[0])); /* * Let's use this device Bluetooth adapter to select which paired OBD-II * compliant device we'll use. */ final BluetoothAdapter mBtAdapter = BluetoothAdapter.getDefaultAdapter(); if (mBtAdapter == null) { listBtDevices.setEntries(pairedDeviceStrings.toArray(new CharSequence[0])); listBtDevices.setEntryValues(vals.toArray(new CharSequence[0])); // we shouldn't get here, still warn user Toast.makeText(this, "This device does not support Bluetooth.", Toast.LENGTH_LONG).show(); return; } /* * Listen for preferences click. * * TODO there are so many repeated validations :-/ */ final Activity thisActivity = this; listBtDevices.setEntries(new CharSequence[1]); listBtDevices.setEntryValues(new CharSequence[1]); listBtDevices.setOnPreferenceClickListener(new OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { // see what I mean in the previous comment? if (mBtAdapter == null || !mBtAdapter.isEnabled()) { Toast.makeText(thisActivity, "This device does not support Bluetooth or it is disabled.", Toast.LENGTH_LONG).show(); return false; } return true; } }); /* * Get paired devices and populate preference list. */ Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices(); if (pairedDevices.size() > 0) { for (BluetoothDevice device : pairedDevices) { pairedDeviceStrings.add(device.getName() + "\n" + device.getAddress()); vals.add(device.getAddress()); } } listBtDevices.setEntries(pairedDeviceStrings.toArray(new CharSequence[0])); listBtDevices.setEntryValues(vals.toArray(new CharSequence[0])); }
35. BleProfileServiceReadyActivity#isBLEEnabled()
Project: Android-nRF-Toolbox
File: BleProfileServiceReadyActivity.java
File: BleProfileServiceReadyActivity.java
protected boolean isBLEEnabled() { final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); final BluetoothAdapter adapter = bluetoothManager.getAdapter(); return adapter != null && adapter.isEnabled(); }
36. BleProfileExpandableListActivity#isBLEEnabled()
Project: Android-nRF-Toolbox
File: BleProfileExpandableListActivity.java
File: BleProfileExpandableListActivity.java
protected boolean isBLEEnabled() { final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); final BluetoothAdapter adapter = bluetoothManager.getAdapter(); return adapter != null && adapter.isEnabled(); }
37. BleProfileActivity#isBLEEnabled()
Project: Android-nRF-Toolbox
File: BleProfileActivity.java
File: BleProfileActivity.java
protected boolean isBLEEnabled() { final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); final BluetoothAdapter adapter = bluetoothManager.getAdapter(); return adapter != null && adapter.isEnabled(); }
38. DfuActivity#isBLEEnabled()
Project: Android-nRF-Toolbox
File: DfuActivity.java
File: DfuActivity.java
private boolean isBLEEnabled() { final BluetoothManager manager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); final BluetoothAdapter adapter = manager.getAdapter(); return adapter != null && adapter.isEnabled(); }
39. BluetoothCrashResolver#startRecovery()
Project: android-beacon-library
File: BluetoothCrashResolver.java
File: BluetoothCrashResolver.java
@TargetApi(17) private void startRecovery() { // The discovery operation will start by clearing out the Bluetooth mac list to only the 256 // most recently seen BLE mac addresses. recoveryAttemptCount++; BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter(); LogManager.d(TAG, "about to check if discovery is active"); if (!adapter.isDiscovering()) { LogManager.w(TAG, "Recovery attempt started"); recoveryInProgress = true; discoveryStartConfirmed = false; LogManager.d(TAG, "about to command discovery"); if (!adapter.startDiscovery()) { LogManager.w(TAG, "Can't start discovery. Is Bluetooth turned on?"); } LogManager.d(TAG, "startDiscovery commanded. isDiscovering()=%s", adapter.isDiscovering()); // terms of battery, we will cancel it. if (TIME_TO_LET_DISCOVERY_RUN_MILLIS > 0) { LogManager.d(TAG, "We will be cancelling this discovery in %s milliseconds.", TIME_TO_LET_DISCOVERY_RUN_MILLIS); cancelDiscovery(); } else { LogManager.d(TAG, "We will let this discovery run its course."); } } else { LogManager.w(TAG, "Already discovering. Recovery attempt abandoned."); } }