android蓝牙和串口模块的通信

android蓝牙和串口模块的通信
最近一段时间研究了下android端和蓝牙串口模块间的通信,废话不多说,直接屡一屡思路和撸代码

  • 手机端蓝牙的搜索
  • 和串口模块间的配对
  • 最后就是数据的传输了

蓝牙的搜索

1、通过广播方式接收蓝牙的搜索结果,注册相应的广播

IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
this.registerReceiver(mReceiver, filter);

2、写一个广播接收器,获取周围的蓝牙设备,正常情况发现蓝牙时需判断该蓝牙模块是否已经配对,若已配对,则忽略。(但由于公司应用的要求,所以在这我省略了,只是多加这句话而已 device.getBondState() != BluetoothDevice.BOND_BONDED)

private final BroadcastReceiver mReceiver = new BroadcastReceiver(){
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                falgs=0;
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if(newDevicesAdapter.getPosition(device.getName() + 
                        "\n" + device.getAddress())==-1){
                    newDevicesAdapter.add(device.getName() + "\n" + 
                                                            device.getAddress());
                    newDevicesAdapter.notifyDataSetChanged();
                }

            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                setProgressBarIndeterminateVisibility(false);
                setTitle(R.string.select_paire);
                if (newDevicesAdapter.getCount() == 0) {
                    falgs=1;
                    newDevicesAdapter.add(getResources()
                            .getText(R.string.no_paire).toString());
                }
            }
        }

    };

注意:蓝牙搜索和配对前先判断手机是否支持蓝牙并且打开

private final BluetoothAdapter mblueAdapter=BluetoothAdapter.getDefaultAdapter();
if(mblueAdapter==null){ //表示手机不支持蓝牙设备 }
if(!mblueAdapter.isEnabled()){
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, ScanActivity.REQUEST_ENABLE_BT); //请求完成后在onActivityResult作出相应的操作
        }

3、开始蓝牙的搜索,先判断是否处于搜索状态

if(bluetoothAdapter.isDiscovering()){
    bluetoothAdapter.cancelDiscovery();
        }
bluetoothAdapter.startDiscovery();

4、蓝牙搜索完成后,就是蓝牙的连接

//先绑定蓝牙 BluetoothDevice dev=mblueAdapter.getRemoteDevice(address);
public boolean startService(BluetoothDevice device){

        if (connectThread != null && connectThread.isAlive()) {
            return true;
        }
        //获取蓝牙实例   判断机器是否支持蓝牙功能
        final BluetoothAdapter mBluetoothAdapter = BluetoothAdapter
                .getDefaultAdapter();
        if (mBluetoothAdapter == null) {
            MainActivity.getShowToast("This device does not support bluetooth").show();
            stopSelf();
            return false;
        }

        //判断蓝牙是否开启
        if (!mBluetoothAdapter.isEnabled()) {
            mHandler.obtainMessage(10).sendToTarget();
            stopSelf();
            return false;
        }
        //下面则是连接蓝牙并且实现数据的传输
        connectThread=new BluetoothConnThread(mHandler,device);
        new ObdReaderServiceWorkerThread(connectThread).start();
        return true;
    }

5、下面是connectThread线程里面的部分代码

UUID MY_UUID = UUID
    .fromString("00001101-0000-1000-8000-00805F9B34FB");

@Override
    public void run() {
        //连接的时候停止搜索,防止资源消耗
        BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
        try {
            socket = mDevice
                    .createInsecureRfcommSocketToServiceRecord(MY_UUID);
        //用socket打开输入输出流            
            socket.connect();
            in=socket.getInputStream();
            out=socket.getOutputStream();
        } catch (Exception ex) {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            //发送连接失败消息
            serviceHandler.obtainMessage(BluetoothTools.MESSAGE_CONNECT_ERROR)
            .sendToTarget();
            return;
        }
        //发送连接成功消息,
        serviceHandler.obtainMessage(BluetoothTools.MESSAGE_CONNECT_SUCCESS).sendToTarget();
        mInput=new InputThread(in, serviceHandler);
        runReadData(mInput);
        while(mInput.isAlive()){
            try {
                sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

上面所写都是项目中的部分代码,时间关系来不及整理,可能会有点错乱,大家多多包涵,这是鄙人第一次写博客,有错的,和不够详细的大家可以多多拍砖………………..一起学习。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值