Android示例蓝牙代码通过蓝牙发送一个简单的字符串 [英] Android sample bluetooth code to send a simple string via bluetooth

查看:20
本文介绍了Android示例蓝牙代码通过蓝牙发送一个简单的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过蓝牙将一个简单的字符串数据(例如a")从一个安卓设备发送到另一个.我在 android sdk 中查看了示例蓝牙代码,但它对我来说太复杂了.我无法理解按下按钮时如何仅发送特定数据.我怎么解决这个问题?

I want to send a simple string data such as 'a' from an android device to other one via bluetooth. I looked sample bluetooth code in android sdk but it is so complex for me. I cannot understand how I can send only specific data when I press a button. How can I solve this problem?

推荐答案

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

这篇关于Android示例蓝牙代码通过蓝牙发送一个简单的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆