Search code examples
androidhandlerandroid-lifecycle

Where to call Handler Class's constructor in activity lifecycle


I'm a beginner to android, so sorry in advance for any mistakes.

So I have an activity in which I have a handler to execute a message. Now I don't know where should I call the constructor of this handler in the activity life cycle. Should it be in the activity's constructor or onCreate() or onInit(), which one would be most suitable. I have this handler's static object to be initialised so I guess it won't be suitable to call it in activity's constructor. Please help.


Solution

  • There is no method called onInit in Activity's life cycle and we do not use a constructor in Activity either .

    Activity is a component of android its object is initialize by OS itself whenever we call startActivity.

    Now for your answer you can initialize Handler inside #onCreate(). You can also use runOnUiThread for limited purpose. Try not to use static properties .

    class A extends AppCompatActivity{
        private Handler handler;
        @Override
        protected void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            //Other stuff
            handler=new Handler();
        }
    }