android 蓝牙

xiaoxiao2021-02-28  82

1、添加权限<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />     <uses-permission android:name="android.permission.BLUETOOTH" /> 2、得到蓝牙适配器BluetoothAdapter    mBtAdapter = BluetoothAdapter.getDefaultAdapter(); 3、搜索设备 mBtAdapter.startDiscovery(); 4、在广播中得到蓝牙设备BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); 5、获取蓝牙的名称和地址device.getName() + "\n" + device.getAddress() 连接设备 :BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address); 开子线程连接设备BluetoothSocket tmp = device.createRfcommSocketToServiceRecord( MY_UUID_SECURE); 连接成功后InputStream tmpIn = socket.getInputStream();  OutputStream tmpOut =socket.getOutputStream(); 就可以进行通信了 6、关闭蓝牙mBtAdapter.disable() demo下载:http://download.csdn.net/detail/u013866845/9834581

private final BroadcastReceiver mReceiver = new 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);                 // 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);                 }             }         }     };

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

最新回复(0)