Android-Activity 构造函数与 onCreate

我知道 Android Activities有特定的生命周期,onCreate应该被覆盖并用于初始化,但是构造函数中究竟发生了什么?是否存在可以/应该覆盖 Activity构造函数的情况,或者应该永远不要碰它?

我假设构造函数不应该被使用,因为对 Activities的引用没有被完全清除(因此阻碍了垃圾收集器) ,而且 onDestroy就是为此而存在的。是这样吗?

54296 次浏览

You need to override the Constructor when your activity will have custom params or you want to track calls from classes that inherited from.

I can't think of any good reason to do anything in the constructor. You never construct an activity directly, so you can't use it to pass in parameters. Generally, just do things in onCreate.

I am now on a case that needs to override the constructor. In fact, I have some activities that have the same structure. So instead of creating many activities, I'll create one "Master" activity and the others will inherit this one. So I need to override the constructor of the child activity to be able to initialize some variables that will be used in the oncreate methods.

In two words, the constructor makes you simulate a "masteractivity" that can be reused by inheritance!

A good reason for putting things in the constructor as Gili's comment had stated is the use of final fields.

However, if you initialize things in the constructor, then the lifespan of the object will be a little bit longer, though I don't think by much because the onCreate would be called shortly thereafter.

Although it's against my ideal, I do avoid the constructor for initialization of the activity members and rely on onResume() and onPause() for resources that my app is dealing with.

For onCreate() I usually use it to do view mapping to local variables. Though android-annotations already does that for me so I rarely have an onCreate() method for my Activity. I still use it in Service though.

However, if you look at the members you may be initializing

  • they would have a "close" method that you have to invoke at the proper time (onResume or onPause)

  • they would be part of the view which means it needs to be initialized then onCreate needs to be called

  • they are constants which don't need to be put in the constructor anyway, just a static final would do. This includes Paint and Path constants which can be initialized by a static block