How to create a Bluetooth Service on android?

0

I am making an application that searches and connects to bluetooth devices My problem is that when I change Activity and return to close the connection my BluetoothSocket returns to NULL and when I call the method for close() to close the connection no longer closes it. I was studying the possibility of creating a service that runs in the background so that when changing Activity, the Socket is not set to NULL .

If I do not change Activity, the connection and disconnection are done normally.

private BluetoothSocket mBTSocket;

These are the Functions I use

private class ConnectThread extends Thread {
    //private BluetoothSocket mmSocket;
    private final BluetoothDevice mmDevice;
    private final String mmAddress;
    private  final String mmName;
    private  final UUID mmUUID;


    public ConnectThread(BluetoothDevice device,final String name, final String address,UUID uuid,Handler handler) {
        this.mmAddress = address;
        this.mmName = name;
        this.mmDevice = device;
        //this.mmSocket = socket;
        this.mmUUID = uuid;
        BluetoothSocket tmp = null;
        try {
            tmp = mmDevice.createRfcommSocketToServiceRecord(mmUUID);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //mmSocket = tmp;
        mBTSocket = tmp;
    }

    @Override
    public void run() {
        boolean connected = false;
        mBluetoothAdapter.cancelDiscovery();
        try {
            mBTSocket.connect();
            connected = true;
        } catch(IOException e) {
            Log.d("CONNECTTHREAD","Could not connect: " + e.toString());
            try {
                //bTSocket.close();
                mBTSocket.close();
                handler.obtainMessage(STATE_CONNECTION_FAILED).sendToTarget();
                connected = false;
            } catch(IOException close) {
                Log.d("CONNECTTHREAD", "Could not close connection:" + e.toString());
                handler.obtainMessage(STATE_CONNECTION_FAILED).sendToTarget();
                connected = false;
            }
        }
        if(connected){
            mConnectedThread = new ConnectedThread(mBTSocket);
            mConnectedThread.start();
            handler.obtainMessage(STATE_CONNECTED, mmName).sendToTarget();
            handler.obtainMessage(STATE_CONNECTED_MAC,mmAddress).sendToTarget();
        }
    }

    public void cancel() {
        try {
            mBTSocket.close();
            //mBTSocket = null;

        } catch (IOException e) {
            handler.obtainMessage(STATE_DISCONNECTION_FAILED).sendToTarget();
        }
    }

}

This is the 2nd Function

private class ConnectedThread extends Thread{
    private final BluetoothSocket mmSocket;
    private final InputStream mmInStream;
    private final OutputStream mmOutStream;

    public ConnectedThread(BluetoothSocket socket){
        mmSocket = socket;
        InputStream tempIn = null;
        OutputStream temOut = null;

        try {
            tempIn = mmSocket.getInputStream();
            temOut = mmSocket.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        mmInStream = tempIn;
        mmOutStream = temOut;
    }

    public void run(){
        byte[] buffer = new byte[1024];
        int bytes;

        while (true){
            try {

                bytes = mmInStream.available();
                if(bytes != 0) {

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

                break;
            }
        }
    }
    public void write(String input) {
        byte[] bytes = input.getBytes();          
        try {
            mmOutStream.write(bytes);
        } catch (IOException e) { }
    }



    public void cancel() {
        try {
            mmSocket.close();
            handler.obtainMessage(STATE_DISCONNECT).sendToTarget();
        } catch (IOException e) {
            handler.obtainMessage(STATE_DISCONNECTION_FAILED).sendToTarget();
        }
    }


}

Messages at Handler I use to modify a TextView that shows the device with which the connection was established.

private final Handler handlerBT = new Handler(new Handler.Callback() {

    @SuppressLint("SetTextI18n")
    @Override
    public boolean handleMessage(Message msg) {

        switch (msg.what){
            case STATE_SEARCHING:
                ((Button) findViewById(R.id.button_scan_id)).setText(R.string.cancelar);
                textView_StatusBT_MAC.setText("");
                textView_StatusBT.setText("Buscando ...handler");
                break;
            case STATE_NO_SEARCHING:
                ((Button) findViewById(R.id.button_scan_id)).setText(R.string.buscar);
                break;
            case STATE_CONNECTING:
                textView_StatusBT.setText("Conectando... handler");
                break;
            case STATE_CONNECTED:
                textView_StatusBT.setText("Conectado a: " + (String)(msg.obj));
                break;
            case STATE_CONNECTED_MAC:
                textView_StatusBT_MAC.setText((String)(msg.obj));
                break;
            case STATE_DISCONNECT:
                textView_StatusBT.setText("Desconetado...handler" );
                textView_StatusBT_MAC.setText("");
                break;
            case STATE_DISCONNECTION_FAILED:
                textView_StatusBT.setText("Fallo en Desconexion...handler" );
                textView_StatusBT_MAC.setText("");
                break;
            case STATE_BT_ON:
                ((Button) findViewById(R.id.button_Conect_id)).setText(R.string.apagar_bluetooth);
                textView_StatusBT.setText("Encendido...handler");
                break;
            case STATE_BT_OFF:
                ((Button) findViewById(R.id.button_Conect_id)).setText(R.string.encender_bluetooth);
                textView_StatusBT.setText("Apagado...handler");
                break;
            case STATE_FOUND:
                textView_StatusBT.setText("Dispositivos Encontrados ...handler");
                break;
            case STATE_NOT_FOUND:
                textView_StatusBT.setText("No se encontraron Dispositivos ...handler");
                break;
            case STATE_TEST:
                break;
            case STATE_CONNECTION_FAILED:
                textView_StatusBT.setText("Connection Failed...handler");
                break;

            case STATE_MESSAGE_RECEIVED:
                //despues

                break;
        }
        return true;
    }
});
    
asked by Alejandro C. Bonilla 08.10.2018 в 23:54
source

0 answers