How to notify an activity when GlobalVariables are changed

烈酒焚心 提交于 2019-11-29 12:51:51

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.

public interface ResponseReceivedListener {
    void onResponseReceived(int arg1, string arg2); ..<----add arguments you want to pass back
}

In your TCPServer class

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

...

public void addResponseReceivedListener(ResponseReceivedListener listener){
    if (!listeners.contains(listener){
        listeners.add(listener);
    }
}

public void removeResponseReceivedListener(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:

public class MainActivity extends Activity implements ResponseReceivedListener {

...

@Override
public void onCreate(Bundle savedInstanceState) 
{
    ...
    tcpServer.setResponseReceivedistener(this);
    ...
}

public void onResponseReceived(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".

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!