在不同进程中的两个活动之间传递数据

时间:2014-08-12 04:56:02

标签: java android android-service aidl

我需要在两个不同的流程之间传递Objects,我阅读了有关它的所有材料,但我仍然有一些问题

1 。我可以在不同的processesAIDL之间传递对象,但是它复杂而混乱,我也读到了他Messenger

传输邮件,但我不能传递一个Object来实现Parcelable吗?

Bundle b = new Bundle();
b.putParcelable("MyObject", (Parcelable) object);
msg.setData(b);

handler.sendMessage(msg);

并在Handler中提取它?如果是,那么AIDL超过Messenger的进展是什么...只有多线程问题?

2 。我可以使用processesMessenger来处理不同的AIDL,但我无法在Bundle中使用Activities没有所有像今天的Android应用程序那样的服务可以将对象作为输入:

intent.putExtra("MyParcelableObject", object);

2 个答案:

答案 0 :(得分:1)

首先在 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 :(得分:0)

如果您只想在驻留在两个不同进程中的组件之间传递数据,则可以使用与用于在两个活动之间共享对象的语义类似的语义。例如,将进程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,因为它们更轻量级。

相关问题