【问题标题】:How to cache objects into internal memory如何将对象缓存到内存中
【发布时间】:2014-07-10 07:32:24
【问题描述】:

我有一个问题。每次打开活动时,我都会创建某种重物。在使用程序时,这个活动可以打开很多次,所以每次我都应该等待一些繁重的事情完成。有没有办法将这个大对象缓存到内存中,并在第二次启动活动时从内存中获取它。 或者还有另一种方法可以做到这一点?

【问题讨论】:

标签: android


【解决方案1】:

将对象另存为文件:

FileOutputStream output = context.openFileOutput("object.bin", Context.MODE_PRIVATE);
ObjectOutputStream outputStream = new ObjectOutputStream(output);
outputStream.writeObject(objectToSave);
outputStream.close();

从文件中加载对象

FileInputStream input = context.openFileInput(fileName);
ObjectInputStream inputStream = new ObjectInputStream(input);
Object obj = inputStream.readObject();
inputStream.close();
ObjectToSave ots;
if(obj instanceof ObjectToSave)
{
its = (ObjectToSave) obj;
}

【讨论】:

    【解决方案2】:

    您可以随时随地extend Application 并存储/检索任意对象。

    所以你的活动看起来像这样

    void onCreate(Bundle bundle) {
       GlobalState state = (GlobalState) getApplicationContext();
       MyObject obj = state.getMyObject();
       if (obj == null) {
          obj = createHeavyObject();
          state.setMyObject(obj);
       }
       // your business logic here
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-09
      • 2013-07-27
      • 1970-01-01
      相关资源
      最近更新 更多