GetIntent () and a subclass of Intent

I wrote a class MyIntent that extends Intent. and then I use an instance of MyIntent to call the startActivity (MyIntent) function.

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

constructor:

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

however, when I call getIntent () in a new running action, the return value of getIntent () is Intent not MyIntent, i.e.

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

when I try (MyIntent) getIntent (), the system throws me a ClassCastException. How?

+5
source share
2 answers

You cannot do this because Intent implements the interface Parcelableand Cloneable, it is recreated when the intent object moves through the processes. Therefore, this will be another example.

ActivityManagerProxy, startActivity , , . , Intent .

+5

"" . Intent super.

, :

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)
    }
}

" " :

...

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

" " Intent :

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

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

, , . , , .

+4

All Articles