android 蓝牙

来源:互联网 发布:众筹平台源码 编辑:程序博客网 时间:2024/06/03 11:27

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);
                }
            }
        }
    };





0 0
原创粉丝点击