Reputation: 860
I have a class that extends ResultReceiver. When I start my main activity, on the onCreate method, I call an IntentService to fetch some data from the internet.
Since I need the service to pass Movie objects to the main activity, I need to instantiate the ResultReceiver in the activity and pass it to the service.
final class MovieResultReceiver extends ResultReceiver {
private static final String MOVIE_ARRAY = "movie array";
private static final int RESULT_SUCCESS= 101000;
private ResultProcessor mProcessor;
MovieResultReceiver(Handler handler) {
super(handler);
}
interface ResultProcessor {
void onReceiveResult(int resultCode, Bundle resultData);
}
void setReceiver(ResultProcessor resultProcessor) {
mProcessor = resultProcessor;
}
@Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
if (mProcessor != null) {
mProcessor.onReceiveResult(resultCode, resultData);
}
}
void notifyReceiver(Bundle bundle, Parcelable[] parcelables) {
bundle.putParcelableArray(MOVIE_ARRAY,parcelables);
send(RESULT_SUCCESS,bundle);
}
private MovieResultReceiver(Parcel in) {
super(new Handler());
}
static final Creator<MovieResultReceiver> CREATOR = new Creator<MovieResultReceiver>() {
@Override
public MovieResultReceiver createFromParcel(Parcel source) {
return new MovieResultReceiver(source);
}
@Override
public MovieResultReceiver[] newArray(int size) {
return new MovieResultReceiver[0];
}
};
@Override
public void writeToParcel(Parcel dest, int flags) {
// I need to pass a reference to MainActivity,
// so I need to write it to the parcel somehow
}
}
The ResultProcessor member variable will be set to my Main Activity, because it will use the data that the service will fetch.
My question is:
How can I maintain a reference to the main activity when I pass the ResultReceiver as an intent extra?
What do I need to "write to parcel"?
Upvotes: 1
Views: 671
Reputation: 3908
You can't do this and it is right because Parcel
is time independent object - it can be restored even after an Activity
is recreated, so the reference to it will change.
You can pass a reference to the Main Activity via Application
object or some static field. That field will be initialized in activity's onCreate
and used while reading data from parcel.
Upvotes: 1