Android run thread in service every X seconds

后端 未结 4 1535
醉酒成梦
醉酒成梦 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:34

    Starting a runnable every few seconds is gonna have some lag no matter what way you slice it, no? I don't see why a Handler shouldn't work just fine.

    You might be experiencing some troubles though because you have

    void startRepeatingTask()
    {
        m_handlerTask.run(); 
    }
    

    Instead, you should use the Handler and do something like:

    void startRepeatingTask()
    {
        m_handler.post(m_handlerTask); 
    }
    

    (As an aside, the convention in Java is to use camel case, not snake case. So it should be mHandler, not m_handler, etc. Just telling you because it might make your code easier to read for some.)

提交回复
热议问题