samuelabate
samuelabate

Reputation: 1631

Extending the Application class in android twice

Is it okay or possible to extend the Application class in android twice and have two childs of it in an application? And also why do we need it & what's the purpose of extending it?

Upvotes: 1

Views: 196

Answers (3)

dipdipdip
dipdipdip

Reputation: 2556

You want something like this?

MyApp extends Application
MySecondApp extends MyApp

This is possible. There are several usecases for this. For example define an Application for your App but override it for a specific build type or product flavor (e.g. debug). Or a custom Application for your (Android) Tests:

MyApp extends Application
MyDebugApp extends MyApp
MyTestApp extends MyApp/MyDebugApp

Define each Application Class in the according AndroidManifest:

MyApp => main package
MyDebugApp => debug package
MyTestApp => androidTest package

Upvotes: 1

CommonsWare
CommonsWare

Reputation: 1006634

Is it okay or possible to extend the Application class in android twice and have two childs of it in an application?

You can only have one registered Application subclass in the android:name attribute of the <application> element. You are welcome to create as many subclasses of Application as you want, but only one will be used. However, you are welcome to have MyApp extend Application, have MyOtherApp extend MyApp, and register MyOtherApp in the manifest.

And also why do we need it

Few apps need it. Quoting the documentation, "There is normally no need to subclass Application".

what's the purpose of extending it?

If you have application logic that needs to be executed every time Android forks a process for you, Application is a common place to trigger that logic. For example, most crash logging libraries (e.g., ACRA) have you configure them in an Application subclass, so that they can handle crashes from everywhere else in your app, for every one of your processes.

Upvotes: 1

Glen Pierce
Glen Pierce

Reputation: 4801

Yes, it's possible. The reason extend classes is to reuse code written in the parent class and extend its functionality.

Upvotes: 0

Related Questions