How to loop a service?

前端 未结 5 1226
深忆病人
深忆病人 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条回答
  •  旧时难觅i
    2021-02-05 12:43

    Each of lifecycle method of service is called from UI thread. If you need background task to be running all the time, you can crate new thread for this. This is actually very well described in documentation.

    In your case however, you should consider using AlarmManager instead. It handles recurring events very well and was specifically designed for similar scenarios.

    Another solution would be to use Handler and its postDelayed() function. This can be used when your operation (that should be executed every 60s) is not time-consuming (or otherwise you should still run it in background thread).

    Overall, creating a thread that sleeps all the time is not a good solution for mobile devices. This consumes resources that could've been spent for something more useful. Especially considering a rich set of capabilities of Android for recurring events.

提交回复
热议问题