我想将一个Handler对象包装起来,将Bundle从一个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);
然后,在Service onStartCommandMetehod中,我执行以下操作:
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);
MyHandler类如下:
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();
}
}
服务接收自定义处理程序,但从来没有,并且从类Handler调用sendMessage方法,但是Activity永远不会收到消息...
对于MyHandler类,我基本上使用了android developer site中的代码并添加了Handler继承以及构造函数。
有什么不对?
提前致谢!