Singletons vs. Application Context in Android?

后端 未结 10 1320
醉话见心
醉话见心 2020-11-22 03:11

Recalling this post enumerating several problems of using singletons and having seen several examples of Android applications using singleton pattern, I wonder if it\'s a go

相关标签:
10条回答
  • 2020-11-22 03:26

    My activity calls finish() (which doesn't make it finish immediately, but will do eventually) and calls Google Street Viewer. When I debug it on Eclipse, my connection to the app breaks when Street Viewer is called, which I understand as the (whole) application being closed, supposedly to free up memory (as a single activity being finished shouldn't cause this behavior). Nevertheless, I'm able to save state in a Bundle via onSaveInstanceState() and restore it in the onCreate() method of the next activity in the stack. Either by using a static singleton or subclassing Application I face the application closing and losing state (unless I save it in a Bundle). So from my experience they are the same with regards to state preservation. I noticed that the connection is lost in Android 4.1.2 and 4.2.2 but not on 4.0.7 or 3.2.4, which in my understanding suggests that the memory recovery mechanism has changed at some point.

    0 讨论(0)
  • 2020-11-22 03:28

    They're actually the same. There's one difference I can see. With Application class you can initialize your variables in Application.onCreate() and destroy them in Application.onTerminate(). With singleton you have to rely VM initializing and destroying statics.

    0 讨论(0)
  • 2020-11-22 03:33

    From: Developer > reference - Application

    There is normally no need to subclass Application. In most situation, static singletons can provide the same functionality in a more modular way. If your singleton needs a global context (for example to register broadcast receivers), the function to retrieve it can be given a Context which internally uses Context.getApplicationContext() when first constructing the singleton.

    0 讨论(0)
  • 2020-11-22 03:42

    I had the same problem: Singleton or make a subclass android.os.Application?

    First I tried with the Singleton but my app at some point makes a call to the browser

    Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
    

    and the problem is that, if the handset doesn't have enough memory, most of your classes (even Singletons) are cleaned to get some memory so, when returning from the browser to my app, it crashed everytime.

    Solution: put needed data inside a subclass of Application class.

    0 讨论(0)
提交回复
热议问题