android_Activity系列 activity的传递

来源:互联网 发布:matlab如何读取usb数据 编辑:程序博客网 时间:2024/04/29 04:14

用Intent传递

启动另外一个 Activity

Activity.startActivity()方法可以根据传入的参数启动另外一个 Activity:

 Intent intent =new Intent(CurrentActivity.this,OtherActivity.class);  startActivity(intent); 

当然,OtherActivity同样需要在 AndroidManifest.xml 中定义。

Activity 之间通信
使用 Intent 通信

在 Android 中,不同的 Activity 实例可能运行在一个进程中,也可能运行在不同的进程中。因此我们需要一种特别的机制帮助我们在 Activity 之间传递消息。Android 中通过 Intent 对象来表示一条消息,一个 Intent 对象不仅包含有这个消息的目的地,还可以包含消息的内容,这好比一封 Email,其中不仅应该包含收件地址,还可以包含具体的内容。对于一个 Intent 对象,消息“目的地”是必须的,而内容则是可选项。

在上面的实例中通过 Activity. startActivity(intent)启动另外一个 Activity 的时候,我们在 Intent 类的构造器中指定了“收件人地址”。

如果我们想要给“收件人”Activity 说点什么的话,那么可以通过下面这封“e-mail”来将我们消息传递出去:

 Intent intent =new Intent(CurrentActivity.this,OtherActivity.class);  // 创建一个带“收件人地址”的 email  Bundle bundle =new Bundle();// 创建 email 内容 bundle.putBoolean("boolean_key", true);// 编写内容 bundle.putString("string_key", "string_value");  intent.putExtra("key", bundle);// 封装 email  startActivity(intent);// 启动新的 Activity 

那么“收件人”该如何收信呢?在 OtherActivity类的 onCreate()或者其它任何地方使用下面的代码就可以打开这封“e-mail”阅读其中的信息:

 Intent intent =getIntent();// 收取 email  Bundle bundle =intent.getBundleExtra("key");// 打开 email  bundle.getBoolean("boolean_key");// 读取内容 bundle.getString("string_key"); 

上面我们通过 bundle对象来传递信息,bundle维护了一个 HashMap<String, Object>对象,将我们的数据存贮在这个 HashMap 中来进行传递。但是像上面这样的代码稍显复杂,因为 Intent 内部为我们准备好了一个 bundle,所以我们也可以使用这种更为简便的方法:

 Intent intent =new Intent(EX06.this,OtherActivity.class);  intent.putExtra("boolean_key", true);  intent.putExtra("string_key", "string_value");  startActivity(intent); 

接收:

 Intent intent=getIntent();  intent.getBooleanExtra("boolean_key",false);  intent.getStringExtra("string_key"); 

使用 SharedPreferences

SharedPreferences 使用 xml 格式为 Android 应用提供一种永久的数据存贮方式。对于一个 Android 应用,它存贮在文件系统的/data/ data/your_app_package_name/shared_prefs/目录下,可以被处在同一个应用中的所有 Activity 访问。Android 提供了相关的 API 来处理这些数据而不需要程序员直接操作这些文件或者考虑数据同步问题。

 // 写入 SharedPreferences  SharedPreferences preferences = getSharedPreferences("name", MODE_PRIVATE);  Editor editor = preferences.edit();  editor.putBoolean("boolean_key", true);  editor.putString("string_key", "string_value");  editor.commit();          // 读取 SharedPreferences  SharedPreferences preferences = getSharedPreferences("name", MODE_PRIVATE);  preferences.getBoolean("boolean_key", false);  preferences.getString("string_key", "default_value"); 

其它方式

Android 提供了包括 SharedPreferences 在内的很多种数据存贮方式,比如 SQLite,文件等,程序员可以通过这些 API 实现 Activity 之间的数据交换。如果必要,我们还可以使用 IPC 方式。