Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why cant we create an activity using new keyword?

why we have to launch an activity using intent

why cannot we launch it using Activity a = new Activity ??

i tried searching in android developers but did not get any answer

like image 795
Tushar Saha Avatar asked Dec 05 '25 18:12

Tushar Saha


2 Answers

You can, but it won't be fully initialized. There's a series of functions on the Activity that needs to be called in the right order to correctly initialize it, and a series of steps taken by the framework in order to display the activity. Calling startActivity will take those steps and call the Activity lifecycle functions in the correct order. So there's no reason to use new.

Looking at it another way- lets say you were to do Activity a = new Activity(). How would the OS know you did that, and know its supposed to display that Activity? How would it know that the Activity is now supposed to go into the foreground? It wouldn't. It needs to be told that a new Activity was launched. That's why startAcctivity exists. And since you have to call that anyway, why not just make it a factory method as well, so initialization and launching are one step?

like image 199
Gabe Sechan Avatar answered Dec 08 '25 10:12

Gabe Sechan


Not only you can create an activity object using the new keyword, but also you can inflate its layout/sub-views and then even launch it.

But the approach of implementing things above is very tedious and error-prone. And it is not recommended if you are dealing with normal Android app development.

If you are curious on how it is done, have a look at these github projects:

https://github.com/singwhatiwanna/dynamic-load-apk

https://github.com/didi/VirtualAPK

https://github.com/DroidPluginTeam/DroidPlugin

These projects aim to load and launch external Activities/Services from UNINSTALLED apk files. One tiny aspect of the way they implement this is by creating activities with new.

like image 30
Jiaqi Liu Avatar answered Dec 08 '25 09:12

Jiaqi Liu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!