1

所以我在这里有这段代码;

myIntent.putExtra("schedule",serializableClass);

这个意图转到我的广播接收器,我确实得到了如下可序列化的,

public void  onRecieve(Context context, Intent intent)
{
    Schedule s = (Schedule) intent.getSerializableExtra("schedule");
}

但它总是返回,即使当我把 Extras 它不为空时,即使在传递它之前检查过myIntent.putExtra()我真的不知道会发生什么返回,为什么它总是返回 null?.. 有人知道这个问题吗?

4

2 回答 2

1

演员表是错误的,我会更容易传递序列化的字符串并进行反序列化。我正在使用这个类。

    public final class ObjectSerializer {

    private ObjectSerializer() {

    }

    public static String serialize(Serializable obj) throws IOException {
        if (obj == null)
            return "";
        try {
            ByteArrayOutputStream serialObj = new ByteArrayOutputStream();
            ObjectOutputStream objStream = new ObjectOutputStream(serialObj);
            objStream.writeObject(obj);
            objStream.close();
            return encodeBytes(serialObj.toByteArray());
        } catch (Exception e) {
            throw new IOException("Serialization error: " + e.getMessage(), e);
        }
    }

    public static Object deserialize(String str) throws IOException {
        if (str == null || str.length() == 0)
            return null;
        try {
            ByteArrayInputStream serialObj = new ByteArrayInputStream(
                    decodeBytes(str));
            ObjectInputStream objStream = new ObjectInputStream(serialObj);
            return objStream.readObject();
        } catch (Exception e) {
            throw new IOException("Serialization error: " + e.getMessage(), e);
        }
    }

    public static String encodeBytes(byte[] bytes) {
        StringBuffer strBuf = new StringBuffer();

        for (int i = 0; i < bytes.length; i++) {
            strBuf.append((char) (((bytes[i] >> 4) & 0xF) + ('a')));
            strBuf.append((char) (((bytes[i]) & 0xF) + ('a')));
        }

        return strBuf.toString();
    }

    public static byte[] decodeBytes(String str) {
        byte[] bytes = new byte[str.length() / 2];
        for (int i = 0; i < str.length(); i += 2) {
            char c = str.charAt(i);
            bytes[i / 2] = (byte) ((c - 'a') << 4);
            c = str.charAt(i + 1);
            bytes[i / 2] += (c - 'a');
        }
        return bytes;
    }

} 

之后像这样使用:

String scheduleSerialization = ObjectSerializer.serialize(schedule); 
myIntent.putExtra("schedule",scheduleSerialization);

最后要做的是:

public void  onRecieve(Context context, Intent intent)
{
    String serial =  intent.getStringExtra("schedule");
    if(serial!=null)
    Schedule s = (Schedule) ObjectSerializer.deserialize(serial) ;
}
于 2012-09-21T09:46:37.700 回答
0

不鼓励在 Android 上使用 Serializable,因为它很慢。如果您查看 android 源代码,您会看到

  • 通常将信息分解为多个键并将它们作为原始类型(整数、字符串等)发送
  • 当无法完成时,将使用 Parcelable 对象
于 2012-09-21T13:06:31.433 回答