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

问题描述 投票:1回答:1

我正在尝试在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) {}


        }   
        }
java android inputstream android-bluetooth
1个回答
1
投票

很清楚为什么会发生这种情况,因为你这样编码了!你把蓝牙io的代码片段放在一个onclick监听器中,所以它只在单击该按钮时运行;

如果你想在接收到某个蓝牙信号后调节android app来执行一段代码,你需要在另一个thread中无限期地(并且不阻止ui)监听该信号(不仅仅是当一个按钮是点击)然后如果你想更新ui,请调用handler;所以你的代码应该是这样的:

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
            }
        }
    })
© www.soinside.com 2019 - 2024. All rights reserved.