Android - running a method periodically using postDelayed() call

前端 未结 8 1329
一向
一向 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:27
    final Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
          @Override
          public void run() {
            //Do something after 100ms
            Toast.makeText(c, "check", Toast.LENGTH_SHORT).show();  
            handler.postDelayed(this, 2000);
          }
        }, 1500);
    
    0 讨论(0)
  • 2020-11-27 14:42

    Please check the below its working on my side in below code your handler will run after every 1 Second when you are on same activity

     HandlerThread handlerThread = new HandlerThread("HandlerThread");
                    handlerThread.start();
                    handler = new Handler(handlerThread.getLooper());
                    runnable = new Runnable()
                    {
                        @Override
                        public void run()
                        {
    
                                handler.postDelayed(this, 1000);
                            }
                    };
                    handler.postDelayed(runnable, 1000);
    
    0 讨论(0)
提交回复
热议问题