1
votes

I'm trying to process an analog pressure sensor signal on Arduino Uno and sends an output string to my Android app UI via Bluetooth.

I've established a BT connection between the app and the HC-05 module and was able to get the inputStream on the UI by writing a string to my Arduino and in response receive a string back.

I'm trying to trigger a dialog alert once there's a signal received from the Arduino, button b1 is config as setOnclickListner to write to the Arduino and in response the Arduino sends the inputStream.

The problem is that the app reads the input stream once as soon as the activity is open but stops receiving afterwards, this is an issue for me since the design of my UI suppose to send a signal based on the realtime incoming data from the sensors, not when is it triggered by setOnClickListener.

I'm trying to find a way to write to the Arduino without clicking a button, then once the app is reading the inputstream I need it to keep listening for incoming data and call the dialog function everytime, any suggestions where I could start?

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


        }   
        }
1

1 Answers

1
votes

It is very clear why this is happening, because you coded it that way! you put the piece of code which does the Bluetooth io in an onclick listener, so it's only ran when that button is clicked;

if you want to condition the android app to execute a piece of code after a certain bluetooth signal is received, you need to be listening for that signal indefinitely( and to not to block the ui) in another thread (not just when a button is clicked) then call a handler if you wanna update the ui; so your code should look like this:

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