java - 将对象从服务发送到 Activity (无法编码非 Parcelable)

标签 java android runtimeexception

我正在尝试将我的 Activity 数据发送到服务并接收一些返回信息,但我得到:

java.lang.RuntimeException: Can't marshal non-Parcelable objects across processes.

Activity 中的代码如下所示:

Message msg = Message.obtain(null, 1);
    msg.obj=1;
    msg.replyTo=new Messenger(new PlanRequestIncomingHandler());
    try {
        msgService.send(msg);
    } catch (RemoteException e) {
        Log.i(tag, "Can not send msg to service");
        e.printStackTrace();
    }

当我设置 msg.obj = something 时,我得到 java.lang.RuntimeException,有人可以帮助我吗?

最佳答案

你可以通过Parcelable通过 Messenger 键入对象。或者如果你想通过 primitive data types使用 Bundle包装如下。

在服务端:

//Create a bundle object and put your data in it
Bundle bundle = new Bundle();
bundle.putInt("key", 1);

Message msg = Message.obtain(null, 123);
msg.obj = bundle;
msg.replyTo = new Messenger(new PlanRequestIncomingHandler());
try {
    msgService.send(msg);
} catch (RemoteException e) {
    Log.i(tag, "Can't send msg to service");
    e.printStackTrace();
}

在 Activity 结束时:

switch(msg.what) {
    case 123:
        if(msg.obj != null) {
            Bundle bundle = (Bundle) msg.obj;
            System.out.println("Got integer "+ bundle.getInt("key"));
        }
    break;
}

干杯:-)

关于java - 将对象从服务发送到 Activity (无法编码非 Parcelable),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6596291/

相关文章:

java - 使用 Java Stream 条件映射到新对象

java - Loop and half VS Repeat-until-sentinel 习惯用法

android - 卡片 View 之间的距离太大

android - 使用 robolectric 进行单元测试会出现 NoSuchMethodException 错误

java - 尽管我得到了结果,为什么我会收到此错误?

Java:如何为 double 值设置精度?

java - GridBagLayout 中组件的大小不正确

android - android 中的警报对话框

android - 如何通过代码在Android中检索调用转移状态?

android - 自定义 session 保存