Android:异常传递匿名类作为Intent参数

时间:2012-05-16 15:18:49

标签: java android serializable anonymous-class

例外:

java.lang.RuntimeException: Parcelable encountered IOException writing serializable object (name = MyClass$2)

(简化)代码:

i.putExtra("myparam", generateA(context, "foo"));
...
private A generateA(final Context context, String foo) {
    return new A() {

        @Override
        public void test() {
            System.out.println("test");
        }
    };
}

界面:

public interface A extends Serializable {

    public void test();

}

我做错了什么?我传递的是Serializable。

1 个答案:

答案 0 :(得分:0)

如果我理解得很好,意图失败是因为你的匿名类因其Handler而无法序列化?

是否可以在目标活动中实现处理程序? bahaviour类应该只包含具有目标活动提供的处理程序的行为函数:

private transient Handler h;

//Called by the activity in the onCreate
void setHandler(Handler h){
   this.h = h;
}

//Called by the activity to start the behaviour function
void startBehaviour (){
  //...
  //The activity handler will call startHandlerBehaviour itself
  h.sendMessage();
}

//Called by the activity in the Handler to execute in the good context
void startHandlerBehaviour() {
  //...
}