蓝牙数据传输

时间:2018-07-26 12:30:27

标签: java android bluetooth

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

我这样称呼片段:

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

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

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

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

这是我的DataSend服务代码:

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

}

2 个答案:

答案 0 :(得分:1)

我将使用您连接的设备初始化BluetoothConnection,然后以这种方式发送数据。看起来像这样:

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 :(得分:0)

您是否致电startService(sendData);以启动蓝牙发送服务?看来您只是在创建意图并用数据填充它,而没有启动它。