Java Code Examples for android.bluetooth.BluetoothAdapter
The following examples show how to use
android.bluetooth.BluetoothAdapter. These examples are extracted from open source projects.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: neatle Source File: BaseScanner.java License: MIT License | 6 votes |
private void conditionalStart() { BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter(); if (adapter == null) { NeatleLogger.e("Bluetooth LE scan failed to start. No bluetooth adapter found"); return; } int adapterState = adapter.getState(); if (adapterState != BluetoothAdapter.STATE_ON) { NeatleLogger.e("Bluetooth off, will start scanning when it turns on."); pause(); return; } onStart(adapter, scanMode); doStarted = true; if (scanDuration > 0) { handler.postDelayed(pauseCallback, scanDuration); } }
Example 2
Source Project: grblcontroller Source File: GrblBluetoothSerialService.java License: GNU General Public License v3.0 | 6 votes |
@Override public void onCreate(){ super.onCreate(); mAdapter = BluetoothAdapter.getDefaultAdapter(); mState = STATE_NONE; mNewState = mState; if(mAdapter == null){ EventBus.getDefault().post(new UiToastEvent(getString(R.string.text_bluetooth_adapter_error), true, true)); stopSelf(); }else{ if(Build.VERSION.SDK_INT > Build.VERSION_CODES.N_MR1){ startForeground(Constants.BLUETOOTH_SERVICE_NOTIFICATION_ID, this.getNotification(null)); } serialBluetoothCommunicationHandler = new SerialBluetoothCommunicationHandler(this); EventBus.getDefault().register(this); } }
Example 3
Source Project: Bluefruit_LE_Connect_Android_V2 Source File: BleUtils.java License: MIT License | 6 votes |
public static int getBleStatus(Context context) { if (!context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) { return STATUS_BLE_NOT_AVAILABLE; } final BluetoothAdapter adapter = getBluetoothAdapter(context); // Checks if Bluetooth is supported on the device. if (adapter == null) { return STATUS_BLUETOOTH_NOT_AVAILABLE; } if (!adapter.isEnabled()) { return STATUS_BLUETOOTH_DISABLED; } return STATUS_BLE_ENABLED; }
Example 4
Source Project: sdl_java_suite Source File: MediaStreamingStatus.java License: BSD 3-Clause "New" or "Revised" License | 6 votes |
@SuppressLint("MissingPermission") boolean isBluetoothActuallyAvailable(){ BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter(); if(adapter == null || !adapter.isEnabled() ){ //False positive return false; } if(android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH ){ int state = adapter.getProfileConnectionState(BluetoothProfile.A2DP); if(state != BluetoothAdapter.STATE_CONNECTING && state != BluetoothAdapter.STATE_CONNECTED){ //False positive return false; } } return true; }
Example 5
Source Project: apollo-DuerOS Source File: HomeActivity.java License: Apache License 2.0 | 6 votes |
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); mLocationManager.addGpsStatusListener(mGpsStatusListener); mWifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE); mConnectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED); intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); registerReceiver(mReceiver, intentFilter); updateBlueToothStatus(); }
Example 6
Source Project: IoT-Firstep Source File: DeviceScanActivity.java License: GNU General Public License v3.0 | 6 votes |
@Override protected void onResume() { super.onResume(); //如果没开蓝牙,请求打开蓝牙 if (!mBluetoothAdapter.isEnabled()) { if (!mBluetoothAdapter.isEnabled()) { Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); } } // Initializes list view adapter. mAdapter = new LeDeviceListAdapter(this); mLView.setAdapter(mAdapter); mLView.setOnItemClickListener(this); scanLeDevice(true); }
Example 7
Source Project: AsteroidOSSync Source File: P_AndroidBluetoothManager.java License: GNU General Public License v3.0 | 6 votes |
@Override public final void stopLeScan(BluetoothAdapter.LeScanCallback callback) { if (m_adaptor != null) { if (m_bleManager.getScanManager().isPostLollipopScan()) { L_Util.stopNativeScan(m_adaptor); } else { m_adaptor.stopLeScan(callback); } } else m_bleManager.getLogger().e("Tried to stop scan (if it's even running), but the Bluetooth Adaptor is null!"); }
Example 8
Source Project: blefun-androidthings Source File: GattServer.java License: Apache License 2.0 | 6 votes |
@Override public void onReceive(Context context, Intent intent) { int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.STATE_OFF); switch (state) { case BluetoothAdapter.STATE_ON: startAdvertising(); startServer(); break; case BluetoothAdapter.STATE_OFF: stopServer(); stopAdvertising(); break; default: // Do nothing break; } }
Example 9
Source Project: microbit Source File: PairingActivity.java License: Apache License 2.0 | 6 votes |
/** * Finds all bonded devices and tries to unbond it. */ private void unPairDevice() { ConnectedDevice connectedDevice = BluetoothUtils.getPairedMicrobit(this); String addressToDelete = connectedDevice.mAddress; // Get the paired devices and put them in a Set BluetoothAdapter mBluetoothAdapter = ((BluetoothManager) getSystemService(BLUETOOTH_SERVICE)).getAdapter(); Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices(); for(BluetoothDevice bt : pairedDevices) { logi("Paired device " + bt.getName()); if(bt.getAddress().equals(addressToDelete)) { try { Method m = bt.getClass().getMethod("removeBond", (Class[]) null); m.invoke(bt, (Object[]) null); } catch(NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { Log.e(TAG, e.toString()); } } } }
Example 10
Source Project: linphone-android Source File: AndroidAudioManager.java License: GNU General Public License v3.0 | 6 votes |
private void startBluetooth() { mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (mBluetoothAdapter != null) { Log.i("[Audio Manager] [Bluetooth] Adapter found"); if (mAudioManager.isBluetoothScoAvailableOffCall()) { Log.i("[Audio Manager] [Bluetooth] SCO available off call, continue"); } else { Log.w("[Audio Manager] [Bluetooth] SCO not available off call !"); } mBluetoothReceiver = new BluetoothReceiver(); IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED); mContext.registerReceiver(mBluetoothReceiver, filter); bluetoothAdapterStateChanged(); } }
Example 11
Source Project: PresencePublisher Source File: AddBeaconChoicePreferenceDummy.java License: MIT License | 6 votes |
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2) public AddBeaconChoicePreferenceDummy(Context context, Fragment fragment) { super(context); setKey(DUMMY); setIcon(android.R.drawable.ic_menu_add); setTitle(R.string.add_beacon_title); setSummary(R.string.add_beacon_summary); setOnPreferenceClickListener(prefs -> { BluetoothManager bluetoothManager = (BluetoothManager) getContext().getSystemService(Context.BLUETOOTH_SERVICE); if (bluetoothManager == null) { HyperLog.w(TAG, "Unable to get bluetooth manager"); } else { BluetoothAdapter bluetoothAdapter = bluetoothManager.getAdapter(); if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()) { Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); fragment.startActivityForResult(enableBtIntent, ON_DEMAND_BLUETOOTH_REQUEST_CODE); return true; } } BeaconScanDialogFragment instance = getInstance(getContext(), this::onScanResult, getSharedPreferences().getStringSet(BEACON_LIST, Collections.emptySet())); instance.show(fragment.requireFragmentManager(), null); return true; }); }
Example 12
Source Project: SmartOrnament Source File: LinkDeviceFragment.java License: Apache License 2.0 | 6 votes |
@Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated mEt_msgContenthod stub String action = intent.getAction(); if (BluetoothDevice.ACTION_FOUND.equals(action)) { BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); if (mDeviceList.contains(device)) { //防止重复添加蓝牙设备 return; } mArrayList.add(device.getName() + "\n" + device.getAddress()); mDeviceList.add(device); adapter.notifyDataSetChanged(); //通知数据源更新,刷新蓝牙列表 } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) { //Toast.makeText(MainActivity.this, "搜索完成!", Toast.LENGTH_SHORT).show(); } }
Example 13
Source Project: science-journal Source File: MkrSciBleManager.java License: Apache License 2.0 | 6 votes |
public static void subscribe( Context context, String address, String characteristic, Listener listener) { synchronized (gattHandlers) { GattHandler gattHandler = gattHandlers.get(address); if (gattHandler == null) { BluetoothManager manager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE); if (manager == null) { return; } BluetoothAdapter adapter = manager.getAdapter(); BluetoothDevice device = adapter.getRemoteDevice(address); gattHandler = new GattHandler(); gattHandlers.put(address, gattHandler); device.connectGatt(context, true /* autoConnect */, gattHandler); } gattHandler.subscribe(characteristic, listener); } }
Example 14
Source Project: tilt-game-android Source File: BluetoothServerConnectionHelper.java License: MIT License | 6 votes |
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); } }
Example 15
Source Project: retroband Source File: MainActivity.java License: Apache License 2.0 | 6 votes |
/** * Initialization / Finalization */ private void initialize() { Logs.d(TAG, "# Activity - initialize()"); mService.setupService(mActivityHandler); // If BT is not on, request that it be enabled. // RetroWatchService.setupBT() will then be called during onActivityResult if(!mService.isBluetoothEnabled()) { Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableIntent, Constants.REQUEST_ENABLE_BT); } // Load activity reports and display if(mRefreshTimer != null) { mRefreshTimer.cancel(); } // Use below timer if you want scheduled job //mRefreshTimer = new Timer(); //mRefreshTimer.schedule(new RefreshTimerTask(), 5*1000); }
Example 16
Source Project: unity-bluetooth Source File: BCLServiceServer.java License: MIT License | 6 votes |
private void discoverableDevice() { boolean bonded = false; for (BluetoothDevice device : mPairedDevices) { if (mPairingAddress.equals(device.getAddress())) { bonded = true; break; } } if (!bonded) { Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300); mActivity.startActivity(discoverableIntent); } mAcceptThread = new AcceptThread(); mAcceptThread.start(); }
Example 17
Source Project: Android-Bluetooth-Fingerprint Source File: DashBoardActivity.java License: Apache License 2.0 | 6 votes |
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_dash_board); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT); Toolbar toolbar = (Toolbar) findViewById(R.id.dash_board_toolbar); setSupportActionBar(toolbar); // Get local Bluetooth adapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); // If the adapter is null, then Bluetooth is not supported if (mBluetoothAdapter == null) { showSnackBar("Bluetooth is not available"); finish(); } }
Example 18
Source Project: redalert-android Source File: BluetoothIntegration.java License: Apache License 2.0 | 6 votes |
public static boolean isBluetoothEnabled() { // Must call Looper.prepare() due to ICS bug // And we can't call the function from UI thread when we receive a push notification) // http://stackoverflow.com/questions/5920578/bluetoothadapter-getdefault-throwing-runtimeexception-while-not-in-activity if (Looper.myLooper() == null) { Looper.prepare(); } // Get bluetooth adapter BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); // Null means device doesn't support Bluetooth if (bluetoothAdapter == null) { // No Bluetooth support return false; } else { // Check if it's enabled and return the result return bluetoothAdapter.isEnabled(); } }
Example 19
Source Project: DataLogger Source File: DisplayActivity.java License: MIT License | 6 votes |
public void onClick(View v) { int state = SharedPreferencesHelper.getBluetoothStatus(DisplayActivity.this); switch (state) { case Constants.BLUETOOTH_STATE_DISABLED: startActivityForResult(new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE), 0); break; case Constants.BLUETOOTH_STATE_ENABLED: case Constants.BLUETOOTH_STATE_CONNECTING: case Constants.BLUETOOTH_STATE_CONNECTED: boolean isMaster = (mDeviceLocation == Constants.DEVICE_LOCATION_HAND); if (isMaster) { Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300); startActivity(discoverableIntent); } else { Intent serverIntent = new Intent(DisplayActivity.this, BluetoothDeviceListActivity.class); startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE); } break; } }
Example 20
Source Project: EFRConnect-android Source File: BrowserActivity.java License: Apache License 2.0 | 5 votes |
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == BlUETOOTH_SETTINGS_REQUEST_CODE) { BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (!bluetoothAdapter.isEnabled() && bluetoothEnableDialog != null) { bluetoothEnableDialog.show(); } } }
Example 21
Source Project: sample-bluetooth-audio Source File: A2dpSinkActivity.java License: Apache License 2.0 | 5 votes |
/** * Enable the current {@link BluetoothAdapter} to be discovered (available for pairing) for * the next {@link #DISCOVERABLE_TIMEOUT_MS} ms. */ private void enableDiscoverable() { Log.d(TAG, "Registering for discovery."); Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, DISCOVERABLE_TIMEOUT_MS); startActivityForResult(discoverableIntent, REQUEST_CODE_ENABLE_DISCOVERABLE); }
Example 22
Source Project: wearmouse Source File: BluetoothStateActivity.java License: Apache License 2.0 | 5 votes |
private void checkState(int state) { if (state != BluetoothAdapter.STATE_TURNING_ON && state != BluetoothAdapter.STATE_TURNING_OFF) { finish(); } else { ((TextView) findViewById(R.id.title)) .setText( getString( state == BluetoothAdapter.STATE_TURNING_ON ? R.string.pref_bluetooth_turningOn : R.string.pref_bluetooth_turningOff)); } }
Example 23
Source Project: Bluefruit_LE_Connect_Android_V2 Source File: GattServer.java License: MIT License | 5 votes |
public GattServer(Context context, Listener listener) { mListener = listener; mBluetoothManager = (BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE); // Update internal status onBluetoothStateChanged(context); // Set Ble status receiver IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED); LocalBroadcastManager.getInstance(context).registerReceiver(mBleAdapterStateReceiver, filter); }
Example 24
Source Project: react-native-sunmi-inner-printer Source File: BluetoothUtil.java License: MIT License | 5 votes |
public static BluetoothDevice getDevice(BluetoothAdapter bluetoothAdapter) { BluetoothDevice innerprinter_device = null; Set<BluetoothDevice> devices = bluetoothAdapter.getBondedDevices(); for (BluetoothDevice device : devices) { if (device.getAddress().equals(Innerprinter_Address)) { innerprinter_device = device; break; } } return innerprinter_device; }
Example 25
Source Project: AsteroidOSSync Source File: P_AndroidBluetoothManager.java License: GNU General Public License v3.0 | 5 votes |
@Override public final boolean startLeScan(BluetoothAdapter.LeScanCallback callback) { if (m_adaptor != null) return m_adaptor.startLeScan(callback); return false; }
Example 26
Source Project: DeviceConnect-Android Source File: HeartRateDeviceService.java License: MIT License | 5 votes |
@Override public void onReceive(final Context context, final Intent intent) { String action = intent.getAction(); if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) { int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1); if (state == BluetoothAdapter.STATE_ON) { getManager().start(); } else if (state == BluetoothAdapter.STATE_OFF) { getManager().stop(); } } }
Example 27
Source Project: blue-pair Source File: BroadcastReceiverDelegator.java License: MIT License | 5 votes |
/** * Instantiates a new BroadcastReceiverDelegator. * * @param context the context of this object. * @param listener a callback for handling Bluetooth events. * @param bluetooth a controller for the Bluetooth. */ public BroadcastReceiverDelegator(Context context, BluetoothDiscoveryDeviceListener listener, BluetoothController bluetooth) { this.listener = listener; this.context = context; this.listener.setBluetoothController(bluetooth); // Register for broadcasts when a device is discovered. IntentFilter filter = new IntentFilter(); filter.addAction(BluetoothDevice.ACTION_FOUND); filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED); filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED); context.registerReceiver(this, filter); }
Example 28
Source Project: appium-uiautomator2-server Source File: GetDeviceInfo.java License: Apache License 2.0 | 5 votes |
@Nullable private static BluetoothInfoModel extractBluetoothInfo(DeviceInfoHelper deviceInfoHelper) { BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); return bluetoothAdapter == null ? null : new BluetoothInfoModel(deviceInfoHelper.toBluetoothStateString(bluetoothAdapter.getState())); }
Example 29
Source Project: android_9.0.0_r45 Source File: BluetoothManagerService.java License: Apache License 2.0 | 5 votes |
/** * if on is true, wait for state become ON * if off is true, wait for state become OFF * if both on and off are false, wait for state not ON */ private boolean waitForOnOff(boolean on, boolean off) { int i = 0; while (i < 10) { try { mBluetoothLock.readLock().lock(); if (mBluetooth == null) { break; } if (on) { if (mBluetooth.getState() == BluetoothAdapter.STATE_ON) { return true; } } else if (off) { if (mBluetooth.getState() == BluetoothAdapter.STATE_OFF) { return true; } } else { if (mBluetooth.getState() != BluetoothAdapter.STATE_ON) { return true; } } } catch (RemoteException e) { Slog.e(TAG, "getState()", e); break; } finally { mBluetoothLock.readLock().unlock(); } if (on || off) { SystemClock.sleep(300); } else { SystemClock.sleep(50); } i++; } Slog.e(TAG, "waitForOnOff time out"); return false; }
Example 30
Source Project: connectivity-samples Source File: BluetoothChatService.java License: Apache License 2.0 | 5 votes |
/** * Constructor. Prepares a new BluetoothChat session. * * @param context The UI Activity Context * @param handler A Handler to send messages back to the UI Activity */ public BluetoothChatService(Context context, Handler handler) { mAdapter = BluetoothAdapter.getDefaultAdapter(); mState = STATE_NONE; mNewState = mState; mHandler = handler; }