【问题标题】:Android - Arduino Bluetooth communication: app stops reading inputstreamAndroid - Arduino 蓝牙通信:应用程序停止读取输入流
【发布时间】:2019-02-19 16:59:51
【问题描述】:

我正在尝试处理 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】:

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

    如果您想在接收到某个蓝牙信号后让 android 应用程序执行一段代码,您需要在另一个 thread(不是只是当一个按钮被点击)然后调用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
                }
            }
        })
    

    【讨论】:

      猜你喜欢
      • 2012-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-18
      • 2016-03-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多