【问题标题】:How to Start an Intent from a contained class of an Activity如何从包含的 Activity 类启动 Intent
【发布时间】:2011-06-13 22:25:27
【问题描述】:

我正在寻找从不是 Activity 而是 Activity 类的包含对象的类中启动 Intent 的最佳方式。

例如Activity类:

Class MainActivity extends ListActivty
{
...
TestLauncher tester;
}

以及我想从哪个类开始意图:

Class TestLauncher
{
   public TestLauncher ()
   {
      //Code to create an intent needs a Context
      //Intent i = new Intent(Context, class)

      //Code to start activity needs to be called with an Activity
      //Activity.StartActivity(i);
   }
}

在架构上做到这一点的最佳方法是什么?我应该将MainActivity 作为参数传递给TestLauncher 的构造函数吗?还是有我不知道的更好方法?

【问题讨论】:

  • @J J:“我应该将 MainActivity 作为参数传递给 TestLauncher 的构造函数吗?” - 是的,或者只是将this 作为一次性传递给TestLauncher 中用于启动活动的任何方法。

标签: android android-intent android-activity android-context


【解决方案1】:
Class TestLauncher
{
   public TestLauncher (Context c)
   {
      Intent i = new Intent(c, YourActivity.class)
      c.startActivity(i);
   }
}

TestLauncher ts=new TestLauncher(getApplicationContext());

【讨论】:

  • 不要使用getApplicationContext()。只需通过this(作为活动上下文)。使用 getApplicationContext() 可能会导致意外行为。
  • 无法传递 Activity 上下文导致内存泄漏?
  • 嗯,棘手的一个。是的,在某些情况下,传递 Activity 上下文可能会导致泄漏,但在 OP 的问题中,内部类被用于简单地启动另一个活动,它只是用于此目的。好点 - 我收回我所说的,使用应用程序上下文可能是有效的,但我倾向于不使用它,除非我特别需要它。
  • 很好,我不知道 getApplicationContext()。感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-07-20
  • 1970-01-01
  • 2011-05-16
  • 1970-01-01
  • 1970-01-01
  • 2017-06-21
相关资源
最近更新 更多