Android开发------IPC机制之Bundle实现

来源:互联网 发布:淘宝青少年男装店排名 编辑:程序博客网 时间:2024/05/22 02:00

android前面介绍了Android的IPC机制,现在我们通过Bundle实现他的IPC机制,后面会相继介绍不同的跨进程通信方式

场景:手机上存在两个应用,现在需要通过应用A的Activity跳转到应用B的Activity中并传递数据,从而实现进程间通信

1.首先创建两个应用A,与应用B

应用A的Activity如下

 private Button button=null;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        initView();        button.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                Intent intent=new Intent();                Bundle bundle=new Bundle();                bundle.putString("key","我在跟你通信呢");                ComponentName componentName=new ComponentName("www.goldwind.cn.ipcbundlea","www.goldwind.cn.ipcbundlea.MainActivity");                intent.setComponent(componentName);                intent.putExtras(bundle);                startActivity(intent);            }        });    }    public void initView(){        button=(Button) findViewById(R.id.send);    }

我们通过创建Intent 在Intent中设置Component来实现两个应用间的Activity跳转,这里的intent.setComponent()方法中设置组件名称,ComponentName来确定组件ComponentName构造方法中传递参数两个参数,第一个包名,第二个包名下的类名(即要跳转的Activity的名称);注意:写完整的包名,然后通过Intent的putExtras方法携带Bundle对象传递数据过去,

2.应用B的Activity如下:

   private TextView textView=null;    private Button button=null;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);            initView();            Bundle bundle=getIntent().getExtras();           if(bundle!=null){                textView.setText(bundle.getString("key"));           }    }    public void initView(){        textView=(TextView)findViewById(R.id.shuju);        button=(Button)findViewById(R.id.send);    }

应用B通过getIntent().getExtras()获取传递过来的Bundle对象,我们通过Bundle 的getString()方法通过key获取传递的数据。并设置TextView的值。

3.界面截图A

以下是不同情况下的状态。

1.A启动后                                           2.B自己启动                                           3.通过A跳转启动B获取数据后改变状态                                   



0 0
原创粉丝点击