Using single Class in multiple Activities

2020-07-31 03:31发布

问题:

I implemented a class called WebSocketClient which provides the functionality to open and connect to a websocket, send data through the websocket, etc... Now I want to use this class in my Activities. In order to be informed of incomming messages from the websocket i created a WebsocketListener which can be registered in the WebSocketClient so the activity which would like to communicate through the Websocket would implement this interface and register itself. The problem is, how can I use the WebSocketClient in multiple activities? My first idea was to implement the WebSocketClient class as a Singleton, so in each activity I am able to get the instance of the WebSocketClient via WebSocketClient.getInstance() and register itself as a WebSocketListener. Is this a good way of implementing what i want? So if i am in Activity A i would call WebSocketClient.getInstance().register(this), when i switch to the next Activity B I also have to call WebSocketClient.getInstance().register(this) which would change the current listener to the current active activity. This way i am able to use the WebSocketClient in each activity.

Will this work? Does anybody have a better solution?

kind regards

回答1:

You could use the Application class and start your WebSocketClient class as a Singleton.

public class WebSocketClientManager implements OnCloseListener {

 private WeakHashMap<? extends BaseUIListener, Integer> uiListenerss;
 private final static WebSocketClientManager instance;
 static {
    instance = new WebSocketClientManager();
 }

 public static WebSocketClientManager getInstance() {
    return instance;
 }

 @Override
   public void onCloseingTheApp() {
   // do stuff
 }

 // methods
  getListeners 
  setListener
}

You could also let the Application class hold all BaseUIListener. And then in all your Activity´s onResume() you do like this:

 Application.getInstance().addUIListener(OnSomeChangedListener.class, this);

Your WebSocketClientManager when it has something to say it will do like this

for (OnSomeChangedListener someChangedListener: Application.getInstance().getUIListeners(OnSomeChangedListener.class))
     someChangedListener.OnSomeChanged("This just happend");

There is a very nice example of this here: xabber Application class



回答2:

If you store your WebSocketClient object in the Application class you would not have to have Singleton. You could just get it from getApplicationContext() method in activities and use its methods as they are.

That being said, if you will implement Singleton, I would suggest using INSTANCE variable in enum instead of getInstance() method. You can find example at following url: What is the best approach for using an Enum as a singleton in Java?