java - arduino 发送数据失败

标签 java android bluetooth

我已成功将 android 应用程序连接到 arduino,但似乎我无法获取数据,即使我使用了输入流......我不知道这几天一直在寻找和尝试其他解决方案有什么问题。 .

安卓工作室代码:

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    bluetooth = new BluetoothSPP(this);
    text = (TextView) findViewById(R.id.textView2);
    connect = (Button) findViewById(R.id.connect);
    on = (Button) findViewById(R.id.on);
    BluetoothSocket socket = null;
    mAdapter = BluetoothAdapter.getDefaultAdapter();

    if (!bluetooth.isBluetoothAvailable()) {
        Toast.makeText(getApplicationContext(), "Bluetooth is not available", Toast.LENGTH_SHORT).show();
        finish();
    }

    bluetooth.setBluetoothConnectionListener(new BluetoothSPP.BluetoothConnectionListener() {
        public void onDeviceConnected(String name, String address) {
            connect.setText("Connected to " + name);
        }

        public void onDeviceDisconnected() {
            connect.setText("Connection lost");
        }

        public void onDeviceConnectionFailed() {
            connect.setText("Unable to connect");
        }
    });

    connect.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (bluetooth.getServiceState() == BluetoothState.STATE_CONNECTED) {
                bluetooth.disconnect();
            } else {
                Intent intent = new Intent(getApplicationContext(), DeviceList.class);
                startActivityForResult(intent, BluetoothState.REQUEST_CONNECT_DEVICE);
            }


        }
    });


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


        }


    });

    /*off.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            bluetooth.send(OFF, true);
        }
    });*/




}






 public void onStart() {
    super.onStart();
    if (!bluetooth.isBluetoothEnabled()) {
        bluetooth.enable();
    } else {
        if (!bluetooth.isServiceAvailable()) {
            bluetooth.setupService();
            bluetooth.startService(BluetoothState.DEVICE_OTHER);
        }
    }
}

< /* class ConnectedThread extends Thread {
        private InputStream mInStream;

public ConnectedThread(BluetoothSocket socket) throws IOException { InputStream tmpIn = null; // Get the input and output streams, using temp objects because // member streams are final try { tmpIn = socket.getInputStream(); } catch (IOException e) { } mInStream = tmpIn; } } public void run() { BufferedReader r = new BufferedReader(new InputStreamReader(mInStream)); while (true) { try { int a = r.read(); Log.d(TAG, Integer.toString(a)); } catch (IOException e) { break; } } } }*/ void beginListenForData() { final Handler handler = new Handler(); final byte delimiter = 10; //This is the ASCII code for a newline character stopWorker = false; readBufferPosition = 0; readBuffer = new byte[1024]; workerThread = new Thread(new Runnable() { public void run() { while (!Thread.currentThread().isInterrupted() && !stopWorker) { try { int bytesAvailable = mmInputStream.available(); if (bytesAvailable > 0) { byte[] packetBytes = new byte[bytesAvailable]; mmInputStream.read(packetBytes); for (int i = 0; i < bytesAvailable; i++) { byte b = packetBytes[i]; if (b == delimiter) { byte[] encodedBytes = new byte[readBufferPosition]; System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length); final String data = new String(encodedBytes, "US-ASCII"); readBufferPosition = 0; handler.post(new Runnable() { public void run() { text.setText(data); } }); } else { readBuffer[readBufferPosition++] = b; } } } } catch (IOException ex) { stopWorker = true; } } } }); workerThread.start(); } void closeBT() throws IOException { stopWorker = true; mmOutputStream.close(); mmInputStream.close(); text.setText("Bluetooth Closed"); } public void onDestroy() { super.onDestroy(); bluetooth.stopService(); } public void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == BluetoothState.REQUEST_CONNECT_DEVICE) { if (resultCode == Activity.RESULT_OK) bluetooth.connect(data); } else if (requestCode == BluetoothState.REQUEST_ENABLE_BT) { if (resultCode == Activity.RESULT_OK) { bluetooth.setupService(); } else { Toast.makeText(getApplicationContext() , "Bluetooth was not enabled." , Toast.LENGTH_SHORT).show(); finish(); } } }

Arduino 代码:

enter image description here

最佳答案

您不需要 InputStream 和 OutputStream,因为您没有使用 native android RFCOMM 蓝牙 api。我用谷歌搜索了 BluetoothSPP 类,发现你正在使用这个 github 库进行蓝牙 spp 通信:akexorcist/Android-BluetoothSPPLibrary

您的代码似乎适用于连接/断开您的 arduino 设备。所以,我认为你适本地整合了图书馆。缺少的是发送/接收蓝牙数据的代码。我更新了你的代码如下:

on.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
    bluetooth.send("ON", true);
}
});

off.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        bluetooth.send("OFF", true);
    }
});

bluetooth.setOnDataReceivedListener(new OnDataReceivedListener() {
    public void onDataReceived(byte[] data, String message) {
         Toast.makeText(getApplicationContext(), String.format("Data Received: %s", message), Toast.LENGTH_SHORT).show();
    }
});

关于java - arduino 发送数据失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55668562/

相关文章:

android - 视频突然停止从 Youtube API 播放

android - SQLIte 查询,选择等于的所有内容 - Android

android - 未调用蓝牙 GATT 断开 onConnectionStateChange

java - 用另一个 while 循环 Java 扩展我的程序

java - Spring - 具体类中的@scheduled方法未运行

java - 使用 Angular 2+ 启动 Spring maven 项目

android - 尽管尝试了教程,但蓝牙设备未连接到 Android 应用程序

java - 在 Matlab 中从 Java GUI 调用 2 个类

android - Android Instant Apps:YouTube Android Player不兼容吗?

iphone - 如何通过蓝牙获取iPhone的手机号码?