Android - Activity constructor

﹥>﹥吖頭↗ 提交于 2019-11-29 12:55:38
Y.S

All of your initializations should be performed in the onCreate() method of your Activity:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.cManager = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
    this.mTextView = (TextView)this.findViewById(R.id.mProgressText);
}

Overriding the constructor of Activity involves quite a bit of heavy lifting, and is really not a walk in the park. Although you can [of course] have an empty constructor for an Activity, it really is quite superfluous in the context of the Android framework.

Related answers:

1. Why I cannot pass parameters to Android Activity Constructor.

2. Start an Activity with a parameter.

Blaisorblade

Android activities can have constructors as long as they take zero arguments. And in fact there is such a constructor as soon as you initialize any field when declaring it.

But as your log says, System services not available to Activities before onCreate(), so you can't call getSystemService from the constructor.

So the code in https://stackoverflow.com/a/28636652/53974 is correct, but the reason isn't.

Your code should be in onCreate()

Don't bother with a constructor for activities.

Android activity allows only class default constructor is allowed. i.e. constructor with zero parameters. In default constructor you can do initializations to those final variables except which are linked system services as only available after lifecycle onCreate method.

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