-4

Why do we extend application class. Android apps run properly even without extending it.

Can anyone explain this scenario as why exactly do we extend it.

For Example:

public class MyApp extends Application {

    private static MyApp app;
    private ImageDownloaderComponent imageDownloaderComponent;

    @Override
    public void onCreate() {
        super.onCreate();
        app = this;
        imageDownloaderComponent = DaggerImageDownloaderComponent.builder().imageDownloaderModule(new ImageDownloaderModule(this)).build();
    }

}
Ümañg ßürmån
  • 9,695
  • 4
  • 24
  • 41
  • 1
    Because it's the only singleton global instance of Context that can be freely used in most cases around the app (except alert dialogs, anything involving inflation of support v4 widgets, and starting activities) – EpicPandaForce Aug 20 '18 at 19:55
  • Possible duplicate of [Why to extend an Application class?](https://stackoverflow.com/questions/18002227/why-to-extend-an-application-class) – Bernhard Barker Sep 12 '18 at 15:55

1 Answers1

7

Android apps run properly even without extending it.

Android apps can run properly without extending it. They can run properly without extending Activity. You extend Application when it does something useful for you.

Can anyone explain this scenario as why exactly do we extend it.

It is used for per-process initialization that should always happen, not just for certain activities or other components.

So, for example, you might initialize:

  • Dependency injection (e.g., Dagger)
  • Crash logging (e.g., ACRA)
  • Diagnostic tools (e.g., LeakCanary, Stetho, Sonar)
  • Global pools (e.g., OkHttpClient)

Ideally, you initialize as little as possible, simply because this initialization is performed on the main application thread every time your process is forked. But, it is often convenient for things that should be set up before any of your application logic is executed.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491