How can Android source code not have a main method and still run?

MGoBlue93 picture MGoBlue93 · Nov 19, 2010 · Viewed 15.3k times · Source

I've seen this in a few tutorials now... but how in the world can Android source code not have a main method and still run.

For example (from http://developer.android.com/guide/tutorials/hello-world.html):

public class HelloAndroid extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
}

That runs but there is no main!!!

I've also thought that using things like onCreate (or formLoad, etc.) was bad becuase a constructor should do that work and such built-in methods can be smelly sometimes. But onCreate is an entry point? Even without a main?

What if there is more than one activity... is there a hierarchy to these built in event handlers? OnCreate trumps everything else? Otherwise, how would the app know what to run or where to enter the program?

Thanks!

Answer

user1903788 picture user1903788 · Dec 14, 2012

Each application will be having it's own Virtual Machine. To run an app, within it's space (VM), must have a main method.

Activities are not the actual classes to be invoked for start of application. There is a class called Application, which will be the root class for an application to be launched.

If there is no main method, how can a VM recognize how to start an app?

Framework has classes called Process, VMRuntime which are responsible for starting an application. Which indeed deal with main method.

For better understanding, study the Zygote service of Android. deals with Applicationmanager Service, ActivityStack Activity Threadds etc.