4

Most of the time, when designing an desktop application, I love to make the main application as singleton for convenient purpose. I can easily access the application's data and methods, without having to pass the main application reference all over around.

public class MainFrame extends javax.swing.JFrame {
    // Private constructor is sufficient to suppress unauthorized calls to the constructor
    private MainFrame()
    {
    }

    /**
     * MainFrameHolder is loaded on the first execution of Singleton.getInstance()
     * or the first access to MainFrameHolder.INSTANCE, not before.
     */
    private static class MainFrameHolder {
        private final static MainFrame INSTANCE = new MainFrame();
    }

    /**
     * Returns MainFrame as singleton.
     * 
     * @return MainFrame as singleton
     */
    public static MainFrame getInstance() {
        return MainFrameHolder.INSTANCE;
    }
}

However, from Android platform point of view, I am no longer sure whether it is correct/safe to do so, as I have no direct control over the creation of MainActivity. The MainActivity I am going to have are

  • Launch mode will be standard.
  • The only time, when the instance of MainActivity will be created is when user taps on application icon. Means, the only way to launch is being specified in AndroidManifest.xml's <application> tag. There shouldn't be any other Java code's within MainActivity.apk, to launch MainActivity itself.

public class MainActivity extends Activity {
    public static MainActivity INSTANCE = null;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        assert(INSTANCE == null);
        INSTANCE = this;
    }
}
Cheok Yan Cheng
  • 47,586
  • 132
  • 466
  • 875

1 Answers1

6

If the reason you want to do that is because you have some initialization code that should only run once when the application is first launched, or to store shared data for your entire app, the onCreate() method of a subclass of Application might be a better place, because Android guarantees that only one of those will exist per application. See this link for an explanation on how to do that.

Community
  • 1
  • 1
Jeshurun
  • 22,940
  • 6
  • 79
  • 92
  • Thanks for the link. I also find a quite useful information from the following link : http://stackoverflow.com/questions/2002288/static-way-to-get-context-on-android – Cheok Yan Cheng Jun 24 '12 at 18:52