getIntent() and subclass of Intent

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?


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.


You can use the copy constructor to convert your "abstract" Intent into a more concrete one. Therefore you would need to override the copy constructor of the Intent class and simply call super.

Say this is your intent:

public class StronglyTypedIntent extends Intent {
    private final static String ID = "verySecret";    

    public StronglyTypedIntent(final Activity initiator, final String someInformation) {
        super(initiator, SomeTargetActivity.class);
        putExtra(ID, someInformation);
    } 

    public StronglyTypedIntent(final Intent original) {
        super(original);
    }

    public String getSomeInformation() {
        return getStringExtra(ID)
    }
}

You could then initiate this intent from the "initiator activity" like this:

...

public void someLogicInTheInitiatingActivity() {
    startActivity(new StronglyTypedIntent(this, "some information"));
}
...    

In the "target activity" you could get the Intent like this:

...
public void someLogicInTheTargetActivity() {
    StronglyTypedIntent intent = new StronglyTypedIntent(getIntent());

    doSomethingWithTheInformation(intent.getSomeInformation());
}
...

Technically this seems to be a good way to abstract the details of data transfer through intents. However, it might be a performance problem to always copy the intent.

链接地址: http://www.djcxy.com/p/67900.html

上一篇: 将TreeMap从一个活动传递给另一个活动

下一篇: getIntent()和Intent的子类