2

If I do something like this:

public class MyApp extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        //init something else here if you want
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
        //terminate something else here if you want
    }

}

And include the name of this class in the Manifest file like this:

<application
        android:name="com.packagename.MyApp"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

Is this effectively giving us a way to run whatever code we want before and after the app runs?

Edit: If I step into the onCreate() statement I see this in the code:

/**
     * Called when the application is starting, before any activity, service,
     * or receiver objects (excluding content providers) have been created.
     * Implementations should be as quick as possible (for example using 
     * lazy initialization of state) since the time spent in this function
     * directly impacts the performance of starting the first activity,
     * service, or receiver in a process.
     * If you override this method, be sure to call super.onCreate().
     */
    @CallSuper
    public void onCreate() {
    }

    /**
     * This method is for use in emulated process environments.  It will
     * never be called on a production Android device, where processes are
     * removed by simply killing them; no user code (including this callback)
     * is executed when doing so.
     */
    @CallSuper
    public void onTerminate() {
    }

Edit 2: I could also save the application context as a global static variable:

public class MyApp extends Application {
    private static Context context;

    @Override
    public void onCreate() {
        super.onCreate();
        MyApp.context = getApplicationContext();
    }

    public static Context getAppContext() {
        return MyApp.context;
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
    }
}
Sufian
  • 5,997
  • 14
  • 60
  • 111

2 Answers2

2

Not before and after but in whole Application lifecycle, e.g. all running Activitys, Services and other contextual creatures... if none of them is currently visible/running Android system may always remove your Application from memory (user also).

If you are looking for a way to run some code outside screen/without any UI, check out Service class or other delayed alarm-basing method.

You can't depend on subclassing Application class because you don't even know when it is killed by OS "automatically".

Sufian
  • 5,997
  • 14
  • 60
  • 111
snachmsm
  • 10,975
  • 1
  • 22
  • 52
  • Are you saying that Application is just as exposed to being removed as something like an Activity? – The 29th Saltshaker Aug 17 '16 at 20:24
  • I also found this: http://stackoverflow.com/a/3780156/4967485 "At what time the application object will be cleared from memory is not very well documented but I think that if your app is in the background and memory is rare the OS may destroy your whole app and therefore also removing the application object from memory." – The 29th Saltshaker Aug 17 '16 at 20:26
  • 1
    @The29thSaltshaker: "Are you saying that Application is just as exposed to being removed as something like an Activity? " -- processes do not live forever. When your process terminates, the `Application` (and all other objects) go away. However, while the process is running, the `Application` will not be removed. – CommonsWare Aug 17 '16 at 20:32
  • @CommonsWare Is there any difference between instantiating a singleton (or any other static instance) from the Application class' onCreate method vs. from an Activity? – The 29th Saltshaker Aug 17 '16 at 20:34
  • 1
    @The29thSaltshaker: There may be entry points into your app that are not activities (services, receivers, providers). Now, you can still always use a `getInstance()` sort of lazy singleton initializer to handle arbitrary entry points. For an app (not a library), in many places, it is as much a stylistic choice as anything, IMHO. – CommonsWare Aug 17 '16 at 20:39
  • @CommonsWare I added an example to my post. Does this not imply I can do `MyApp.getAppContext()` to get the application context from anywhere in the app, which is something I would otherwise be unable to do unless I explicitly set it from an Activity using something like `this.getApplicationContext` first? – The 29th Saltshaker Aug 17 '16 at 20:52
  • I am also unsure if there is a risk to this, if something like a service or content provider or whatever "gets to the context first" somehow and does something to it such that when I try to save the application context in that onCreate statement, it gets null (for example) – The 29th Saltshaker Aug 17 '16 at 20:53
  • 1
    @The29thSaltshaker: "Does this not imply I can do `MyApp.getAppContext()` to get the application context from anywhere in the app" -- yes. I don't like the approach, as too many developers use the wrong `Context` for a particular job, and this makes it that much easier to screw up. But, I am not aware of anything directly wrong with what you have there. – CommonsWare Aug 17 '16 at 20:56
  • 1
    @The29thSaltshaker what are you trying to achieve exactly? There might be better ways for what you're looking for. So tell us what is it. – Sufian Aug 17 '16 at 21:15
1

Yes. The main reason of having it extend Application class

  • Is to have all initialization that you want to be singletons throughout the app and used in components.
  • Have some static variables to be used across components

Ref: Logic why we should use

sumandas
  • 519
  • 5
  • 18
  • Is the Application class the only way to instantiate singletons / static instances safely? – The 29th Saltshaker Aug 17 '16 at 20:32
  • @The29thSaltshaker : I think you are referring in reference to your Database instance being singleton. As far as I have used the SQLHelper extended classes, opening and closing would make it lock automatically. Application extended classes helps to have Singleton that needs access at multiple places and are to be done prior to activity start.Example a user loads some values from sqllite and that is common to all it's user for demo purpose then sure. But if you want data specific to user or user query declaring here won't help you much. – sumandas Aug 17 '16 at 20:37
  • heads up, the is down and redirecting to malware it seems like – Joe Pinsonault Jul 29 '18 at 23:06