Why are lifecycle methods in activity class defined with protected access specifier

房东的猫 提交于 2019-12-04 09:46:34
Sam
  • They are protected for encapsulation within the framework package android.app and subclasses.
  • They are to be called by android.app.ActivityManager (same package) only. Depending on the method implementation, things could get messed up, if one can call those methods arbitrarily, from anywhere.

So, this is by design and that design helps to avoid certain conceptual errors. If you really must have a public method, just implement one and use it from outside and within the corresponding lifecycle method.
However, though not recommended in this case, one could override protected methods with public methods.

i am defining here why public and protected and how it work:

It's useful to have public onClick methods because you can "force" certain buttons to be clicked programmatically. A common example of this is causing the same to code to execute when the user presses the enter key, or pressed the Submit button.

I don't think Android calls Activity.onCreate directly. Note that Activity inherits from Context (which does have a public constructor). It is my understanding that the constructor triggers some events to occur, and the onCreate/Pause/Resume/Destroy methods are called internally to the class at the appropriate time.

For example, when you create an activity, the view XML file has to be parsed and inflated. This happens automatically, so there's something happening behind the scenes that you don't directly control.

Not public because those lifecycle methods are essentially used internally by the SDK and are not meant to be called by any other classes (you are not supposed to call anywhere activity.onResume() from any class, this is done automatically).

Not private to allow some custom code to be ran by subclasses.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!