Mak
Mak

Reputation: 1111

Prevent multiple instantiation of an activity

Is it possible to make an activity singleton? I have found many resources that just tell to use android:launchMode="singleInstance" or singleTask, but I would constructor to be called only once.

Ideally, I would like to be able to specify custom constructor/builder method e.g. getInstance()

Upvotes: 0

Views: 75

Answers (2)

Eugen Pechanec
Eugen Pechanec

Reputation: 38223

You could store your references in Application instead of an Activity. The application class is de facto a singleton. You only need to define your access methods.

public class BaseApplication extends Application {

  private static BaseApplication sInstance = null;

  public synchronized static BaseApplication getInstance() {
    return sInstance;
  }

  public synchronized static void setInstance(BaseApplication app) {
    sInstance = app;
  }

  public BaseApplication() {
  }

  @Override
  public void onCreate() {
    super.onCreate();
    setInstance(this);
}

Now you can access it by calling BaseApplication.getInstance(). As a bonus the Application extends Context so now you have an application context reference anywhere you want (safe to use pretty much everywhere except inflating layouts).

Don't forget to define this class as the base application class in your manifest:

<application
    android:name="com.yourapp.BaseApplication">

Upvotes: 2

Alexander
Alexander

Reputation: 48252

Usually they do as follows:

1) define what comprise the Activity state

2) Save the state in onSaveInstanceState

3) Restore the state in onCreate or in onRestoreInstanceState

Upvotes: 1

Related Questions