Android 多个Activity间对象共享

这里总结了Android中几种对象共享的方式,便于以后查阅。


一,基于消息的通信机制  Intent : Boudle   Extra

这种方式比较常见,有很多的介绍,主要通过 Intent类型,将要传递的数据与一个key绑定,在另一Activity中通过key进行取值。但此方式的问题是可以传递 (共享)的 数据类型有限,比如遇到不可序列化的数据Bitmap,InputStream, 或者LinkList链表等等数据类型就不太好用。有时候不得已需要自己去实现序列化的接口。它比较适用于传递一些简单类型的值。


在SendActivity中定义的函数:

	private void ExecIntentTransfer()
	{
		String strValue = m_teValue.getText().toString();
		
		if ((strValue == "") || (strValue.length() == 0))
			return;
		
		Intent intent = new Intent();  
        intent.setClassName( getApplicationContext(), "com.example.activitysharedata.ActivitySharewithIntent" );  

        Bundle b = new Bundle();   
        b.putString("key", strValue);  
          
        intent.putExtras( b );    
        startActivity(intent);  
  
        System.exit(0);
	}


在接收函数中定义的函数:

public class ActivitySharewithIntent  extends Activity  
{
	private TextView m_tvValue;
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_intent);
		
		m_tvValue =  (TextView)findViewById(R.id.tvValue);
		String strValue = getIntent().getExtras().getString("key");
		
		m_tvValue.setText(strValue);
	}
}

其中,接收端用到的key和发送端的要保持一致。



二,利用static静态数据, public static成员变量

这种方式使用简单,缺点是使用了静态全局变量,对于多线程或有多个模块修改其值的时候,会有一定的风险。它可以传递任意类型的变量。


发送端的程序,其实就是向全局变量赋值。 注意这里要用 this.finish()函数,而不能使用System.exit()函数࿰

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值