这里总结了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()函数