Skip to content Skip to sidebar Skip to footer

How To Notify An Activity When Globalvariables Are Changed

I have an android application that is connected to the computer via USB cable. I use a TCPServer Class to send messages and listen. For example: When I send a message like: request

Solution 1:

First of all, it is almost always bad practice to pass Activity instances around. This is a time when it's bad.

Define an interface and use a callback to let the activity know that a response has been received.

publicinterfaceResponseReceivedListener {
    voidonResponseReceived(int arg1, string arg2); // <- add arguments you want to pass back
}

In your TCPServer class:

ArrayList<ResponseReceivedListener> listeners = newArrayList<>();

// ...publicvoidsetResponseReceivedListener(ResponseReceivedListener listener) {
    if (!listeners.contains(listener) {
        listeners.add(listener);
    }
}

publicvoidremoveResponseReceivedListener(ResponseReceivedListener listener) {
    if (listeners.contains(listener) {
        listeners.remove(listener);
    }
}

When you receive a response:

for (ResponseReceivedListener listener : listeners) {
   listener.onResponseReceived(arg1, arg2);
}

In your Activity:

publicclassMainActivityextendsActivityimplementsResponseReceivedListener {

    // ...@OverridepublicvoidonCreate(Bundle savedInstanceState) {
        // ...

        tcpServer.setResponseReceivedListener(this);

        // ...
    }

    publicvoidonResponseReceived(int arg1, string arg2) {
        // do whatever you need to do
    }

    // ...
}

All from memory so please excuse typos.

This approach decouples the classes. The TCP Server has no knowledge of the activities. It simply calls back to any listeners registered. Those listeners might be Activities, they might be services. They might be instances of MySparklyUnicorn. The server neither knows nor cares. It simply says "if anyone's interested, I've received a response and here are the details".

Post a Comment for "How To Notify An Activity When Globalvariables Are Changed"