How to notify an activity when GlobalVariables are changed

前端 未结 1 1233
不思量自难忘°
不思量自难忘° 2020-12-20 07:38

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 messag

相关标签:
1条回答
  • 2020-12-20 08:20

    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".

    0 讨论(0)
提交回复
热议问题