繁体   English   中英

Android - Arduino 蓝牙通信:应用程序停止读取输入流

[英]Android - Arduino Bluetooth communication: app stops reading inputstream

我正在尝试在 Arduino Uno 上处理模拟压力传感器信号,并通过蓝牙将输出字符串发送到我的 Android 应用程序 UI。

我已经在应用程序和 HC-05 模块之间建立了 BT 连接,并且能够通过向我的 Arduino 写入一个字符串来获取 UI 上的 inputStream 并作为响应接收一个字符串。

一旦收到来自 Arduino 的信号,我就会尝试触发对话框警报,按钮 b1 被配置为 setOnclickListner 以写入 Arduino,作为响应,Arduino 发送 inputStream。

问题是应用程序在活动打开后立即读取输入流一次,但之后停止接收,这对我来说是一个问题,因为我的 UI 设计假设基于来自传感器的实时传入数据发送信号,不是什么时候由 setOnClickListener 触发的。

我正在尝试找到一种无需单击按钮即可写入 Arduino 的方法,然后一旦应用程序正在读取输入流,我就需要它继续侦听传入数据并每次都调用对话框函数,有什么建议可以开始吗?

public class Bluetooth_Activity extends AppCompatActivity   {

    //widgets
    Button b1;  Button b2; Button b3;
    TextView t1; TextView t2;

//    Bluetooth:
    String address = null, name = null;
    BluetoothAdapter myBluetooth = null;
    BluetoothServerSocket serverSocket;
    BluetoothSocket btSocket = null;
    Set<BluetoothDevice> pairedDevices;
    static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    Handler bluetoothIn;
    BluetoothDevice dispositivo;
    private StringBuilder recDataString = new StringBuilder();
    InputStream tmpIn = null;
    OutputStream tmpOut = null;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bluetooth_);
        b1 = (Button) findViewById(R.id.button1);
        b3 = (Button) findViewById(R.id.str_dialog);

        try {
            bluetooth_connect_device();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

private void alertSystem () throws IOException {
    AlertDialog.Builder mBuilder = new AlertDialog.Builder(Bluetooth_Activity.this);
    View mView = getLayoutInflater().inflate(R.layout.alert_dialog, null);
    Button mClose = (Button) mView.findViewById(R.id.btn_close);

    mBuilder.setView(mView);
    final AlertDialog dialog = mBuilder.create();
    dialog.show();

    mClose.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            dialog.dismiss();
        }
    });
}


//  BLUETOOTH FUNCTIONS:
    private class someThread extends Thread{
        public void run() {
            abc();
        }
    }


    private void bluetooth_connect_device() throws IOException {

        try {
            myBluetooth = BluetoothAdapter.getDefaultAdapter();
            address = myBluetooth.getAddress();
            pairedDevices = myBluetooth.getBondedDevices();
            if (pairedDevices.size() > 0) {
                for (BluetoothDevice bt : pairedDevices) {
                    address = bt.getAddress().toString();
                    name = bt.getName().toString();
                    Toast.makeText(getApplicationContext(), "Connected", Toast.LENGTH_SHORT).show();
                }
            }

        } catch (Exception we) {
        }
        myBluetooth = BluetoothAdapter.getDefaultAdapter();//get the mobile bluetooth device
        BluetoothDevice dispositivo = myBluetooth.getRemoteDevice(address);//connects to the device's address and checks if it's available
        btSocket = dispositivo.createInsecureRfcommSocketToServiceRecord(myUUID);//create a RFCOMM (SPP) connection
        btSocket.connect();

        try
        {
            Toast.makeText(getApplicationContext(), ("BT Name: " + name + "\nBT Address: " + address), Toast.LENGTH_SHORT).show();
        } catch (Exception e) {}

    }

    public void abc() {

            try {

                byte[] buffer = new byte[256];  // buffer store for the stream
                int bytes; // bytes returned from read()

                tmpIn = btSocket.getInputStream();
                DataInputStream mmInStream = new DataInputStream(tmpIn);
                bytes = mmInStream.read(buffer);
                String readMessage = new String(buffer, 0, bytes);
                Toast.makeText(getApplicationContext(),
                        "OutPut Recived From Bluetooth : \n" + readMessage,
                        Toast.LENGTH_SHORT).show();
                alertSystem();
            } catch (Exception e) {
            }
       }

      @Override
      public void onClick(View v) {
        if (v.getId() == R.id.button1)
        {
            try
            {
                String i="f";         //here i'm sending a single char f and when arduino recived it it will
                // send a response 
                btSocket.getOutputStream().write(i.getBytes());
                Thread.sleep(1500);
                abc();
            } catch (Exception e) {}


        }   
        }

很明显为什么会发生这种情况,因为您是这样编码的! 您将执行蓝牙 io 的代码放在 onclick 侦听器中,因此它仅在单击该按钮时运行;

如果您想在接收到某个蓝牙信号后让 android 应用程序执行一段代码,您需要在另一个线程中无限期地监听该信号(并且不要阻止用户界面)(不仅仅是当一个按钮被单击)然后调用处理程序,如果你想更新用户界面; 所以你的代码应该是这样的:

new Thread(new Runnable() {
        @Override
        public void run() {
            while (true){//an infinite loop
                //read signals
                //process them
                //call some handler to deal with the ui
            }
        }
    })

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM