How to Start an Intent from a contained class of a

2019-05-26 07:04发布

问题:

I'm looking for the best way to start an intent from a class that is not an Activity, but is a contained object of an Activity class.

For example the Activity Class:

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

and the class that I want to start the intent from:

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);
   }
}

What is the best way to do this architecturally? Should I pass MainActivity as a parameter to TestLauncher's constructor? Or is there a better way that I am not aware of?

回答1:

Class TestLauncher
{
   public TestLauncher (Context c)
   {
      Intent i = new Intent(c, YourActivity.class)
      c.startActivity(i);
   }
}

TestLauncher ts=new TestLauncher(getApplicationContext());