Why Android Developers Should Forget the Word Singleton
Android apps typically run in a single process, sharing memory and system resources. However, Android gives developers the flexibility to run individual components — such as Activities, Services, or BroadcastReceivers — in separate processes. The Android system does not guarantee that a Singleton written in an app will truly be the only one.
This is why Singleton is not a programming pattern or anti-pattern. It is pure evil. Especially in Android development. If a developer is asked to name patterns he knows during an interview, and he names Singleton first, then the interview can end there. Seriously.
And in this article I will tell you why.
Let's imagine we have a Singleton.
object Singleton
Will there be the same instance of Singleton object in Activity and IntentService or Service?
Answer – NO.
Because for each Android component the system can create its own process. And for IntentService a separate process is allocated by default.
In addition, the Application class will be recreated. In some cases, Application will create a new instance of the Application class. In some cases, the onCreate method will be called multiple times.
You can check this by playing with the android:process setting in the Manifest file.
Let's sum it up:
never use Singleton in your application;
Be prepared for the fact that the Application class may have multiple instances;
the onCreate method can be called multiple times.