Below is the example of my Parcelable class. As you can see, I want to put activity in a Parcel
, but how could I do that? I look into the source code of Activity
, it is not Parcelable
nor Serializable
.
public class MyParcelable implements Parcelable {
private Activity mActivity;
private int mData;
private String mName;
@Override
public void writeToParcel(Parcel out, int flags) {
//out.writeX(mActivity);
out.writeInt(mData);
out.writeString(mName);
}
private MyParcelable(Parcel in) {
//mActivity = in.readX();
mData = in.readInt();
mName = in.readString();
}
public MyParcelable(Activity activity, int data, String name) {
mActivity = activity;
mData = data;
mName = name;
}
@Override
public int describeContents() {
return 0;
}
public static final Parcelable.Creator<MyParcelable> CREATOR
= new Parcelable.Creator<MyParcelable>() {
@Override
public MyParcelable createFromParcel(Parcel in) {
return new MyParcelable(in);
}
@Override
public MyParcelable[] newArray(int size) {
return new MyParcelable[size];
}
};
}
You can put anything in Parcel and take anything out of Parcel. But whether that "anything" will work afterwards will depend on variety of factors.
All Activity instances exist in close cooperation with Android's ActivityManager. Most of methods, that define Activity: startActivity()
, finish()
, restart()
, setContentView()
, getPackage()
delegate to methods of ActivityManager, ViewManager, PackageManager, and other system services. These methods won't work after Activity is destroyed by system. Those methods also won't work if you instantiate Activity class without Android's "special sauce". While it is technically possible to instantiate an Activity class using reflection or JNI, those instances simple won't work.
This is what people mean, when they say that Activity is "managed by Android": it is basically driven by OS processes, and can not exist without communication with those processes. Fortunately, Android has a way to initiate such communication: an Intent
. Replace this line:
private Activity mActivity;
with
private Intent mActivity;
And use the parcelized Intent to start the Activity once you receive it on other side. Of course, if you need more things than just Intent to get your Activity in usable shape, you will have to store those things alongside with Intent within your Parcelable.