How to loop a service?

前端 未结 5 1218
深忆病人
深忆病人 2021-02-05 11:53

My service needs to check for something every minute and

while(true)
{
   Thread.sleep(60000) 
   //REST OF CODE HERE//
}

is not working. Makin

5条回答
  •  再見小時候
    2021-02-05 12:26

    A service itself is not a subthread. This means that every code that is run in your service will be run on the main UI Thread. You need to start a Thread, or use an AsyncTask in your service to move the computation to the background.

    Have a look at the documentation of service for more information.

    If you want to repeat some code every minute you can use a handler.

    A handler has a method called postDelayed this allows you to specify a time after which a runnable will be run. Just call the method again at the end of your runnable to rerun the code after a minute.

提交回复
热议问题