I am trying to create basic WebSocket server with this library. I want to make a toast message when a message is received. In onMessage() function below I have implemented that. But no toast message is happening.
But Received message is printed on console.
WebSocketServer ws = new WebSocketServer(new InetSocketAddress(3000)) { @Override public void onOpen(WebSocket conn, ClientHandshake handshake) { conn.send("Hello world"); } @Override public void onClose(WebSocket conn, int code, String reason, boolean remote) { } @Override public void onMessage(WebSocket conn, String message) { System.out.println("Recieved: "+message); Toast.makeText(MainActivity.this, "Recieved: " + message, Toast.LENGTH_SHORT).show(); } @Override public void onError(WebSocket conn, Exception ex) { } @Override public void onStart() { } }; ws.start(); }
Advertisement
Answer
I think you have to switch to the UI thread to show the Toast.
You can try using a Handler
:
new Handler(Looper.getMainLooper()).post(new Runnable() { public void run() { Toast.makeText(MainActivity.this, "Received: " + message, Toast.LENGTH_SHORT).show(); } });
Or calling runOnUiThread
:
runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(MainActivity.this, "Received: " + message, Toast.LENGTH_SHORT).show(); } });
Or broadcasting the message:
@Override public void onMessage(WebSocket conn, String message) { System.out.println("Recieved: "+message); Intent intent = new Intent("msgReceived"); intent.putExtra("message", message); LocalBroadcastManager.getInstance(this).sendBroadcast(intent); }
And registering a BroadcastReceiver in your Activity:
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String message = intent.getExtras().getString("message"); Toast.makeText(MainActivity.this, "Received: " + message, Toast.LENGTH_SHORT).show(); } }; @Override protected void onStart() { super.onStart(); LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, new IntentFilter("msgReceived")); @Override protected void onStop() { LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver); super.onStop(); }