枚举广播意图:Parcelable遇到ClassClassNotFoundException,读取Serializable对象

时间:2018-01-10 11:51:52

标签: android enums

我用enum发送广播意图,然后onReceiver动作

 Intent intent = new Intent("com.coagent.intent.action.test")
 intent.putExtra("Key_state", KeyState.NONE);
 MainActivity.this.sendBroadcast(intent);

枚举如下:

 public static enum KeyState {
    NONE,
    DOWN,
    UP
}

然后其他应用程序onReceive广播,处理意图

  String EXTRA_KEY_STATE="Key_state";
  Serializable keyState = intent.getSerializableExtra(EXTRA_KEY_STATE);
    String ks = ((Enum) keyState).toString();
    LogUtils.i(TAG, "Wjc handerChangAnAction: ks=" + ks);
    if (null != ks && !ks.equals("NONE")) {
        return;
    }

但是在接收时会立即崩溃

FATAL EXCEPTION: main
Process: com.wjc.wecarnews, PID: 25775
java.lang.RuntimeException: Unable to start receiver 
com.wjc.wecarnews.system.PlayReceiver: java.lang.RuntimeException: 
Parcelable encounteredClassNotFoundException reading a Serializable object 
(name = com.rhr.wjc.demo.MainActivity$KeyState)
at android.app.ActivityThread.handleReceiver(ActivityThread.java:2414)
at android.app.ActivityThread.access$1700(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1272)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:805)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:621)
at dalvik.system.NativeStart.main(Native Method)

1 个答案:

答案 0 :(得分:-1)

建议不要将Enum值传递给Intentsee explanation here

或者,您可以执行以下操作:

当您发送Intent时:

 Intent intent = new Intent("com.coagent.intent.action.test")
 intent.putExtra("Key_state", KeyState.NONE.ordinal());
 MainActivity.this.sendBroadcast(intent);

当您收到Intent时:

int ordinal = intent.getIntExtra("Key_state",-1);
String ks = KeyState.values()[ordinal].toString();
LogUtils.i(TAG, "Wjc handerChangAnAction: ks=" + ks);
if (null != ks && !ks.equals("NONE")) {
   return;
}

P.S。在android中根本不推荐使用Enums read this article