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

∥☆過路亽.° 提交于 2019-12-06 04:37:19

问题


Why are the lifeCycle methods in android have access specifiers as protected ?


what i understand about Access-specifiers is as below::


  • But why should we need to make all the life-cycle methods as protected
  • I notice this when i override the lifecycle methods
  • I know over-riding the methods of Activity class as methods in Activity class are defined protected
  • But why are they defined as protected


回答1:


  • 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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/20161662/why-are-lifecycle-methods-in-activity-class-defined-with-protected-access-specif

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