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

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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值