I am looking for a way to trigger the function named receiveUDP each time a UDP packet is received. How can can I do that on Kotlin? Here is the code I currently have working like a simple chat.
It uses 01 editText for user input, 01 textView for display received packets and one button to send user input.
package com.e.udpchat1
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.os.StrictMode
import android.view.View
import android.widget.EditText
import android.widget.TextView
import java.io.IOException
import java.net.DatagramPacket
import java.net.DatagramSocket
import java.net.InetAddress
class SoftOptions {
var RemoteHost: String = "192.168.1.255"
var RemotePort: Int = 6454
constructor()
init{}
}
// Global
val Settings = SoftOptions()
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Where should I call?
// var Buffer = receiveUDP(1500)
// so that it constantly listen to incoming UDP packets
}
fun clickButtonSend(view: View) {
// Do something in response to button
// Send editText1 Text thru UDP.
val editText = findViewById<EditText>(R.id.editText1)
var message = editText.text.toString()
sendUDP(message)
// Add text to textView1.
val textView = findViewById<TextView>(R.id.textView1)
var chat = textView.text.toString()
textView.setText(chat + message + "\n")
// Clear editText1 after all sent.
editText.setText("")// Clear Input text.
}
fun sendUDP(messageStr: String) {
// Hack Prevent crash (sending should be done using an async task)
val policy = StrictMode.ThreadPolicy.Builder().permitAll().build()
StrictMode.setThreadPolicy(policy)
try {
//Open a port to send the package
val socket = DatagramSocket()
socket.broadcast = true
val sendData = messageStr.toByteArray()
val sendPacket = DatagramPacket(sendData, sendData.size, InetAddress.getByName(Settings.RemoteHost), Settings.RemotePort)
socket.send(sendPacket)
println("fun sendBroadcast: packet sent to: " + InetAddress.getByName(Settings.RemoteHost) + ":" + Settings.RemotePort)
} catch (e: IOException) {
// Log.e(FragmentActivity.TAG, "IOException: " + e.message)
}
}
fun receiveUDP( size: Int): ByteArray {
val ret = ByteArray(size)
var socket: DatagramSocket? = null
try {
//Keep a socket open to listen to all the UDP trafic that is destined for this port
socket = DatagramSocket(Settings.RemotePort, InetAddress.getByName(Settings.RemoteHost))
socket.broadcast = true
val Buffer = ByteArray(1500)
val packet = DatagramPacket(Buffer, Buffer.size)
socket.receive(packet)
// Add text to textView1.
val textView = findViewById<TextView>(R.id.textView1)
val chat = textView.text.toString()
textView.setText(chat + packet + "\n")
} catch (e: Exception) {
e.printStackTrace()
} finally {
socket?.close()
}
return ret
}
}
I would expect to see every received packet in the textView1.