I want to parcelable a Handler object to send it by a Bundle from one Activity to a service in order to get some info from this service.
Right now, to test it it's a simple message. Here's the code in the Activity:
private MyHandler mHandlerSharing = new MyHandler() {
public void handleMessage(Message msg) {
// this line in the Activity is never reached when debugging
String data = msg.getData().getString("data");
Toast.makeText(mContext, data, Toast.LENGTH_SHORT).show();
}
};
// in some function
mSecureSharing.putExtra(Constants.HANDLER, (Parcelable) mHandlerSharing);
Then, in the Service onStartCommandMetehod I do the following:
MyHandler myHandler = (MyHandler) intent.getExtras().getParcelable(Constants.HANDLER);
Message msgObj = myHandler.obtainMessage();
Bundle b = new Bundle();
b.putString("data", "SecureSharing running");
msgObj.setData(b);
myHandler.sendMessage(msgObj);
The class MyHandler is the following:
import android.os.Handler;
import android.os.Parcel;
import android.os.Parcelable;
public class MyHandler extends Handler implements Parcelable{
private int mData;
public MyHandler(){
super();
}
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel out, int flags) {
out.writeInt(mData);
}
public static final Parcelable.Creator<MyHandler> CREATOR = new Parcelable.Creator<MyHandler>() {
public MyHandler createFromParcel(Parcel in) {
return new MyHandler(in);
}
public MyHandler[] newArray(int size) {
return new MyHandler[size];
}
};
private MyHandler(Parcel in) {
mData = in.readInt();
}
}
The service receives the custom handler but never but and call sendMessage method from the class Handler, but the Activity never receives the message...
For MyHandler class, I basically used the code from the android developer site and add the Handler inheritance as well as a constructor.
What can be wrong?
Thanks in advance!