Pass interface between activities in intent - interface fails to be Serializable or Parcelable
You cannot "pass an interface". An "interface" is an abstract thing. What you want to pass is a concrete implementation of that interface, ie: an object (that happens to implement your interface). When you instantiate your "interface" (in your example, like this:
intent.putExtra("testInterface", new ITest() {
@Override
void onSuccess(String text) {
}
}
you are actually creating an instance of an anonymous class that implements the interface ITest
. To pass this in an Intent
you would need to make this class also implement Parcelable
or Serializable
.
However, even if you did that, it would not solve your problem. What you need to understand is that you can't pass objects (instances) by putting them as "extras" in an Intent
. When you do that, Android actually serializes and then deserializes the object so that you end up with 2 objects, one is a serialized/deserialized copy of the original.
If you want ActivityB
to communicate with ActivityA
, you will need to use another technique. Try one of these:
ActivityB
sends a broadcastIntent
, whichActivityA
listens forActivityA
startsActivityB
usingstartActivityForResult()
andActivityB
sends data back toActivityA
usingsetResult()
- Use
public static
(ie: global) variables to communicate - Store data in shared preferences, or a file, or a database
What you really need to understand is that, under certain conditions, the following can occur:
- your app is running with
ActivityA
in the stack andActivityB
on the top of the stack - user presses HOME
- Android moves your task to the background and eventually kills the hosting process
- User returns to your app (by starting it again or selecting it from "recent task" list
- Android creates a new process for your app, and instantiates
ActivityB
, then callsonCreate()
,onStart()
andonResume()
ofActivityB
.
In this case, there is no instance of ActivityA
anymore. That instance is dead. So ActivityB
cannot communicate with ActivityA
because it no longer exists.