Android - Activity constructor

前端 未结 4 858
执念已碎
执念已碎 2020-12-20 09:06

I noticed that using the shortcut Alt + Insert and selecting the builders, it tries to create a constructor with each private property (e.g. cManager

相关标签:
4条回答
  • 2020-12-20 09:15

    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.

    0 讨论(0)
  • 2020-12-20 09:16

    Your code should be in onCreate()

    Don't bother with a constructor for activities.

    0 讨论(0)
  • 2020-12-20 09:18

    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.

    0 讨论(0)
  • 2020-12-20 09:19

    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.

    0 讨论(0)
提交回复
热议问题