Search code examples
javaandroidandroid-intentserializable

Android custom Intent class


I want to send a complex object from one Activity to another, so this complex object cannot be serialize, because some fields in this object are system classes and natively non-serializable. That's why I want to create my custom class named "MyIntent" inherits from android.content.Intent, with this way, I can put any type of objects in my custom Intent. But, in the second activity, getIntent() method returns android.content.Intent instance, not MyIntent instance. I don't understand why, maybe i did not implement android.content.Intent class correctly.

public class MyIntent extends Intent
{
}

//starting activity
MyIntent intent = new MyIntent();
intent.setClass(context, SecondActivity.class);
context.startActivity(intent);


//inside of onCreate() of SecondActivity
Intent i = getIntent();
i instanceof MyIntent = false

Solution

  • startActivity() involves inter-process communication, even when the activity you are starting is in the same app and the same process. Android will ignore your subclass, because the OS process that handles startActivity() requests cannot use your subclass, as that is in your app, and the OS process is not your app. And, the IPC that delivers the request to start the activity back to your process will not know anything about your subclass.

    Either:

    • Combine these into one activity (e.g., using two fragments), or

    • Use some sort of singleton data manager that both activities can work with