Android - running a method periodically using postDelayed() call

前端 未结 8 1419
一向
一向 2020-11-27 13:45

I have a situation in an Android app where I want to start a network activity (sending out some data) which should run every second. I achieve this as follows:

In th

8条回答
  •  清歌不尽
    2020-11-27 14:17

    Perhaps involve the activity's life-cycle methods to achieve this:

    Handler handler = new Handler();
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          handler.post(sendData);
    }
    
    @Override
    protected void onDestroy() {
          super.onDestroy();
          handler.removeCallbacks(sendData);
    }
    
    
    private final Runnable sendData = new Runnable(){
        public void run(){
            try {
                //prepare and send the data here..
    
    
                handler.postDelayed(this, 1000);    
            }
            catch (Exception e) {
                e.printStackTrace();
            }   
        }
    };
    

    In this approach, if you press back-key on your activity or call finish();, it will also stop the postDelayed callings.

提交回复
热议问题