两个选项:使用或Parcelable
Serializable
在:
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("handles", new FileHandles(handles));
外:
FileHandles handles = intent.getParcelableExtra("handles");
对象:
import android.os.Parcel;
import android.os.Parcelable;
import java.util.ArrayList;
import java.util.List;
public class FileHandles implements Parcelable {
private final List<Long> fileHandles;
public FileHandles(List<Long> fileHandles) {
this.fileHandles = fileHandles;
}
public FileHandles(Parcel in) {
int size = in.readInt();
long[] parcelFileHandles = new long[size];
in.readLongArray(parcelFileHandles);
this.fileHandles = toObjects(size, parcelFileHandles);
}
private List<Long> toObjects(int size, long[] parcelFileHandles) {
List<Long> primitiveConv = new ArrayList<Long>();
for (int i = 0; i < size; i++) {
primitiveConv.add(parcelFileHandles[i]);
}
return primitiveConv;
}
public List<Long> asList() { // Prefer you didn't use this method & added domain login here, but stackoverflow can only teach so much..
return fileHandles;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(fileHandles.size());
dest.writeLongArray(toPrimitives(fileHandles));
}
private static long[] toPrimitives(List<Long> list) {
return toPrimitives(list.toArray(new Long[list.size()]));
}
public static long[] toPrimitives(Long... objects) {
long[] primitives = new long[objects.length];
for (int i = 0; i < objects.length; i++)
primitives[i] = objects[i];
return primitives;
}
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
@Override
public FileHandles createFromParcel(Parcel in) {
return new FileHandles(in);
}
@Override
public FileHandles[] newArray(int size) {
return new FileHandles[size];
}
};
}
可序列化(强制使用哪个实现( 不)ArrayList
Serializable
List
在:
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("handles", new ArrayList<Long>());
外:
ArrayList handles = (ArrayList) intent.getSerializableExtra("handles");