简体   繁体   English

反序列化期间如何获得对Android Context的引用?

[英]How can I get a reference to Android Context during deserialization?

I have a class that holds a reference to a Context, and I plan to serialize an object of this class. 我有一个持有对Context的引用的类,并且我计划序列化此类的对象。 As you know, a Context object cannot be serialized, so I've marked it as transient . 如您所知, Context对象无法序列化,因此我将其标记为transient

Now, the problem I'm facing is how can I restore the state of the Context reference? 现在,我面临的问题是如何恢复Context引用的状态? I need to somehow pass in a reference to the application's current context during deserialization. 我需要在反序列化期间以某种方式传递对应用程序当前上下文的引用。 Is there a way to do this during deserialization, or do I have to first restore the object and then reinitialize the transient variable through a seperate method or something. 有没有办法在反序列化期间执行此操作,或者我必须首先还原对象,然后通过单独的方法或其他方法重新初始化transient变量。

You should look at overriding readObject() method. 您应该查看重写的readObject()方法。 And in readObject(), you can initialize Context variable to whatever value you consider suitable. 在readObject()中,您可以将Context变量初始化为您认为合适的任何值。

eg 例如

class Test implements Serializable{
 private int a;
 private string b;
 transient Context c;
 private void readObject(ObjectInputStream in) throws IOException{
  in.defaultReadObject();
  //now initialize transient fields
  c=ContextFactory.getContext();
 }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM