Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getIntent() and subclass of Intent

Tags:

android

I wrote a class MyIntent which extends Intent. and then i use an instance of MyIntent to invoke startActivity(MyIntent).

MyIntent i=new MyIntent(this,NewActivity.class);

the constructor is:

public MyIntent(Context context,Class<?> cls){
super(context,cls);
putExtra(var1,var2);
//other codes
((Activity)context).startActivity(this);
}

however,when i call getIntent() in the new started activity the returned value of getIntent() is an Intent not MyIntent,that is

getIntent() instanceof Intent // true;
getIntent() instanceof MyIntent // false;

when i try (MyIntent)getIntent() the system throws me ClassCastException.How so?

like image 979
Fermat's Little Student Avatar asked Aug 07 '12 01:08

Fermat's Little Student


1 Answers

You can't do that, as Intent implements Parcelable and Cloneable interface, it's recreated when the intent object moves across processes. Hence it will be a different instance.

In the source code of ActivityManagerProxy, startActivity You will notice that intent will not be passed by reference, instead it is written into a Parcel to create a new object. So the created Intent object in previous Activity will no longer be referred.

like image 141
NcJie Avatar answered Nov 15 '22 08:11

NcJie