0

I'm having a problem involving my android app and an arduino board. I installed an app that searches for available bluetooth devices and connects to them, now I want when the devices disconnect a notification is sent to the mobile device ... Anyone know how to do this function ???

ConnectionThread:

 public class ConnectionThread extends Thread {

BluetoothSocket btSocket = null;
BluetoothServerSocket btServerSocket = null;
InputStream input = null;
OutputStream output = null;
String btDevAddress = null;
String myUUID = "00001101-0000-1000-8000-00805F9B34FB";
boolean server;
boolean running = false;

/*  Este construtor prepara o dispositivo para atuar como servidor.
 */
public ConnectionThread() {

    this.server = true;
}

/*  Este construtor prepara o dispositivo para atuar como cliente.
    Tem como argumento uma string contendo o endereço MAC do dispositivo
Bluetooth para o qual deve ser solicitada uma conexão.
 */
public ConnectionThread(String btDevAddress) {

    this.server = false;
    this.btDevAddress = btDevAddress;
}

/*  O método run() contem as instruções que serão efetivamente realizadas
em uma nova thread.
 */
public void run() {

    /*  Anuncia que a thread está sendo executada.
        Pega uma referência para o adaptador Bluetooth padrão.
     */
    this.running = true;
    BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();

    /*  Determina que ações executar dependendo se a thread está configurada
    para atuar como servidor ou cliente.
     */
    if(this.server) {

        /*  Servidor.
         */
        try {

            /*  Cria um socket de servidor Bluetooth.
                O socket servidor será usado apenas para iniciar a conexão.
                Permanece em estado de espera até que algum cliente
            estabeleça uma conexão.
             */
            btServerSocket = btAdapter.listenUsingRfcommWithServiceRecord("AWC", UUID.fromString(myUUID));
            btSocket = btServerSocket.accept();

            /*  Se a conexão foi estabelecida corretamente, o socket
            servidor pode ser liberado.
             */
            if(btSocket != null) {

                btServerSocket.close();
            }

        } catch (IOException e) {

            /*  Caso ocorra alguma exceção, exibe o stack trace para debug.
                Envia um código para a Activity principal, informando que
            a conexão falhou.
             */
            e.printStackTrace();
            toMainActivity("---N".getBytes());
        }


    } else {

        /*  Cliente.
         */
        try {

            /*  Obtem uma representação do dispositivo Bluetooth com
            endereço btDevAddress.
                Cria um socket Bluetooth.
             */
            BluetoothDevice btDevice = btAdapter.getRemoteDevice(btDevAddress);
            btSocket = btDevice.createRfcommSocketToServiceRecord(UUID.fromString(myUUID));

            /*  Envia ao sistema um comando para cancelar qualquer processo
            de descoberta em execução.
             */
            btAdapter.cancelDiscovery();

            /*  Solicita uma conexão ao dispositivo cujo endereço é
            btDevAddress.
                Permanece em estado de espera até que a conexão seja
            estabelecida.
             */
            if (btSocket != null)
                btSocket.connect();

        } catch (IOException e) {

            /*  Caso ocorra alguma exceção, exibe o stack trace para debug.
                Envia um código para a Activity principal, informando que
            a conexão falhou.
             */
            e.printStackTrace();
            toMainActivity("---N".getBytes());
        }

    }

    /*  Pronto, estamos conectados! Agora, só precisamos gerenciar a conexão.
        ...
     */

    if(btSocket != null) {

        /*  Envia um código para a Activity principal informando que a
        a conexão ocorreu com sucesso.
         */
        toMainActivity("---S".getBytes());

        try {

            /*  Obtem referências para os fluxos de entrada e saída do
            socket Bluetooth.
             */
            input = btSocket.getInputStream();
            output = btSocket.getOutputStream();

            /*  Cria um byte array para armazenar temporariamente uma
            mensagem recebida.
                O inteiro bytes representará o número de bytes lidos na
            última mensagem recebida.
             */
            byte[] buffer = new byte[1024];
            int bytes;

            /*  Permanece em estado de espera até que uma mensagem seja
            recebida.
                Armazena a mensagem recebida no buffer.
                Envia a mensagem recebida para a Activity principal, do
            primeiro ao último byte lido.
                Esta thread permanecerá em estado de escuta até que
            a variável running assuma o valor false.
             */
            while(running) {

                bytes = input.read(buffer);
                toMainActivity(Arrays.copyOfRange(buffer, 0, bytes));

            }

        } catch (IOException e) {

            /*  Caso ocorra alguma exceção, exibe o stack trace para debug.
                Envia um código para a Activity principal, informando que
            a conexão falhou.
             */
            e.printStackTrace();
            toMainActivity("---N".getBytes());
        }
    }

}

/*  Utiliza um handler para enviar um byte array à Activity principal.
    O byte array é encapsulado em um Bundle e posteriormente em uma Message
antes de ser enviado.
 */
private void toMainActivity(byte[] data) {

    Message message = new Message();
    Bundle bundle = new Bundle();
    bundle.putByteArray("data", data);
    message.setData(bundle);
    MainActivity.handler.sendMessage(message);
}

/*  Método utilizado pela Activity principal para transmitir uma mensagem ao
 outro lado da conexão.
    A mensagem deve ser representada por um byte array.
 */
public void write(byte[] data) {

    if(output != null) {
        try {

            /*  Transmite a mensagem.
             */
            output.write(data);

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

        /*  Envia à Activity principal um código de erro durante a conexão.
         */
        toMainActivity("---N".getBytes());
    }
}

/*  Método utilizado pela Activity principal para encerrar a conexão
 */
public void cancel() {

    try {

        running = false;
        btServerSocket.close();
        btSocket.close();



    } catch (IOException e) {
        e.printStackTrace();
    }
    running = false;
}

Main Activity:

 public class MainActivity extends AppCompatActivity {

public static int ENABLE_BLUETOOTH = 1;
public static int SELECT_PAIRED_DEVICE = 2;
public static int SELECT_DISCOVERED_DEVICE = 3;

static TextView statusMessage;
static TextView textSpace;
ConnectionThread connect;

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

    statusMessage = (TextView) findViewById(R.id.statusMessage);
    textSpace = (TextView) findViewById(R.id.textSpace);

    BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
    if (btAdapter == null) {
        statusMessage.setText("Que pena! Hardware Bluetooth não está funcionando :(");
    } else {
        statusMessage.setText("Ótimo! Hardware Bluetooth está funcionando :)");
        if(!btAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, ENABLE_BLUETOOTH);
            statusMessage.setText("Solicitando ativação do Bluetooth...");

        } else {
            statusMessage.setText("Bluetooth já ativado :)");
        }
    }
}


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if(requestCode == ENABLE_BLUETOOTH) {
        if(resultCode == RESULT_OK) {
            statusMessage.setText("Bluetooth ativado :D");
        }
        else {
            statusMessage.setText("Bluetooth não ativado :(");
        }
    }
    else if(requestCode == SELECT_PAIRED_DEVICE || requestCode == SELECT_DISCOVERED_DEVICE) {
        if(resultCode == RESULT_OK) {
            statusMessage.setText("Você selecionou " + data.getStringExtra("btDevName") + "\n"
                    + data.getStringExtra("btDevAddress"));

            connect = new ConnectionThread(data.getStringExtra("btDevAddress"));
            connect.start();
        }
        else {
            statusMessage.setText("Nenhum dispositivo selecionado :(");
        }
    }
}

public void discoverDevices(View view) {

    Intent searchPairedDevicesIntent = new Intent(this, DiscoveredDevices.class);
    startActivityForResult(searchPairedDevicesIntent, SELECT_DISCOVERED_DEVICE);
}

public void enableVisibility(View view) {

    Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
    discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 30);
    startActivity(discoverableIntent);
}

public void waitConnection(View view) {

    connect = new ConnectionThread();
    connect.start();
}

public void sendMessage(View view) {

    EditText messageBox = (EditText) findViewById(R.id.editText_MessageBox);
    String messageBoxString = messageBox.getText().toString();
    byte[] data =  messageBoxString.getBytes();
    connect.write(data);
}

@SuppressLint("HandlerLeak")
public static Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {

        Bundle bundle = msg.getData();
        byte[] data = bundle.getByteArray("data");
        String dataString= new String(data);

        if(dataString.equals("---N"))
            statusMessage.setText("Ocorreu um erro durante a conexão D:");
        else if(dataString.equals("---S"))
            statusMessage.setText("Conectado :D");
        else {

           // textSpace.setText(new String(data));
        }
    }
};
 ***function I want to perform***

public void alarme(){
    NotificationCompat.Builder mBuilder =
            new NotificationCompat.Builder(this)
                    .setContentTitle("My notification")
                    .setContentText("Hello World!");

    Intent resultIntent = new Intent(this, MainActivity.class);
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        stackBuilder.addParentStack(MainActivity.class);
    stackBuilder.addNextIntent(resultIntent);
    PendingIntent resultPendingIntent =
            stackBuilder.getPendingIntent(
                    0,
                    PendingIntent.FLAG_UPDATE_CURRENT
            );
    mBuilder.setContentIntent(resultPendingIntent);
    NotificationManager mNotificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    mNotificationManager.notify(0, mBuilder.build());
}

}

1 Answers1

0

I have solved this issue, Problem is when bluetooth connection is lost, then how you send notification ? So, solution is your android phone ping to bluetooth device everything 10 seconds or 5 seconds, bluetooth device will receive this ping and send response back to your android phone. if your phone gets response, then its working, if your phone does not get response. then you should show user that device is disconnected.

Mubashar Javed
  • 749
  • 1
  • 5
  • 12