2010-04-08 42 views
19

我想序列化一个Bundle对象,但似乎无法找到一个简单的方法。使用Parcel似乎不是一种选择,因为我想将序列化的数据存储到文件中。如何序列化一个包?

关于如何做到这一点的任何想法?

我想要这个的原因是保存和恢复我的活动状态,当它被用户杀死时。我已经创建了一个包含我想保存在onSaveInstanceState中的状态的Bundle。但是,当活动被SYSTEM终止时,android只保留这个Bundle。当用户杀死该活动时,我需要自己保存它。因此,我想序列化并将其存储到文件中。当然,如果你有其他方式来完成同样的事情,我也会为此感恩。

编辑: 我决定将我的状态编码为JSONObject而不是Bundle。然后可以将JSON对象作为可序列化放入Bundle中,或存储到文件中。可能不是最有效的方式,但它很简单,它似乎工作正常。

回答

6

我使用SharedPreferences来解决这个限制,它使用与Bundle类一样的存储和检索数据的putXXX()和getXXX()风格,如果以前使用过Bundle,实现相对简单。

所以的onCreate我在onRestoreInstanceState()

这样

if(savedInstanceState != null) 
{ 
    loadGameDataFromSavedInstanceState(savedInstanceState); 
} 
else 
{ 
    loadGameDataFromSharedPreferences(getPreferences(MODE_PRIVATE)); 
} 

我在我的游戏数据保存到的onSaveInstanceState()一包检查,并从包中加载数据

我还游戏数据从SharedPreferences中的onResume保存到的onPause()SharedPreferences,和负载数据()

onPause() 
{ 
    // get a SharedPreferences editor for storing game data to 
    SharedPreferences.Editor mySharedPreferences = getPreferences(MODE_PRIVATE).edit(); 

    // call a function to actually store the game data 
    saveGameDataToSharedPreferences(mySharedPreferences); 

    // make sure you call mySharedPreferences.commit() at the end of your function 
} 

onResume() 
{ 
    loadGameDataFromSharedPreferences(getPreferences(MODE_PRIVATE)); 
} 

如果有人觉得这是对SharedPreferences的不正确使用,我不会感到惊讶,但它可以完成工作。我一直在我的所有游戏(近200万次下载)中使用这种方法一年多,并且工作正常。

+2

当然有效,我只是希望避免有两种绑定状态的方法,即使它们非常相似。 – hermo 2010-04-09 04:51:24

+0

这正是我想要保存持久状态的想法。 – Awemo 2012-05-13 13:06:12

7

存储任何Parcelable到一个文件是很容易的:

FileOutputStream fos = context.openFileOutput(localFilename, Context.MODE_PRIVATE); 
Parcel p = Parcel.obtain(); // i make an empty one here, but you can use yours 
fos.write(p.marshall()); 
fos.flush(); 
fos.close(); 

享受!

+9

是的,我也找到了。问题是,不能保证你可以再次解组它,比如操作系统被更新并且Parcel已经改变。但是如果你能忍受这一点,那就没问题了。 – hermo 2010-04-09 04:41:03

+12

您从方法mashall()中检索到的数据不得放置在任何类型的永久性存储器中(在本地磁盘上,通过网络等)。为此,您应该使用标准序列化或其他类型的通用序列化机制。地块编组表示针对本地IPC进行了高度优化,因此不会尝试保持与在不同版本的平台中创建的数据的兼容性。 (http://developer.android.com/reference/android/os/Parcel.html#marshall()) – Oneiros 2012-06-11 17:59:00

+0

我想你不应该把保存的文件转移到其他的devies,但可能没关系,如果你正在使用它在单个设备上(例如,用于保存临时数据)。 – 2012-08-24 12:08:56

4

将其转换为SharedPreferences:

private void saveToPreferences(Bundle in) { 
    Parcel parcel = Parcel.obtain(); 
    String serialized = null; 
    try { 
     in.writeToParcel(parcel, 0); 

     ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
     IOUtils.write(parcel.marshall(), bos); 

     serialized = Base64.encodeToString(bos.toByteArray(), 0); 
    } catch (IOException e) { 
     Log.e(getClass().getSimpleName(), e.toString(), e); 
    } finally { 
     parcel.recycle(); 
    } 
    if (serialized != null) { 
     SharedPreferences settings = getSharedPreferences(PREFS, 0); 
     Editor editor = settings.edit(); 
     editor.putString("parcel", serialized); 
     editor.commit(); 
    } 
} 

private Bundle restoreFromPreferences() { 
    Bundle bundle = null; 
    SharedPreferences settings = getSharedPreferences(PREFS, 0); 
    String serialized = settings.getString("parcel", null); 

    if (serialized != null) { 
     Parcel parcel = Parcel.obtain(); 
     try { 
      byte[] data = Base64.decode(serialized, 0); 
      parcel.unmarshall(data, 0, data.length); 
      parcel.setDataPosition(0); 
      bundle = parcel.readBundle(); 
     } finally { 
      parcel.recycle(); 
     } 
    } 
    return bundle; 
} 
+4

这又违背了将包裹内容存储到任何形式的持久性内存(Javadocs警告)的建议。假设你出于某种原因去更新操作系统,那么上面的代码会在'restoreFromPreferences()“方法中崩溃你的应用程序,或者返回一些未知的值。 – Yinzara 2013-01-29 10:28:43

0

如果你想将其存储在持久性存储,你不能依靠parcelable也不序列化机制。你必须自己做,下面是怎样的方式,我通常做:

private static final Gson sGson = new GsonBuilder().create(); 
private static final String CHARSET = "UTF-8"; 
// taken from http://www.javacamp.org/javaI/primitiveTypes.html 
private static final int BOOLEAN_LEN = 1; 
private static final int INTEGER_LEN = 4; 
private static final int DOUBLE_LEN = 8; 

public static byte[] serializeBundle(Bundle bundle) { 
    try { 
     List<SerializedItem> list = new ArrayList<>(); 
     if (bundle != null) { 
      Set<String> keys = bundle.keySet(); 
      for (String key : keys) { 
       Object value = bundle.get(key); 
       if (value == null) continue; 
       SerializedItem bis = new SerializedItem(); 
       bis.setClassName(value.getClass().getCanonicalName()); 
       bis.setKey(key); 
       if (value instanceof String) 
        bis.setValue(((String) value).getBytes(CHARSET)); 
       else if (value instanceof SpannableString) { 
        String str = Html.toHtml((Spanned) value); 
        bis.setValue(str.getBytes(CHARSET)); 
       } else if (value.getClass().isAssignableFrom(Integer.class)) { 
        ByteBuffer b = ByteBuffer.allocate(INTEGER_LEN); 
        b.putInt((Integer) value); 
        bis.setValue(b.array()); 
       } else if (value.getClass().isAssignableFrom(Double.class)) { 
        ByteBuffer b = ByteBuffer.allocate(DOUBLE_LEN); 
        b.putDouble((Double) value); 
        bis.setValue(b.array()); 
       } else if (value.getClass().isAssignableFrom(Boolean.class)) { 
        ByteBuffer b = ByteBuffer.allocate(INTEGER_LEN); 
        boolean v = (boolean) value; 
        b.putInt(v ? 1 : 0); 
        bis.setValue(b.array()); 
       } else 
        continue; // we do nothing in this case since there is amazing amount of stuff you can put into bundle but if you want something specific you can still add it 
//      throw new IllegalStateException("Unable to serialize class + " + value.getClass().getCanonicalName()); 

       list.add(bis); 
      } 
      return sGson.toJson(list).getBytes(CHARSET); 
     } 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
    throw new IllegalStateException("Unable to serialize " + bundle); 
} 

public static Bundle deserializeBundle(byte[] toDeserialize) { 
    try { 
     Bundle bundle = new Bundle(); 
     if (toDeserialize != null) { 
      SerializedItem[] bundleItems = new Gson().fromJson(new String(toDeserialize, CHARSET), SerializedItem[].class); 
      for (SerializedItem bis : bundleItems) { 
       if (String.class.getCanonicalName().equals(bis.getClassName())) 
        bundle.putString(bis.getKey(), new String(bis.getValue())); 
       else if (Integer.class.getCanonicalName().equals(bis.getClassName())) 
        bundle.putInt(bis.getKey(), ByteBuffer.wrap(bis.getValue()).getInt()); 
       else if (Double.class.getCanonicalName().equals(bis.getClassName())) 
        bundle.putDouble(bis.getKey(), ByteBuffer.wrap(bis.getValue()).getDouble()); 
       else if (Boolean.class.getCanonicalName().equals(bis.getClassName())) { 
        int v = ByteBuffer.wrap(bis.getValue()).getInt(); 
        bundle.putBoolean(bis.getKey(), v == 1); 
       } else 
        throw new IllegalStateException("Unable to deserialize class " + bis.getClassName()); 
      } 
     } 
     return bundle; 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
    throw new IllegalStateException("Unable to deserialize " + Arrays.toString(toDeserialize)); 
} 

您表示数据的字节数组,你可以很容易地存储文件,通过网络发送或使用ormLite作为存储到SQL数据库如下:

@DatabaseField(dataType = DataType.BYTE_ARRAY) 
    private byte[] mRawBundle; 

和SerializedItem:

public class SerializedItem { 


private String mClassName; 
private String mKey; 
private byte[] mValue; 

// + getters and setters 
} 

PS:上面的代码依赖于GSON库(这是非常常见的,只是为了让你知道)。

相关问题