这不完全是使用共享偏好的答案,但认为它可能会有所帮助
序列化一个对象并传递它:
我使用下面的代码,然后编写一个包含任何变量而不是不可靠的共享首选项的类。
public class SharedVariables {
public static <S extends Serializable> void writeObject(
final Context context, String key, S serializableObject) {
ObjectOutputStream objectOut = null;
try {
FileOutputStream fileOut = context.getApplicationContext().openFileOutput(key, Activity.MODE_PRIVATE);
objectOut = new ObjectOutputStream(fileOut);
objectOut.writeObject(serializableObject);
fileOut.getFD().sync();
} catch (IOException e) {
Log.e("SharedVariable", e.getMessage(), e);
} finally {
if (objectOut != null) {
try {
objectOut.close();
} catch (IOException e) {
Log.e("SharedVariable", e.getMessage(), e);
}
}
}
}
public static <S extends Serializable> S readObject(
final Context context, String key, Class<S> serializableClass) {
ObjectInputStream objectIn = null;
try {
FileInputStream fileIn = context.getApplicationContext().openFileInput(key);
objectIn = new ObjectInputStream(fileIn);
final Object object = objectIn.readObject();
return serializableClass.cast(object);
} catch (IOException e) {
Log.e("SharedVariable", e.getMessage(), e);
} catch (ClassNotFoundException e) {
Log.e("SharedVariable", e.getMessage(), e);
} finally {
if (objectIn != null) {
try {
objectIn.close();
} catch (IOException e) {
Log.e("SharedVariable", e.getMessage(), e);
}
}
}
return null;
}}
然后示例类:
public class Timestamps implements Serializable {
private float timestampServer;
public float getTimestampServer() {
return timestampServer;
}
public void setTimestampServer(float timestampServer) {
this.timestampServer = timestampServer;
}
}
然后在活动中:
SharedVariables.writeObject(getApplicationContext(), "Timestamps", timestampsData);