Android run thread in service every X seconds

后端 未结 4 1533
醉酒成梦
醉酒成梦 2020-12-05 01:11

I want to create a thread in an Android service that runs every X seconds

I am currently using , but the postdelayed method seems to really lag out my app.

4条回答
  •  既然无缘
    2020-12-05 01:45

    Here is how I run a repeating thread, as you'll see it loops every 1 second. I see no lag with this method.

    final Thread t = new Thread(new RepeatingThread());
    t.start();
    

    And the class:

    import android.os.Handler;
    
    public class RepeatingThread implements Runnable {
    
        private final Handler mHandler = new Handler();
    
        public RepeatingThread() {
    
        }
    
        @Override
        public void run() { 
            mHandler.postDelayed(this, 1000);       
        }
    }
    

提交回复
热议问题