0

I have written the following code in android studio so as to connect using the Connect button to a HC-06 Bluetooth module after entering its MAC address as shown in the code. I want to be able to connect to my Bluetooth module and return on my screen Bluetooth connected as well as disconnected on pressing disconnect. Unfortunately, none of these buttons are performing the required action. Please help me out with my following code and also controller button codes. Thank you!

Here is the manifest:

<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

I have pressed numerous times on connect without any feedback.

    import android.bluetooth.BluetoothAdapter;
    import android.bluetooth.BluetoothDevice;
    import android.bluetooth.BluetoothSocket;
    import android.content.Intent;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.content.Intent;
    import android.text.TextUtils;
    import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.IOException;
import android.widget.Toast;

import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;

import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;




public class RemoteControl extends AppCompatActivity implements View.OnClickListener {
    private FirebaseAuth firebaseAuth;
    private TextView emailDisplay;
    private Button logout;
    private final String Bluetooth_Address = "98:D3:51:F9:33:AC";
    private final UUID PORT_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");

    private BluetoothDevice device;
    private BluetoothSocket socket;
    private OutputStream outputStream;
    private InputStream inputStream;
    private Button Forward_btn, Right_btn, Left_btn, Reverse_btn, Stop_btn, Bluetooth_connect,Bluetooth_disconnect;
    String command;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_remote_control);

        firebaseAuth = FirebaseAuth.getInstance();
        if (firebaseAuth.getCurrentUser() == null) {
            finish();
            startActivity(new Intent(this, MainActivity.class));
        }
        FirebaseUser user = firebaseAuth.getCurrentUser();

        emailDisplay = (TextView) (findViewById(R.id.textView));
        emailDisplay.setText("Welcome " + user.getEmail());
        logout = (Button) findViewById(R.id.logout);
        logout.setOnClickListener(this);
        //declaring button variables
        Forward_btn = (Button) findViewById(R.id.Forward);
        Right_btn = (Button) findViewById(R.id.Right);
        Left_btn = (Button) findViewById(R.id.Left);
        Reverse_btn = (Button) findViewById(R.id.backward);
        Stop_btn = (Button) findViewById(R.id.stop);
        Bluetooth_connect = (Button) findViewById(R.id.connect);
        Bluetooth_disconnect=(Button)findViewById(R.id.disconnect);

    }

    @Override
    public void onClick(View view) {
        if (view == logout) {
            firebaseAuth.signOut();
            finish();
            startActivity(new Intent(this, MainActivity.class));
        }
//OnTouchListener code for the forward button (button long press
        Forward_btn.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN)//MotionEvent.ACTION_DOWN is when you hold a button down
                {

                    command = "1";
                    try {
                        outputStream.write(command.getBytes());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } else if (event.getAction() == MotionEvent.ACTION_UP)//When you release the button
                {
                    command = "10";


                    try {
                        outputStream.write(command.getBytes());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }


                return false;
            }
        });
//OnTouchListener code for the reverse button (button long press)
        Reverse_btn.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    command = "2";
                    try {
                        outputStream.write(command.getBytes());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } else if (event.getAction() == MotionEvent.ACTION_UP) {
                    command = "10";
                    try {
                        outputStream.write(command.getBytes());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }


                return false;
            }
        });

        //OnTouchListener code for the left button (button long press)
        Left_btn.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    command = "3";
                    try {
                        outputStream.write(command.getBytes());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } else if (event.getAction() == MotionEvent.ACTION_UP) {
                    command = "10";
                    try {
                        outputStream.write(command.getBytes());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                return false;
            }
        });

        //OnTouchListener code for the  right button (button long press)
        Right_btn.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    command = "4";
                    try {
                        outputStream.write(command.getBytes());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } else if (event.getAction() == MotionEvent.ACTION_UP) {
                    command = "10";
                    try {
                        outputStream.write(command.getBytes());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                return false;
            }
        });

        Stop_btn.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    command = "5";
                    try {
                        outputStream.write(command.getBytes());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } else if (event.getAction() == MotionEvent.ACTION_UP) {
                    command = "10";
                    try {
                        outputStream.write(command.getBytes());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                return false;
            }
        });

        //Button that connects the device to the bluetooth module when pressed
        Bluetooth_connect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (BTinit()) {
                    BTconnect();
                }

            }
        });
        //add function to disconnect bluetooth here
        Bluetooth_disconnect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                resetConnection();
                if(true){
                    Toast.makeText(getApplicationContext(),"Bluetooth connection disconnected",Toast.LENGTH_SHORT).show();
                }
            }
        });

    }

    //initialise bluetooth module
    public boolean BTinit() {
        boolean found = false;
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (bluetoothAdapter == null)//checks if the intended device supports bluetooth
        {
            Toast.makeText(getApplicationContext(), "Device does not support Bluetooth", Toast.LENGTH_SHORT).show();
        }
        if (!bluetoothAdapter.isEnabled()) {
            Intent enableAdapter = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableAdapter, 0);

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        Set<BluetoothDevice> bondedDevices = bluetoothAdapter.getBondedDevices();
        if (bondedDevices.isEmpty())//check for paired bluetooth device
        {
            Toast.makeText(getApplicationContext(), "Please pair device first", Toast.LENGTH_SHORT).show();
        } else {
            for (BluetoothDevice iterator : bondedDevices) {
                if (iterator.getAddress().equals(Bluetooth_Address)) {
                    device = iterator;
                    found = true;
                    break;

                }
            }
        }
        return found;

    }

    public boolean BTconnect() {
        boolean connected = true;
        try {
            socket = device.createRfcommSocketToServiceRecord(PORT_UUID);
            socket.connect();

            Toast.makeText(getApplicationContext(), "Bluetooth device connected", Toast.LENGTH_SHORT).show();
            ;
        } catch (IOException e) {
            e.printStackTrace();
            connected = false;
        }

        if (connected) {
            try {
                outputStream = socket.getOutputStream();//gets output stream of socket
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return connected;
    }

    private void resetConnection(){
        if(inputStream!=null){
            try{
                inputStream.close();
            }
            catch (IOException e){
                e.printStackTrace();
            }
            inputStream=null;
        }
        if(outputStream!=null){
            try{
                outputStream.close();
            }
            catch(IOException e){
                e.printStackTrace();
            }
            outputStream=null;
        }
        if(socket!=null){
            try{
                socket.close();
            }
            catch (IOException e){
                e.printStackTrace();
            }
            socket=null;
        }
    }

    @Override
    protected void onStart() {
        super.onStart();

    }

}

I need the connect button to connect to the HC 06 and disconnect the socket connection on pressing disconnect

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62

1 Answers1

0

In your onCreate()-method you have to set an onClickListener to your connect and disconnect button like you did with your logout button.

prttyswt
  • 72
  • 7