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 withinMainActivity.apk
, to launchMainActivity
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;
}
}