WebSocket and Push Notification in android kotlin (without using any external services)

34 Views Asked by At

I am writing a program that was getting simple notification from web socket. I have webSocket node JS server and I want to show notification when message is received from web socket server. In WebSocketListener class's onMessage function, I want to show notification or alert box. I got message from websocket and I don't know how to write notification function in this onMessage function.Here is my code. I knew only calling notification or alert function in mainActivity.

override fun onMessage(webSocket: WebSocket, text: String) {
        outPut("Received : $text");
        //I want to show alertDialog with this text from websocket
    }

I have a function for show alert box in mainActivity.

public fun createPushNotification(text: String) {
        val builder = AlertDialog.Builder(this)
        //set title for alert dialog
        builder.setTitle("Testing.")
        //set message for alert dialog
        builder.setMessage("This is testing message for notification.")
        builder.setIcon(android.R.drawable.ic_dialog_alert)

        //performing positive action
        builder.setPositiveButton("Yes"){dialogInterface, which ->
            Toast.makeText(applicationContext,"clicked yes", Toast.LENGTH_LONG).show()
        }
        //performing cancel action
        builder.setNeutralButton("Cancel"){dialogInterface , which ->
            Toast.makeText(applicationContext,"clicked cancel\n operation cancel", Toast.LENGTH_LONG).show()
        }
        //performing negative action
        builder.setNegativeButton("No"){dialogInterface, which ->
            Toast.makeText(applicationContext,"clicked No", Toast.LENGTH_LONG).show()
        }
        // Create the AlertDialog
        val alertDialog: AlertDialog = builder.create()
        // Set other dialog properties
        alertDialog.setCancelable(false)
        alertDialog.show()
    }
0

There are 0 best solutions below