objectToStoreBetweenSession

objectToStoreBetweenSession

我多次呼叫Service,服务执行其工作,然后停止工作。

我需要在同一服务的连续调用之间存储一个对象,

以便:


每次调用服务时,它都会检索使用的对象
并再次保存它,然后在下一次调用中停止使用它。


有问题的对象是RemoteViews对象。

最佳答案

使用可以使用单例模式:

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;
   }
}


进入您的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"));
}

10-06 03:16