I implemented a UPD receiver into my android application. So far I only had one MainAvtivity and I updated a TextView in the Main UI by passing the MainActivity to the UDPReceiver class.
Now I have a second activity and I want my UDP receiver to update a global String variable which can then be accessed by the activity which is currently active.
Also the active Activity needs to have a listener to know when there is a new UDP message. Here is the code for my UDPreceiver.
public class UDPglobalReceiver extends AppCompatActivity implements Runnable {
private final int listen2port = 12345;
private String receivedMessage;
public globalApplication application;
@Override
public void run() {
try (DatagramSocket myclientSocket = new DatagramSocket(null)) {
myclientSocket.setReuseAddress(true);
myclientSocket.setBroadcast(true);
myclientSocket.bind(new InetSocketAddress(listen2port));
while (true) {
byte[] buffer = new byte[256]; // maybe make it smaller if the messages are certainly smaller (max UDP payload)
DatagramPacket mydatagramPacket = new DatagramPacket(buffer, 0, buffer.length);
myclientSocket.receive(mydatagramPacket);
receivedMessage = new String(mydatagramPacket.getData(), "UTF8");
Log.d("UDP", "---------------- UDP: " + receivedMessage);
final String[] ProcessedMessage = receivedMessage.split("\."); // Seperate by .
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
I'm restarting the UDPreceiver class whenever the activity is changed:
// Start the UDP background thread
Thread myPiUDPListener = new Thread(new UDPglobalReceiver());// Create a Thread to listen UDP
myPiUDPListener.start();
There is no necessity for background activity so this is OK.
Question in short how can I update a global variable within my UDPReceiver background thread (within the class) ?
Is there an eventListener that listens whether a global variable has been changed.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…