Search code examples
androidserviceremoteviewstoring-data

Android: how to store an Object in consecutive Service calls?


I call a Service several times, the Service performs its job and then stop himself.

What I need is to store an abject between consecutive calls of the same Service,

So that:

  • every time the Service is called it retrieves the object uses

  • and it saves it again before stopping for using it in the next call.

The object in question is a RemoteViews object.


Solution

  • use can use Singleton Pattern:

    public class SingletonClass{
       private YourObject objectToStoreBetweenSession;
       private SigletonClass instance;
       private SingletonClass(){
           objectToStoreBetweenSession = new YourObject();
       }
    
       private static SingletonClass getInstance(){
          if(instance==null)
             instance = new SingletonClass();
          return instance;
       }
       public void setObject(YourObject obj){
          objectToStoreBetweenSession = obj;
       }
       public YourObject getObject(){
          return objectToStoreBetweenSession;
       }
    }
    

    Into your Service:

    YourObject objectToStoreBetweenSession = SingletonClass.getInstance().getObject();
    if(objectToStoreBetweenSession.value==0){
       //First time that Service is called.
    }else{
       //Do whatever you want
       SingoletonClass.getInstance().setObject(new YourObject("value"));
    }