@Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); Log.d(TAG, "广播接收者运行..." + action); // 查找到设备action if (BluetoothDevice.ACTION_FOUND.equals(action)) { // 得到蓝牙设备 BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); // 如果是已配对的则略过,已得到显示,其余的在添加到列表中进行显示 Log.d(TAG, device.toString()); if (device.getBondState() != BluetoothDevice.BOND_BONDED) { mNewDevicesAdapter.add(device); tv_new_devices.setVisibility(View.VISIBLE); // newDevices.add(device); } } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) { setProgressBarIndeterminateVisibility(false); swiperefresh.setRefreshing(false); // btn_sann.setVisibility(View.VISIBLE); if (mNewDevicesAdapter.getCount() == 0) { setTitle("没有找到新设备"); Toast.makeText(DeviceListActivity.this, "没有发现新设备!", Toast.LENGTH_SHORT).show(); } else { setTitle(getString(R.string.chose_to_connect)); tv_new_devices.setVisibility(View.VISIBLE); } } }
private void initData() { // 初使化设备存储数组 mPairedDevicesAdapter = new DeviceListAdapter(DeviceListActivity.this, pairedDevices); mNewDevicesAdapter = new DeviceListAdapter(DeviceListActivity.this, newDevices); // 设置已配队设备列表 lv_paired_devices.setAdapter(mPairedDevicesAdapter); lv_paired_devices.setOnItemClickListener(mDeviceClickListener); // 设置新查找设备列表 lv_new_devices.setAdapter(mNewDevicesAdapter); lv_new_devices.setOnItemClickListener(mDeviceClickListener); // 注册接收查找到设备action接收器 IntentFilter filter = new IntentFilter(); filter.addAction(BluetoothDevice.ACTION_FOUND); filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); this.registerReceiver(mReceiver, filter); // 得到本地蓝牙句柄 mBtAdapter = BluetoothAdapter.getDefaultAdapter(); // 得到已配对蓝牙设备列表 Set<BluetoothDevice> bondedDevices = mBtAdapter.getBondedDevices(); // 添加已配对设备到列表并显示 if (bondedDevices.size() > 0) { tv_paired_devices.setVisibility(View.VISIBLE); for (BluetoothDevice device : bondedDevices) { mPairedDevicesAdapter.add(device); } } }