Is it safe for me to consider an action as a singleton

In most cases, when developing a desktop application, I like to make the main application as a singleton for convenience. I can easily access application data and methods without having to pass the main link to the application.

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 the point of view of the Android platform, I am not sure if this is / is safe to do, since I do not have direct control over the creation of MainActivity . MainActivity I will have

  • Startup mode will be standard .
  • The only time an instance of MainActivity is created is when the user clicks the application icon. So, the only way to launch it is indicated in the AndroidManifest.xml <application> . There MainActivity.apk not be any other Java code in MainActivity to run 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; } } 
+4
source share
1 answer

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

+6
source

All Articles