Android:如何在连续的Service调用中存储Object?

时间:2013-03-31 16:19:12

标签: android service remoteview storing-data

我多次拨打Service,服务部门完成工作,然后自行停止。

我需要的是在同一服务的连续调用之间存储一个卑鄙,

那样:

  • 每次调用Service时,它都会检索对象

  • 并在下次通话中停止使用之前再次保存。

有问题的对象是RemoteViews对象。

1 个答案:

答案 0 :(得分:1)

使用可以使用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;
   }
}

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