简体   繁体   中英

Android: How to start an activity from a non-activity class using a single instance

I have a Java class (not activity) and I want to start a new activity from it. I am getting the context of the app on its initialisation and then I m using it to start a new activity as shown below. Although, the code ONLY works if I add the following piece of code intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); which is not what I want as I only want to have a single instance of each activity. How can I do the same but instead of creating a new activity getting the one already created? My code is:

public class Foo {
  ...
  protected Foo(Context context) {
    applicationContext = context;
  }

  private void onButtonClick(){
    Intent intent = new Intent(applicationContext, Bar.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //doesnt work without that line
    applicationContext.startActivity(intent);
  }
}

In that case you need to use Activity context to start new Activity. You should modify you class like below

public class Foo {
  ...
  protected Foo(Activity activityContext) {
    this.activityContext= activityContext;
  }

  private void onButtonClick(){
    Intent intent = new Intent(activityContext, Bar.class);
    activityContext.startActivity(intent);
  }
}

But here you code is not clearing the idea, where you are using this class. Because you made this method as private.

Intent.FLAG_ACTIVITY_SINGLE_TOP

使用它可以帮助

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM