首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >蓝牙数据传输

蓝牙数据传输
EN

Stack Overflow用户
提问于 2018-07-26 20:30:27
回答 2查看 70关注 0票数 1

我正在使用这些代码尝试使用Bluetooth意图服务发送数据,但我无法将消息发送到设备。我正在调试这段代码,但是DataSend类元素似乎为空。我如何解决这个问题,或者我如何使用意图服务正确地编写发送消息代码?

我这样调用这个片段:

最终意图sendData =新意图(getActivity(),DataSend.class);

代码语言:javascript
复制
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            String s = editText.getText().toString();

             sendData.putExtra("test",s);
        }
    });

这是我的DataSend服务代码:

代码语言:javascript
复制
public class DataSend extends IntentService{

    private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    private static final String TAG = "DataTransmissionService";

    private BluetoothAdapter btAdapter = null;
    private BluetoothSocket btSocket = null;
    private OutputStream outStream = null;
    private BluetoothDevice device = null;
    private Log log;

    public DataSend() {
        super("DataSend");
    }


    @Override
    protected void onHandleIntent(Intent intent) {
        cleanup();
        if (intent != null){

            btAdapter = BluetoothAdapter.getDefaultAdapter();
            String pairedDeviceAddress = "38:1B:4B:98:E7:ED";

            try {
                log.d(TAG, pairedDeviceAddress);
                device = btAdapter.getRemoteDevice(pairedDeviceAddress);
                log.d(TAG, "Device bond state : " + device.getBondState());

            } catch (Exception e) {
                log.e(TAG, "Invalid address: " + e.getMessage());
                return;
            }

            try {
                btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
            } catch (IOException e) {
                log.e(TAG, "Socket creation failed: " + e.getMessage());
                return;
            }

            try {

                if (!btSocket.isConnected()) {
                    btSocket.connect();
                    log.d(TAG, "Connected");
                } else {
                    log.d(TAG, "Already Connected");  //flow never reaches here for any use case
                }

            } catch (IOException e) {
                log.e(TAG, "btSocket.connect() failed : " + e.getMessage());
                return;
            }

            try {
                outStream = btSocket.getOutputStream();
            } catch (IOException e) {
                log.e(TAG, "Failed to get output stream:" + e.getMessage());
                return;
            }

            sendData("test");
            //cleanup();   called in onDestroy()

        }

    }

    private void cleanup(){

        try {
            if (outStream != null) {
                outStream.close();
                outStream = null;
            }
        } catch (Exception e) {
            log.e(TAG, "Failed to close output stream : " + e.getMessage());
        }

        try {
            if (btSocket != null) {
                btSocket.close();
                btSocket = null;
            }
        }catch (Exception e) {
            log.e(TAG, "Failed to close connection : " + e.getMessage());
        }

    }
    private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
        if(Build.VERSION.SDK_INT >= 10){
            try {
                final Method m = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", new Class[] { UUID.class });
                return (BluetoothSocket) m.invoke(device, MY_UUID);
            } catch (Exception e) {
                log.e(TAG, "Could not create Insecure RFComm Connection",e);
            }
        }

        return  device.createRfcommSocketToServiceRecord(MY_UUID);
    }

    private void sendData(String message) {

        byte[] msgBuffer = message.getBytes();
        log.d(TAG, "Sending : " + message);
        try {
            outStream.write(msgBuffer);
        } catch (IOException e) {
            log.e(TAG, "failed to write " + message);
        }
    }

}
EN

回答 2

Stack Overflow用户

发布于 2018-07-26 21:17:24

我会用你连接的设备初始化一个BluetoothConnection,然后用这种方式发送数据。它看起来有点像这样:

代码语言:javascript
复制
BluetoothConnection connection = new BluetoothConnection(connectedDevice);

public void sendData(){

    String s = editText.getText().toString();

    byte[] b = s.getBytes();

    connection.write(b);

    //System.out.println("Bytes Sent");
}// end sendData
票数 1
EN

Stack Overflow用户

发布于 2018-07-26 21:01:37

您是否调用startService(sendData);来启动蓝牙发送服务?看起来你只是在创建意图,并用数据填充它,而不是启动它。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51538912

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档