[英]Pass data between two Activities in different procceses
我需要在两个不同的过程之间传递Objects
,我阅读了有关它的所有材料,但仍然有一些疑问
1。我可以通过AIDL
在不同processes
之间传递对象,但是它复杂且混乱,我还阅读了有关Messenger
传输消息,但是我不能通过它传递实现这样的Parcelable
的Object
吗?
Bundle b = new Bundle();
b.putParcelable("MyObject", (Parcelable) object);
msg.setData(b);
handler.sendMessage(msg);
并在Handler
中提取它? 如果是的话,那么AIDL
与Messenger
有何进步?仅是多线程问题?
2。要跨不同的processes
工作,我可以使用Messenger
和AIDL
,但不能在没有所有这些服务(例如某些Android应用程序)的服务的情况下使用Bundle
in Activities
,这些服务可以获取对象作为输入:
intent.putExtra("MyParcelableObject", object);
首先在POJO类中实现java.io.Serializable接口,如下所示:
public class MyPojo implements Serializable {
}
其次,在您要传递对象的MainActivity中 ,编写如下代码:
Bundle bundle = new Bundle();
bundle.putSerializable("",""); // to hold list
bundle.putInt("",""); // to hold int
bundle.putString("", ""); // to hold String
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putExtra(bundle);
startActivity(intent);
最后,在SecondActivity中,您可以通过以下方式获取/读取数据
Bundle bundle = getIntent().getExtras();
ArrayList<MyPojo> arrayList= (ArrayList<MyPojo>) bundle.getSerializable("list");
int myPosition = bundle.getInt("position");
String strValue = bundle.getString("myString");
如果只想在驻留在两个不同进程中的组件之间传递数据,则可以使用与在两个活动之间共享对象所使用的语义相似的语义。例如,在以下过程中可能发生进程1中的活动与进程2中的服务之间的通信方式:
来自过程1中的活动
Intent mIntent = new Intent(this, MyService.class);
Bundle extras = mIntent.getExtras();
extras.putString(key, value);
startService(mIntent);
为流程2服务
public int onStartCommand (Intent intent, int flags, int startId)
{
super.onStartCommand(intent, flags, startId);
Bundle bundle = intent.getExtra();
}
同样,在共享对象时,请使用Parcelable而不是Serializable,因为它们更轻巧。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.