@Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); // When discovery finds a device if (BluetoothDevice.ACTION_FOUND.equals(action)) { // Get the BluetoothDevice object from the Intent BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); // If it's already paired, skip it, because it's been listed already if (device.getBondState() != BluetoothDevice.BOND_BONDED) { mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress()); } // When discovery is finished, change the Activity title } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) { setProgressBarIndeterminateVisibility(false); setTitle(R.string.select_device); if (mNewDevicesArrayAdapter.getCount() == 0) { String noDevices = getResources().getText(R.string.none_found).toString(); mNewDevicesArrayAdapter.add(noDevices); } } }
@ReactMethod public void connect(String peripheralUUID, Callback callback) { Log.d(LOG_TAG, "Connect to: " + peripheralUUID ); synchronized(peripherals) { Peripheral peripheral = peripherals.get(peripheralUUID); Log.e(LOG_TAG, "peripheral " + peripheral); if (peripheral == null) { if (peripheralUUID != null) { peripheralUUID = peripheralUUID.toUpperCase(); } if (BluetoothAdapter.checkBluetoothAddress(peripheralUUID)) { BluetoothDevice device = bluetoothAdapter.getRemoteDevice(peripheralUUID); peripheral = new Peripheral(device, reactContext); peripherals.put(peripheralUUID, peripheral); } else { callback.invoke("Invalid peripheral uuid"); return; } } peripheral.connect(callback, reactContext!=null?getCurrentActivity():context); } }
private boolean ensureInit() { if (mBluetoothAdapter == null) { mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); } if (mContext == null) { if (LinphoneService.isReady()) { mContext = LinphoneService.instance().getApplicationContext(); } else { return false; } } if (mContext != null && mAudioManager == null) { mAudioManager = ((AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE)); } return true; }
public BluetoothStateManager(@NonNull Context context, @Nullable BluetoothStateListener listener) { this.context = context.getApplicationContext(); this.bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); this.bluetoothScoReceiver = new BluetoothScoReceiver(); this.bluetoothConnectionReceiver = new BluetoothConnectionReceiver(); this.listener = listener; if (this.bluetoothAdapter == null) return; requestHeadsetProxyProfile(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { context.registerReceiver(bluetoothConnectionReceiver, new IntentFilter(BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED)); } Intent sticky = context.registerReceiver(bluetoothScoReceiver, new IntentFilter(getScoChangeIntent())); if (sticky != null) { bluetoothScoReceiver.onReceive(context, sticky); } handleBluetoothStateChange(); }
private static IntentFilter pairIntentFilter() { final IntentFilter intentFilter = new IntentFilter(); /* reserved for other usages */ /* intentFilter.addAction(BluetoothDevice.ACTION_FOUND); intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED); intentFilter.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED); intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED); intentFilter.addAction(BluetoothDevice.ACTION_PAIRING_REQUEST); */ intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED); intentFilter.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED); intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED); intentFilter.addAction(BluetoothDevice.ACTION_PAIRING_REQUEST); intentFilter.addAction("com.bluetooth.device.action.FOUND"); intentFilter.setPriority(Integer.MAX_VALUE); return intentFilter; }
@Override public void onResume() { super.onResume(); // Register ChipRobotFinder broadcast receiver this.getActivity().registerReceiver(mChipFinderBroadcastReceiver, ChipRobotFinder.getChipRobotFinderIntentFilter()); // Ensures Bluetooth is enabled on the device. If Bluetooth is not currently enabled, // fire an intent to display a dialog asking the user to grant permission to enable it. if (mBluetoothAdapter != null && !mBluetoothAdapter.isEnabled()) { if (!mBluetoothAdapter.isEnabled()) { try { Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); } catch (ActivityNotFoundException ex) { } } } // Start scan ChipRobotFinder.getInstance().clearFoundChipList(); scanLeDevice(false); updateChipList(); scanLeDevice(true); }
public void sendFDroid() { // If Bluetooth has not been enabled/turned on, then enabling device discoverability // will automatically enable Bluetooth. BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter(); if (adapter != null) { if (adapter.getState() != BluetoothAdapter.STATE_ON) { Intent discoverBt = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); discoverBt.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 120); startActivityForResult(discoverBt, REQUEST_BLUETOOTH_ENABLE_FOR_SEND); } else { sendFDroidApk(); } } else { new AlertDialog.Builder(this) .setTitle(R.string.bluetooth_unavailable) .setMessage(R.string.swap_cant_send_no_bluetooth) .setNegativeButton( R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } } ).create().show(); } }
/** * connect the device to bluetooth * * @param context the context * @param deviceInfo the device info * @param receiver the receiver * @throws DeviceConnectException the device connect exception */ public void connectToBluetooth(Context context, DeviceInfoBean deviceInfo, IHealthCareReceiver receiver) throws DeviceConnectException { isDeviceFound = false; iHealthCareReceiver = receiver; mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (mBluetoothAdapter == null) { throw new DeviceConnectException(mContext.getString(R.string.bluetooth_settings_problem)); } mContext = context; mDeviceInfo = deviceInfo; IntentFilter filter = new IntentFilter(); filter.addAction(BluetoothDevice.ACTION_FOUND); filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED); filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED); filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED); filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); mContext.getApplicationContext().registerReceiver(mReceiver, filter); if (mBluetoothAdapter.getState() != BluetoothAdapter.STATE_ON) throw new DeviceConnectException(mContext.getString(R.string.bluetooth_state_not_ready)); mBluetoothAdapter.startDiscovery(); }
private void addStateListener() { if (this.stateReceiver == null) { this.stateReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { onBluetoothStateChange(intent); } }; } try { IntentFilter intentFilter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED); webView.getContext().registerReceiver(this.stateReceiver, intentFilter); } catch (Exception e) { LOG.e(TAG, "Error registering state receiver: " + e.getMessage(), e); } }
@Override public void handleClick() { if (mBluetoothEnableForTether) return; if (isTetheringOn()) { setTethering(false); } else { BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter(); if (adapter != null) { if (adapter.getState() == BluetoothAdapter.STATE_OFF) { mBluetoothEnableForTether = true; adapter.enable(); } else if (adapter.getState() == BluetoothAdapter.STATE_ON) { setTethering(true); } } } refreshState(); }
/** * Logs the state of the local Bluetooth adapter. */ protected void logBluetoothAdapterInfo(BluetoothAdapter localAdapter) { Log.d(TAG, "BluetoothAdapter: " + "enabled=" + localAdapter.isEnabled() + ", " + "state=" + stateToString(localAdapter.getState()) + ", " + "name=" + localAdapter.getName() + ", " + "address=" + localAdapter.getAddress()); // Log the set of BluetoothDevice objects that are bonded (paired) to the local adapter. Set<BluetoothDevice> pairedDevices = localAdapter.getBondedDevices(); if (!pairedDevices.isEmpty()) { Log.d(TAG, "paired devices:"); for (BluetoothDevice device : pairedDevices) { Log.d(TAG, " name=" + device.getName() + ", address=" + device.getAddress()); } } }
@Override public void onReceive(Context context, Intent intent) { switch (intent.getAction()) { case BluetoothAdapter.ACTION_STATE_CHANGED: int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR); switch (state) { case BluetoothAdapter.STATE_TURNING_ON:// 蓝牙打开中 break; case BluetoothAdapter.STATE_ON:// 蓝牙打开完成 break; case BluetoothAdapter.STATE_TURNING_OFF:// 蓝牙关闭中 break; case BluetoothAdapter.STATE_OFF:// 蓝牙关闭完成 break; default: break; } default: break; } }
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if(D) Log.e(TAG, "+++ ON CREATE +++"); // Set up the window layout setContentView(R.layout.main); // Get local Bluetooth adapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); // If the adapter is null, then Bluetooth is not supported if (mBluetoothAdapter == null) { Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show(); finish(); return; } }
private void startAdvertising() { BluetoothAdapter bluetoothAdapter = mBluetoothManager.getAdapter(); mBluetoothLeAdvertiser = bluetoothAdapter.getBluetoothLeAdvertiser(); if (mBluetoothLeAdvertiser == null) { Log.w(TAG, "Failed to create advertiser"); return; } AdvertiseSettings settings = new AdvertiseSettings.Builder() .setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_BALANCED) .setConnectable(true) .setTimeout(0) .setTxPowerLevel(AdvertiseSettings.ADVERTISE_TX_POWER_MEDIUM) .build(); AdvertiseData data = new AdvertiseData.Builder() .setIncludeDeviceName(true) .setIncludeTxPowerLevel(false) .addServiceUuid(new ParcelUuid(SERVICE_UUID)) .build(); mBluetoothLeAdvertiser .startAdvertising(settings, data, mAdvertiseCallback); }
private boolean openBtDevice() { // 获得蓝牙匹配器 mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); // 蓝牙设备不被支持 if (mBluetoothAdapter == null) { Toast.makeText(getActivity(), "该设备没有蓝牙设备", Toast.LENGTH_LONG).show(); return false; } // 蓝牙如果没打开,直接提示需要打开蓝牙 if (!mBluetoothAdapter.isEnabled()) { // 隐式Intent Intent enableBtIntent = new Intent( BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, REQUES_BT_ENABLE_CODE); //在onActivityResult有打开服务端线程的操作哦 } else { // 如果蓝牙在运行本程序前已经人为打开,那么直接启动服务器端线程 Toast.makeText(getActivity(), "蓝牙已经打开! ", Toast.LENGTH_LONG).show(); //暂时不启动服务端线程,因为手机充当的总是客服端 // mAcceptThread = new AcceptThread(mBluetoothAdapter,mHandler); // // // // // // // // // // // // // // // // // // // // // // // // // // mAcceptThread.start(); // // // // // // // // // // // // // // // //蓝牙提前打开就启动服务端线程? // // // // // // } return true; }
public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(BluetoothDevice.ACTION_FOUND)) { BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); if (!BluetoothDevicesActivity.this.deviceList.contains(device)) { BluetoothDevicesActivity.this.deviceList.add(device); BluetoothDevicesActivity.this.deviceListAdapter.notifyDataSetChanged(); } } else if (action.equals(BluetoothAdapter.ACTION_DISCOVERY_STARTED)) { Toast.makeText(context, "Bluetooth discovery started", Toast.LENGTH_SHORT).show(); } else if (action.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)) { Toast.makeText(context, "Bluetooth discovery finished", Toast.LENGTH_SHORT).show(); } }
private void setupBLE() { if (!isBLESupported(this)) { Toast.makeText(this, "device not support ble", Toast.LENGTH_SHORT).show(); finish(); return; } BluetoothManager manager = getManager(this); if (manager != null) { mBTAdapter = manager.getAdapter(); } if ((mBTAdapter == null) || (!mBTAdapter.isEnabled())) { Toast.makeText(this, "bluetooth not open", Toast.LENGTH_SHORT).show(); Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); return; } }
public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) { Log.d("BLUETOOTH", "DISCOVERY STARTED"); //lo que se ejecuta cuando el bluetooth comienza a escanear } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) { //lo que se ejecuta cuando el bluetooth finaliza el escaneo Log.d("BLUETOOTH", "DISCOVERY FINISHED"); } else if (BluetoothDevice.ACTION_FOUND.equals(action)) { //lo que se ejecuta cuando el bluetooth encuentra un dispositivo final BluetoothDevice device = (BluetoothDevice) intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); Log.d("BLUETOOTH", "DEVICE DISCOVERED"); listaDevices.put(device.getAddress(), device); Bundle bundle = new Bundle(); bundle.putString("address", device.getAddress()); //TODO crear constantes para los codigos de envio resultReceiverListarYConectar.send(100, bundle); /*runOnUiThread(new Runnable() { @Override public void run() { list.add(device.getAddress()); listaDevices.put(device.getAddress(), device); adapter.notifyDataSetChanged(); } });*/ } }
public void makeDiscoverable() { if (mBluetoothAdapter == null) { return; } else { if (mBluetoothAdapter.isEnabled() && isDiscoverable()) { Log.e("", "===> mBluetoothAdapter.isDiscoverable()"); return; } else { Log.e("", "===> makeDiscoverable"); Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, mTimeDiscoverable); mActivity.startActivityForResult(discoverableIntent, REQUEST_DISCOVERABLE_CODE); } } }
@Override public void onStart() { super.onStart(); // Listen for changes to the Bluetooth state IntentFilter filter = new IntentFilter(); filter.addAction(ACTION_STATE_CHANGED); receiver = new BluetoothStateReceiver(); getActivity().registerReceiver(receiver, filter); // Enable BT adapter if it is not already on. final BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter(); if (adapter != null && !adapter.isEnabled()) { waitingForBluetooth = true; androidExecutor.runOnBackgroundThread(new Runnable() { @Override public void run() { adapter.enable(); } }); } else { startListening(); } cameraView.start(); }
public void onDestroy() { mListener = null; BluetoothAdapter bluetoothAdapter = mBluetoothManager.getAdapter(); if (bluetoothAdapter.isEnabled()) { stopClient(); } mContext.unregisterReceiver(mBluetoothReceiver); }
@Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action) && intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR) == BluetoothAdapter.STATE_OFF) { //Device has disconnected Toast.makeText(BluetoothConnector.this, R.string.bluetooth_required_leaving, Toast.LENGTH_LONG).show(); BluetoothConnector.this.finish(); } }
@Override public void onStart() { super.onStart(); Log.e(TAG, "onStart"); if (BluetoothAdapter.getDefaultAdapter() == null) { Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show(); return; } }
@Override public void flushPendingScanResults(BluetoothAdapter adapter, ScanCallbackCompat callbackCompat) { API21ScanCallback result = callbackMap.get(callbackCompat); if (result == null) { return; } adapter.getBluetoothLeScanner().flushPendingScanResults(result); }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (mBluetoothAdapter == null) { Log.w(TAG, "No default Bluetooth adapter. Device likely does not support bluetooth."); return; } // We use Text-to-Speech to indicate status change to the user initTts(); registerReceiver(mAdapterStateChangeReceiver, new IntentFilter( BluetoothAdapter.ACTION_STATE_CHANGED)); registerReceiver(mSinkProfileStateChangeReceiver, new IntentFilter( A2dpSinkHelper.ACTION_CONNECTION_STATE_CHANGED)); registerReceiver(mSinkProfilePlaybackChangeReceiver, new IntentFilter( A2dpSinkHelper.ACTION_PLAYING_STATE_CHANGED)); if (mBluetoothAdapter.isEnabled()) { Log.d(TAG, "Bluetooth Adapter is already enabled."); initA2DPSink(); } else { Log.d(TAG, "Bluetooth adapter not enabled. Enabling."); mBluetoothAdapter.enable(); } }
/** * Verify the level of Bluetooth support provided by the hardware. * @param bluetoothAdapter System {@link BluetoothAdapter}. * @return true if Bluetooth is properly supported, false otherwise. */ private boolean checkBluetoothSupport(BluetoothAdapter bluetoothAdapter) { if (bluetoothAdapter == null) { Log.w(TAG, "Bluetooth is not supported"); return false; } if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) { Log.w(TAG, "Bluetooth LE is not supported"); return false; } return true; }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); BluetoothAdapter.getDefaultAdapter(); FragmentHelper.switchFragment(getSupportFragmentManager(), new ConnectFragment(), R.id.view_id_content, false); }
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE); View view = inflater.inflate(R.layout.view_add_bluetooth_server, container); ListView listViewBtPairedPCs = (ListView) view.findViewById(R.id.listViewBtPairedPCs); ArrayList<BluetoothDevice> pairedBluetoothList = new ArrayList<>(); BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices(); if (pairedDevices.size() > 0) { for (BluetoothDevice device : pairedDevices) { if(device.getBluetoothClass().getMajorDeviceClass() == BluetoothClass.Device.Major.COMPUTER) { pairedBluetoothList.add(device); } } if (pairedBluetoothList.size() == 0) { Toast.makeText(getActivity().getApplicationContext(), R.string.bluetooth_no_paired_found, Toast.LENGTH_LONG).show(); return null; } } else { Toast.makeText(getActivity().getApplicationContext(), R.string.bluetooth_no_paired_found, Toast.LENGTH_LONG).show(); return null; } BluetoothPairedDevicesAdapter adapter = new BluetoothPairedDevicesAdapter(getActivity(), pairedBluetoothList, this); listViewBtPairedPCs.setAdapter(adapter); return view; }
/** * When try check that bluetooth is enable should check that method return correct data. * @throws Exception if something error happened. */ @Test public void whenTryCheckThatBluetoothIsEnabledShouldCheckThatMethodReturnCorrectData() throws Exception { Activity activity = mock(Activity.class); BluetoothDiscoveryDeviceListener listener = mock(BluetoothDiscoveryDeviceListener.class); BluetoothAdapter adapter = mock(BluetoothAdapter.class); mockStatic(BluetoothAdapter.class); when(BluetoothAdapter.getDefaultAdapter()).thenReturn(adapter); when(adapter.isEnabled()).thenReturn(true); BluetoothController controller = new BluetoothController(activity, adapter, listener); assertThat(controller.isBluetoothEnabled(), is(true)); }
/** * Returns a {@link BluetoothDevice} based on the provided MAC address. * * @param mac the MAC address of the BTLE device * @return the created BT device. */ public static BluetoothDevice getDevice(@NonNull String mac) { String upperMac = mac.toUpperCase(); if (isMacValid(upperMac)) { return BluetoothAdapter.getDefaultAdapter().getRemoteDevice(upperMac); } throw new UnsupportedOperationException("Device mac not recognized."); }
private boolean judgeHaveBluetooth() { mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); //判断设备是否支持蓝牙,不支持就没有后续操作了 if (mBluetoothAdapter == null) { Toast.makeText(this, "你的设备不支持蓝牙,无法连接和传输(。•́︿•̀。)", Toast.LENGTH_LONG).show(); return false; } return true; }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); setSupportActionBar(toolbar); // load our username username = getSharedPreferences(Constants.PREFS_NAME, 0).getString(Constants.PREFS_USERNAME, null); if (BridgefyListener.isThingsDevice(this)) { //if this device is running Android Things, don't go through any UI interaction and //start right away BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); //enabling bluetooth automatically bluetoothAdapter.enable(); username = Build.MANUFACTURER + " " + Build.MODEL; // initialize the Bridgefy framework Bridgefy.initialize(getBaseContext(), registrationListener); setupList(); } else { // check that we have permissions, otherwise fire the IntroActivity if ((ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) || (username == null)) { startActivity(new Intent(getBaseContext(), IntroActivity.class)); finish(); } else { // initialize the Bridgefy framework Bridgefy.initialize(getBaseContext(), registrationListener); setupList(); } } }
private boolean activateBluetooth() { // TODO app freezes after enabling bluetooth through app instead of directly enabling it if (!mBluetoothAdapter.isEnabled()) { Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, 1); return true; } return false; }
/** * 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; }
public void BluetoothScan() { mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); IntentFilter filter = new IntentFilter(); //发现设备 filter.addAction(BluetoothDevice.ACTION_FOUND); //设备连接状态改变 filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED); //蓝牙设备状态改变 filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED); filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); this.registerReceiver(mBluetoothReceiver, filter); mBluetoothAdapter.startDiscovery(); Log.d("XLight", "Bluetooth scan start"); }
public static int getTotalPairedMicroBitsFromSystem() { int totalPairedMicroBits = 0; BluetoothAdapter mBluetoothAdapter = ((BluetoothManager) MBApp.getApp().getSystemService(Context .BLUETOOTH_SERVICE)).getAdapter(); if(mBluetoothAdapter != null && !mBluetoothAdapter.isEnabled()) { Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices(); for(BluetoothDevice bt : pairedDevices) { if(bt.getName().contains("micro:bit")) { ++totalPairedMicroBits; } } } return totalPairedMicroBits; }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.layout_bluetoothlist); this.setFinishOnTouchOutside(false); ButterKnife.bind(this); mHandler = new Handler(); // indicate scanning in the title TextView status = (TextView) findViewById(R.id.bluetoothlist_status); status.setText(R.string.ble_startfind); // initialize bluetooth manager & adapter final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); mBluetoothAdapter = bluetoothManager.getAdapter(); bluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner(); // if bluetooth is not currently enabled, if (!mBluetoothAdapter.isEnabled()) { Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); } else { // initialize list view adapter deviceList = new ArrayList(); mLeDeviceListAdapter = new LeDeviceListAdapter(this, R.layout.item_bluetoothdevice); listView_BluetoothList.setAdapter(mLeDeviceListAdapter); listView_BluetoothList.setOnItemClickListener(new ListViewItemClickListener()); scanLeDevice(true); } }