gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:01:43 34 4
gpt4 key购买 nike

我正在尝试将我的 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/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com