java - Activity 内/Activity 间通信

标签 java android android-intent android-activity

我主要是android开发的初学者,我发现自己使用很多全局变量来在同一 Activity 内的函数之间共享数据,即 Activity 内通信。这主要是因为没有人从 Activity 中调用 onCreate (),因此我无法返回可能在 Activity 中后期编辑的 UI 元素和数据。

除了 Activity 间通信之外,我发现自己使用 Intent extras 来处理小数据,并使用带有静态变量的外部类来在 Activity 终止时传递大数据、图像字符串。我读过here应用程序上下文也可以用于维护全局变量,所以这可能是一个解决方案,但是这使得 Activity 内通信的变量即使在它死后也保持 Activity 状态,这是不必要的。此外,所有 Activity 可能并不总是需要传递的某些数据。

这似乎是不好的做法,所以我的问题:

1)For inter-activity communication is a constant use of intent extras and static variables to pass data ok?

2) For Intra-activity communication what can I use instead of global variables to pass data between different functions that don't call each other but share some value and the value dies with the activity ? Is there a danger to such use of global variables ?

如果这太固执己见或太抽象,我会关闭它。

最佳答案

1) 使用 Intent 是可以的。至于全局变量我不这么认为。当 Android 系统决定释放一些内存后重新创建应用程序时,这些值可能会丢失。为什么不在 SharedPreferences 或 SQLite 中保存数据?

2) 字段(和类)变量是一种正常的使用方式(对于不始终使用 findViewById 等情况来说,这是很好的做法)。如果您想在 Activity 重新创建之间保留数据,为什么不使用 Android 框架( https://developer.android.com/training/basics/activity-lifecycle/recreating.html )提供的数据?

将所需的数据(如项目 ID、值等)保存在 bundle 中,然后恢复它们。

public void onSaveInstanceState(Bundle savedInstanceState) {
    savedInstance.putInt(some_key,value);
}

并在onCreateonRestoreInstanceState中恢复。

关于java - Activity 内/Activity 间通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34640958/

相关文章:

java - Android 错误登录 Twitter 失败,无法获取请求 token

android - 如何在 Android 上使用外部麦克风?

java - 无法合并Dex

android - 构造函数 Intent(new View.OnClickListener(){}, Class<DrinksTwitter>) 未定义

java - 我的 Android Scrollview 在 tabhost 中消耗了太多内存

java - 在 Java 中使用 "super"和 "?"

java - java中如何添加和删除表

android - 是否可以为 textview 的复合绘图提供状态?

android - 启动 Intent 以在 Android 中将应用程序启动到后台

android - 如何在 android 中使用 intent 传递 parcelable 变量值?