javaandroidmultithreadingandroid-snackbar

Android java - Trying to show snackbar in new thread


Ive been trying to make my bluetooth connection thread be able to send messages to the user through snackbars, but they never appear on the screen.

In main method:

//listener for connect button
    try {
        Button btn_connect = findViewById(R.id.btn_connect);
        btn_connect.setOnClickListener(view -> {
            if(bluetoothService.isStarted()){
                snackbarMsg(findViewById(R.id.btn_connect), "Bluetooth connection already established");
            } else{
                new Thread(() -> {
                    try {
                        Log.i(TAG, "New thread started");
                        bluetoothService.run(MainActivity.this);
                        Log.i(TAG,"Bluetooth service started");
                        snackbarMsg(findViewById(R.id.btn_connect), "Bluetooth service started");
                    } catch (Exception e) {
                        Log.e(TAG, "Bluetooth service failed", e);
                    }
                }).start();
            }
        });
    } catch (Exception exception){
        Log.e(TAG, "Bluetooth service failed");
    }

in BluetoothService class:

public void snackbarMsg (View view, String msg){
    try {
        Snackbar snackbar = Snackbar.make(view, msg, BaseTransientBottomBar.LENGTH_SHORT);

        snackbar.show();
    } catch (Exception exception){
        Log.e(TAG, "Could not show snackbar", exception);
    }
}

The view i send with the method is always of something on the main screen, so for example using "snackbarMsg(findViewById(R.id.button_send),"Failed to find bluetooth server");" where button_send is on the screen i want to show the snackbar.

ive tried using runnables and extends thread and whatnot. But since i already have extensions on bluetoothservice class that didnt work, and runnable proved troublesome because i need to send context when starting the run method, and that context seemingly cant be sent at an earlier state, meaning i cant send that info when i create and object fom bluetoothservice at the beginning of the program.

Secondly: im not sure i even need a second thread, since my bluetooth connection is only sending data, not receiving, am i just doing useless work?


Solution

  • You need to run it on the UI/Main thread.

    Use runOnUiThread(action: Runnable)

    runOnUiThread(() -> snackbarMsg(view, "insert message"));