Search code examples
androidandroid-asynctasksingletonandroid-handlerbackground-thread

Android singleton thread talking to server


This is mostly a design decision question.
I have an activity, a broadcast receiver, and a class that talks to my server (call it ServerAccess).

ServerAccess naturally needs to be in a thread of its own since it will be handling some network tasks. The activity needs to have its UI updated from the results of ServerAccess (so it needs some way to access the UI thread). The broadcast receiver also sends needs to send data to ServerAccess.

My question is, should I make ServerAccess a singleton thread? If so, how do you achieve that in Android? My reason for making it singleton is that every time any data exchange occurs from the server, I needs to query some basic user information from the server before I can start exchanging data. I would not like to query this basic user information every time the broadcast receiver receives a broadcast, or every time the activity is opened. Instead, I think a better idea would be to fetch the singleton ServerAccess if it is already created and start exchanging data. If ServerAccess was already instantiated then it would have already fetched that basic user information from the server.

Now would an AsyncTask be the way to go forward with this? Or to make a thread in my Application class like so? Or a singleton Service would be a better idea?


Solution

  • I do think you have to make it singleton. To make a singleton class create a static object of that class and then create a static method getInstance() and here if the object of the class is null then create the instance of the classs else return the instance ..

    Example :

              public class ServerAccess{
                   public static ServerAccess severAccess = null;
                   public static ServerAccess getInstance(){
                       if(serverAccess != null)return serverAccess;
                        serverAccess = new ServerAccess();
                         return serverAccess;
                   }
               }