如何为android.location类序列化?

use*_*494 5 java serialization android location deserialization

我正在尝试序列化我的位置类(使用android.location类)

但是,它给了我一个错误!

11-21 21:25:37.337: W/System.err(3152): java.io.NotSerializableException: android.location
Run Code Online (Sandbox Code Playgroud)

所以,我试图扩展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();
        }
    }
Run Code Online (Sandbox Code Playgroud)

之后,我试图序列化扩展类,但同样的错误.

这是序列化代码

 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;
    }
Run Code Online (Sandbox Code Playgroud)

为什么这个错误?

waq*_*lam 11

Android的Location类已经实现了 Parcelable.因此,您最好使用它而不是实现自己的序列化.

只需使用下列以获得bytes从出来Location:

Parcel p = Parcel.obtain();
objLocation.writeToParcel(p, 0);
final byte[] b = p.marshall();      //now you've got bytes
p.recycle();
Run Code Online (Sandbox Code Playgroud)

但是,您不应该从Parecelable对象中保存字节(在持久存储中)以供以后使用,因为它是为高性能IPC传输而设计的,并不是通用的序列化机制.