Android 传统蓝牙(1)

xiaoxiao2021-02-28  121

1, /** 打开蓝牙 */ private void open() { mBluetoothAdapter.enable(); } 2,/** 开始扫描蓝牙设备 */ private void startScan() { mBluetoothAdapter.startDiscovery(); } 3, @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // 获取被点击的设备 BluetoothDevice device = (BluetoothDevice) parent.getItemAtPosition(position); // 连接设备 startConnect(device); } }/** 连接到被点击的设备 */ private void startConnect(final BluetoothDevice device) { new Thread(){ public void run() { // BluetoothSocket tmp = null; Method method; try { method = device.getClass().getMethod("createRfcommSocket", new Class[]{int.class}); socket = (BluetoothSocket) method.invoke(device, 1); outputStream = socket.getOutputStream(); } catch (Exception e) { // setState(CONNECT_FAILED); Log.e("TAG", e.toString()); } // socket = tmp; try { socket.connect(); // isConnect = true; } catch (Exception e) { // setState(CONNECT_FAILED); Log.e("TAG", e.toString()); } }

注册广播接受者,接收搜索道德蓝@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // 初始化view ListView listView = (ListView) findViewById(R.id.listView); bluetoothDevices = new ArrayList(); adapter = new BluetoothDeviceListAdapter(bluetoothDevices); listView.setAdapter(adapter); listView.setOnItemClickListener(new OnBluetoothDeviceItemClickListener());

// 初始化蓝牙 mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

// 关注新的蓝牙设备信息 IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED); filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); mBluetoothReceiver = new BluetoothReceiver(); registerReceiver(mBluetoothReceiver, filter); // Don’t forget to unregister during onDestroy

} private final class BluetoothReceiver extends BroadcastReceiver { @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); // Add the name and address to an array adapter to show in a ListView bluetoothDevices.add(device); adapter.notifyDataSetChanged(); }else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) { // 开始扫描设备 toast("开始扫描设备"); bluetoothDevices.clear(); adapter.notifyDataSetChanged(); }else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) { // 停止扫描设备 toast("停止扫描设备"); } } }

“`

转载请注明原文地址: https://www.6miu.com/read-29343.html

最新回复(0)