gpt4 book ai didi

Android: onRecieve 的 Intent getSerializableExtra(String key) 返回 null

转载 作者:行者123 更新时间:2023-11-30 04:00:53 24 4
gpt4 key购买 nike

所以我这里有这段代码;

myIntent.putExtra("schedule",serializableClass);

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

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

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

最佳答案

转换是错误的,我会更容易传递序列化字符串并进行反序列化。我正在使用这个类(class)。

    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) ;
}

关于Android: onRecieve 的 Intent getSerializableExtra(String key) 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12527889/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com