我正在尝试序列化我的位置类(使用 android.location 类)
但是,它给了我一个错误!
11-21 21:25:37.337: W/System.err(3152): java.io.NotSerializableException: android.location
因此,我尝试扩展 android.location.Location
类。
private class NewLocation extends Location implements Serializable {
private String Provider;
private double Latitude, Longitude, Altitude;
private float bear;
public NewLocation(Location l) {
super(l);
Provider = l.getProvider();
Latitude = l.getLatitude();
Longitude = l.getLongitude();
Altitude = l.getAltitude();
bear = l.getBearing();
}
}
之后,我尝试序列化扩展类,但同样的错误。
这是序列化代码
public static byte[] serialize(Object obj) throws IOException {
ByteArrayOutputStream bao = new ByteArrayOutputStream();
ObjectOutput oos = new ObjectOutputStream(bao);
byte[] data = null;
oos.writeObject(obj);
oos.flush();
oos.close();
data = bao.toByteArray();
return data;
}
为什么会出现这个错误?
最佳答案
Android 的 Location
类已经实现 Parcelable
。所以你最好用它而不是实现你自己的序列化。
只需使用以下命令从 Location
中获取 bytes
:
Parcel p = Parcel.obtain();
objLocation.writeToParcel(p, 0);
final byte[] b = p.marshall(); //now you've got bytes
p.recycle();
但是,您不应该从 Parecelable
对象中保存字节(在持久存储中)供以后使用,因为它是为高性能 IPC 传输而设计的,而不是通用序列化机制。
关于java - 如何序列化 android.location 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20121159/