android - 通过某种方式通过 Intent 启动 Activity 有什么好处?

标签 android android-intent android-activity

我知道有两种方法可以启动带有 Intent 的 Activity 。假设我在 Activity A 中,我想启动 Activity B。我可以执行以下操作。

1) 在 Activity B 中,我有一些静态方法:

public static Intent newIntent(Context packageContext){
    Intent intent = new Intent(packageContext, ActivityB.class);
    return intent;
}

我可以从 Activity A 调用:

startActivity(ActivityB.newIntent(this));

2)另一种方法是我比较常看到的:

我在 Activity A 中执行以下操作

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

使用一种与另一种相比有什么好处或缺点吗?我认为方法 1 更简洁一些,因为它将 Intent 信息保存在实际将以 Intent 启动的类中。

最佳答案

案例优先

优点:

  • 这遵循 DRY原则意味着不要重复你自己

缺点:

  • 它仅限于一个类,即 ActivityB.class

  • Utility 类的命名约定不明确

  • 注意灵活添加额外的属性,除非方法定义被修改为接受一些 map或者什么的

第二种情况

优点:

  • 更灵活,因为可以开始任何 Activity

  • 任何属性都可以添加到intent对象 i.g putExtra还有很多其他的

缺点:

  • 不遵循DRY原则

  • 多次重复时效率低下

改进

  • 给你的方法适当的命名
  • 可以重载以接受键值映射
  • 申请 Class<?>接受任何类作为参数

关于android - 通过某种方式通过 Intent 启动 Activity 有什么好处?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44988676/

相关文章:

java.lang.IllegalArgumentException : 'value' is not a valid managed object with realm 异常

java - 字符串数组传递给另一个 Activity - android studio

java - 元素 eElement = (元素) nNode;应用程序崩溃

android - 将边距设置为抽屉导航中的菜单项,但不设置标题部分

android - 避免在 Android 中注册重复的广播接收器

java - 通过 Intent 传递 list<String[]>

Android:监听 Activity onDestroy()

android - 如何从 Android Activity 访问 SyncResult

android - GMail for KitKat 在发送不是图像或视频的附件时崩溃

android - 如何下载文件并存入sdcard?