Home > Enterprise >  onCreate method in Android studio
onCreate method in Android studio

Time:12-14

I have started learning Android development recently and have some doubts. " What invokes onCreate method to get called automatically when we create new project or create a new activity ? And how is it getting called"

I tried to search it. But not getting the proper answer

CodePudding user response:

I don't know if there's a specific spot in the documentation that explains this clearly, so I can't really cite sources. This is just what I've picked up over time working in Android and looking at source code.

The Android OS is responsible for launching Activities. An Activity is found and launched through an Intent. It could be internally done in your own app. Or if it is the entry point to your app, it could be launched by the home screen launcher app of the device. Or in debugging mode, the OS can be commanded to launch a specific activity (this is what happens when your Run your app from Android Studio).

An Activity must have an empty constructor (a constructor with no arguments) so the OS can create an instance of your Activity using reflection. Since the OS cannot know of all possible Activity classes ahead of time, it must use reflection to find the constructor and call it.

After it has an instance of your Activity, the OS manages its lifecycle. It will call lifecycle functions like onCreate() at the appropriate times in its life. onCreate() is the first time in your Activity's life where you can do Activity- or Context-specific work safely. So, there are restrictions in what you can do in property initializers and init blocks, since these are called before onCreate().

You must never call your Activity's constructor or its lifecycle functions directly yourself. These are reserved for use by the OS.

  • Related