为了账号安全,请及时绑定邮箱和手机立即绑定

Android示例蓝牙代码可通过蓝牙发送简单的字符串

Android示例蓝牙代码可通过蓝牙发送简单的字符串

暮色呼如 2019-09-21 11:23:47
我想通过蓝牙将一个简单的字符串数据(例如“ a”)从android设备发送到其他设备。我在android sdk中查看了示例蓝牙代码,但这对我来说太复杂了。按下按钮时,我无法理解如何仅发送特定数据。我怎么解决这个问题?
查看完整描述

2 回答

?
牧羊人nacy

TA贡献1862条经验 获得超7个赞

private OutputStream outputStream;

private InputStream inStream;


private void init() throws IOException {

    BluetoothAdapter blueAdapter = BluetoothAdapter.getDefaultAdapter();

    if (blueAdapter != null) {

        if (blueAdapter.isEnabled()) {

            Set<BluetoothDevice> bondedDevices = blueAdapter.getBondedDevices();


            if(bondedDevices.size() > 0) {

                Object[] devices = (Object []) bondedDevices.toArray();

                BluetoothDevice device = (BluetoothDevice) devices[position];

                ParcelUuid[] uuids = device.getUuids();

                BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuids[0].getUuid());

                socket.connect();

                outputStream = socket.getOutputStream();

                inStream = socket.getInputStream();

            }


            Log.e("error", "No appropriate paired devices.");

        } else {

            Log.e("error", "Bluetooth is disabled.");

        }

    }

}


public void write(String s) throws IOException {

    outputStream.write(s.getBytes());

}


public void run() {

    final int BUFFER_SIZE = 1024;

    byte[] buffer = new byte[BUFFER_SIZE];

    int bytes = 0;

    int b = BUFFER_SIZE;


    while (true) {

        try {

            bytes = inStream.read(buffer, bytes, BUFFER_SIZE - bytes);

        } catch (IOException e) {

            e.printStackTrace();

        }

    }

}


查看完整回答
反对 回复 2019-09-21
  • 2 回答
  • 0 关注
  • 1010 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信