Execute function after 5 seconds in Android

后端 未结 9 1010
既然无缘
既然无缘 2020-12-13 12:39

I am new in android development and now my launcher activity show only 5 seconds and after that I want to check the user is logged in or not function and perform the actions

9条回答
  •  情歌与酒
    2020-12-13 13:28

    When possible, try to avoid using postDelayed. It is a bad practice, since it can lose the reference to the objects that you want to draw on your screen and cause a NPE. Use a Handler instead. First of all, create a global variable Handler in which you will have to "handle" the logic for your code. Do so by using the function handleMessage.

    Handler  handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if(msg.what == 1){
                // your code here
            }
        }
    };       
    

    Then, wherever you want to execute it, just call the function:

    // 1 is the ID of your process
    handler.sendEmptyMessageDelayed(1, 5000);
    

    Please remember that in the onDestroyView method (in a Fragment) or the onDestroy (in an Activity) you will have to call

        handler.removeMessages(1)
    

提交回复
热议问题