Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
107 views
in Technique[技术] by (71.8m points)

java - UDP receiver in mulitple activities using Runnable: android studio

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I created a working solution:

For the global variables I used a Singleton design pattern where I created a class that looks like this:

import android.app.Application;
import android.util.Log;

public final class Global_Singleton extends Application {

    public static volatile Global_Singleton INSTANCE = null;

    private Global_Singleton() {}

    // Thread safe by synchronized
    // https://www.youtube.com/watch?v=vSxKnvxe8v0
    public static Global_Singleton getInstance() {
        if (INSTANCE == null) {
            synchronized (Global_Singleton.class) {
                if (INSTANCE == null) { // double check locking
                    INSTANCE = new Global_Singleton();
                }
            }
        }
        return INSTANCE;
    }

    // ----------  UDP incoming data ----------
    private String[] ProcessedMessage;

    public String[] getIncomingMessage() {
        return ProcessedMessage;
    }

    public void setIncomingMessage(String[] processedMessage) {
        ProcessedMessage = processedMessage;
        Log.d("MINE", "---------------- Global_Singleton: " + ProcessedMessage[0]);
    }

}

In my MainActivity I called it using the following line:

Global_Singleton.getInstance();

From now on the variable can be changed and accessed from any activity:

Global_Singleton.INSTANCE.setIncomingMessage(ProcessedMessage);

In order to react to a new message from the server I used Shared Preference and an SharedPreferences.OnSharedPreferenceChangeListener following this Video: https://www.youtube.com/watch?v=XEDmE-pnhqs

I'm not sure if this is the best solution but it definitely does what it is supposed to do.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...