Android read data via BT from Arduino

i have a problem, i can send and receive data bud I want to print the incoming data on the label, for example, when X arrives, the label is 123, arduino sends X code, but android also cannot receive X only. X from arduino, how to deliver to android tag i have a problem,i can send and receive data bud I want to print the incoming data on the label, for example, when X arrives, the label is 123, arduino sends X code, but android also cannot receive X only. X from arduino, how to deliver to android tag i have a problem,i can send and receive data bud I want to print the incoming data on the label, for example, when X arrives, the label is 123, arduino sends X code, but android also cannot receive X only. X from arduino, how to deliver to android tag

public class MonitoringScreen extends AppCompatActivity {

private static final String TAG = "";
private int mMaxChars = 50000;//Default
private UUID mDeviceUUID;
private BluetoothSocket mBTSocket;
private ReadInput mReadThread = null;

private boolean mIsUserInitiatedDisconnect = false;

private TextView mTxtReceive;
private Button mBtnClearInput;
private ScrollView scrollView;
private CheckBox chkScroll;
private CheckBox chkReceiveText;
private Button sagup;
private Button sagdown;
private Button solup;
private Button soldown;
private Button modulekle;
private Button modulcikar;
private Button kalibrasyon;
private ImageButton hakkinda;

private TextView durum;

private boolean mIsBluetoothConnected = false;

private BluetoothDevice mDevice;

private ProgressDialog progressDialog;
int loopDelay = 50;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_monitoring_screen);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    ActivityHelper.initialize(this);

    Intent intent = getIntent();
    Bundle b = intent.getExtras();
    mDevice = b.getParcelable(MainActivity.DEVICE_EXTRA);
    mDeviceUUID = UUID.fromString(b.getString(MainActivity.DEVICE_UUID));
    mMaxChars = b.getInt(MainActivity.BUFFER_SIZE);
    Log.d(TAG, "Ready");
    mTxtReceive = (TextView) findViewById(R.id.txtReceive);
    chkScroll = (CheckBox) findViewById(R.id.chkScroll);
    chkReceiveText = (CheckBox) findViewById(R.id.chkReceiveText);
    scrollView = (ScrollView) findViewById(R.id.viewScroll);
    mBtnClearInput = (Button) findViewById(R.id.btnClearInput);
    sagup = findViewById(R.id.sagup);
    sagdown = findViewById(R.id.sagdown);
    solup = findViewById(R.id.solup);
    soldown = findViewById(R.id.soldown);
    modulekle = findViewById(R.id.modulekle);
    modulcikar = findViewById(R.id.modulcikar);
    kalibrasyon = findViewById(R.id.kalibrasyon);
    hakkinda = findViewById(R.id.useinfo);
    durum=findViewById(R.id.sistembilgisi);
    mTxtReceive.setMovementMethod(new ScrollingMovementMethod());


    sagup.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String msg = ("0");
            SendInput sendInput = new SendInput();
            sendInput.send(msg);
        }
    });

    sagdown.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String msg = ("1");
            SendInput sendInput = new SendInput();
            sendInput.send(msg);
        }
    });

    solup.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String msg = ("2");
            SendInput sendInput = new SendInput();
            sendInput.send(msg);
        }
    });

    soldown.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String msg = ("3");
            SendInput sendInput = new SendInput();
            sendInput.send(msg);
        }
    });

    modulekle.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String msg = ("4");
            SendInput sendInput = new SendInput();
            sendInput.send(msg);
        }
    });

    modulcikar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String msg = ("5");
            SendInput sendInput = new SendInput();
            sendInput.send(msg);
        }
    });

    kalibrasyon.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String msg = ("8");
            SendInput sendInput = new SendInput();
            sendInput.send(msg);
        }
    });

    hakkinda.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String msg = ("X");
            SendInput sendInput = new SendInput();
            sendInput.send(msg);
        }
    });


    mBtnClearInput.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            mTxtReceive.setText("");
        }
    });

  }

private class SendInput {
    InputStream inputStream;
    OutputStream outputStream;
    /* Call this from the main activity to send data to the remote device */
    public void send(String message) {
        if(outputStream==null){
            try {
                outputStream = mBTSocket.getOutputStream();
            } catch (IOException e) {
                Log.d("Hata !!!", "In onResume(), giriş ve çıkış akışı oluşturma başarısız oldu:" + e.getMessage() + ".");
            }
        }
        Log.d(TAG, "...Gönderilecek veriler: " + message + "...");

        byte[] msgBuffer = (message+ " ").getBytes();
        try {
            outputStream.write(msgBuffer);
            Log.e(TAG, "Int" + Arrays.toString(msgBuffer));
        } catch (IOException e) {
            Log.d(TAG, "...Hata verisi gönderme: " + e.getMessage() + "...");
        }
    }
}
private class ReadInput implements Runnable {

    private boolean bStop = false;
    private Thread t;

    public ReadInput() {
        t = new Thread(this, "Gelen veri");
        t.start();
    }

    public boolean isRunning() {
        return t.isAlive();
    }

    @Override
    public void run() {

        InputStream inputStream;

        try {
            inputStream = mBTSocket.getInputStream();
            while (!bStop) {
                byte[] buffer = new byte[256];
                if (inputStream.available() > 0) {
                    inputStream.read(buffer);
                    int i = 0;
                    /*
                     * This is needed because new String(buffer) is taking the entire buffer i.e. 256 chars on Android 2.3.4 http://stackoverflow.com/a/8843462/1287554
                     */
                    for (i = 0; i < buffer.length && buffer[i] != 0; i++) {
                    }
                    final String strInput = new String(buffer, 0, i);

                    /*
                     * If checked then receive text, better design would probably be to stop thread if unchecked and free resources, but this is a quick fix
                     */

                    if (chkReceiveText.isChecked()) {
                        mTxtReceive.post(new Runnable() {
                            @Override
                            public void run() {
                                mTxtReceive.append(strInput);

                                int txtLength = mTxtReceive.getEditableText().length();
                                if(txtLength > mMaxChars){
                                    mTxtReceive.getEditableText().delete(0, txtLength - mMaxChars);

                                }

                                if (chkScroll.isChecked()) { // Scroll only if this is checked
                                    scrollView.post(new Runnable() { // Snippet from http://stackoverflow.com/a/4612082/1287554
                                        @Override
                                        public void run() {
                                            scrollView.fullScroll(View.FOCUS_DOWN);
                                        }
                                    });
                                }
                            }
                        });
                    }
                }
                Thread.sleep(loopDelay);
            }
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }

    }

    public void stop() {
        bStop = true;
    }

}

private class DisConnectBT extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
    }

    @Override
    protected Void doInBackground(Void... params) {

        if (mReadThread != null) {
            mReadThread.stop();
            while (mReadThread.isRunning()); // Wait until it stops
            mReadThread = null;
        }

        try {
            mBTSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        mIsBluetoothConnected = false;
        if (mIsUserInitiatedDisconnect) {
            finish();
        }
    }

}

private void msg(String s) {
    Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
}

@Override
protected void onPause() {
    if (mBTSocket != null && mIsBluetoothConnected) {
        new DisConnectBT().execute();
    }
    Log.d(TAG, "Paused");
    super.onPause();
}

@Override
protected void onResume() {
    if (mBTSocket == null || !mIsBluetoothConnected) {
        new ConnectBT().execute();
    }
    Log.d(TAG, "Resumed");
    super.onResume();
}

@Override
protected void onStop() {
    Log.d(TAG, "Stopped");
    super.onStop();
}

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
}

private class ConnectBT extends AsyncTask<Void, Void, Void> {
    private boolean mConnectSuccessful = true;

    @Override
    protected void onPreExecute() {
        progressDialog = ProgressDialog.show(MonitoringScreen.this, "Bekleyiniz", "Bağlantı kuruluyor...");// http://stackoverflow.com/a/11130220/1287554
    }

    @Override
    protected Void doInBackground(Void... devices) {

        try {
            if (mBTSocket == null || !mIsBluetoothConnected) {
                mBTSocket = mDevice.createInsecureRfcommSocketToServiceRecord(mDeviceUUID);
                BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
                mBTSocket.connect();
            }
        } catch (IOException e) {
            e.printStackTrace();
            mConnectSuccessful = false;
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);

        if (!mConnectSuccessful) {
            Toast.makeText(getApplicationContext(), "Cihaza bağlanılamadı. BT cihazınızı kontrol edin.", Toast.LENGTH_LONG).show();
            // durum.setText("Cihaza bağlanılamadı !");
            // durum.setTextColor(Color.parseColor("#820000"));
            finish();
        } else {
            msg("Cihaza bağlandı");
            mIsBluetoothConnected = true;
            mReadThread = new ReadInput(); // Kick off input reader
            // durum.setText("Bağlantı kuruldu")
            // durum.setTextColor(Color.parseColor("#0c7d00"));
        }
        progressDialog.dismiss();
    }
}

private class ComunicaThread extends Thread{
    private  InputStream minputStream;
    private  OutputStream moutputStream;


    private ComunicaThread(BluetoothSocket socket) {
        InputStream tmpIn= null;
        OutputStream tmpOut= null;

        try {

            tmpIn= socket.getInputStream();
            tmpOut= socket.getOutputStream();
        }
        catch (IOException e)
        {
            Log.d("eSocket","Error: " +e.toString());
        }
        this.minputStream= tmpIn;
        this.moutputStream= tmpOut;
    }

    public void run(){

        byte[] buffer= new byte[1];
        while (true){
            Log.d("Run","Port serisinin girişini okuyan yöntem"  );
            try {
                minputStream.read(buffer);
                char ch=(char)buffer[0];
                Log.d("Run","Port serisinin girişini okuyan yöntem:" +ch );

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

    } }

public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        exitByBackKey();

        //moveTaskToBack(false);

        return true;
    }
    return super.onKeyDown(keyCode, event);
}

protected void exitByBackKey() {

    AlertDialog alertbox = new AlertDialog.Builder(this)
            .setMessage("Uygulamadan çıkılsınmı ?")
            .setPositiveButton("Evet", new DialogInterface.OnClickListener() {

                // do something when the button is clicked
                public void onClick(DialogInterface arg0, int arg1) {

                    finish();

                }
            })
            .setNegativeButton("Hayır", new DialogInterface.OnClickListener() {

                // do something when the button is clicked
                public void onClick(DialogInterface arg0, int arg1) {
                }
            })
            .show();

}

}

Leave a Comment