所以我在这里有这个代码;
myIntent.putExtra("schedule",serializableClass);
并且这个意图转到了我的Broadcast Reciever,我确实可以将其序列化,如下所示,
public void onRecieve(Context context, Intent intent)
{
Schedule s = (Schedule) intent.getSerializableExtra("schedule");
}
但它总是返回,即使当我把Extras它不为空时,甚至在传递它myIntent.putExtra()
之前检查我真的不知道返回什么,为什么它总是返回null?..谁都知道这个问题?
答案 0 :(得分: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) ;
}
答案 1 :(得分:0)
不建议在Android上使用Serializable,因为它很慢。如果你查看android源代码,你会看到