How to loop a service?

前端 未结 5 1204
深忆病人
深忆病人 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.

    0 讨论(0)
  • 2021-02-05 12:32

    Services run on the main thread. If you want to offload processing, you have to start a separate thread. Have a look at IntentService, it does this by default. On another note, having an infinitely running service with sleep() might not a good idea. For scheduled processing, you might want to use AlarmManager.

    0 讨论(0)
  • 2021-02-05 12:32

    As Janusz wrote, you can use handler to post delayed. Here is a sample:

    final Handler handler = new Handler();
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            // Do repeatable stuff
            handler.postDelayed(this, DELAYED_TIME);
        }
    };
    handler.post(runnable);
    

    It will post runnable and then post it again and again after DELAYED_TIME.

    0 讨论(0)
  • 2021-02-05 12:40

    create a thread in your service and put while loop there like this:

     new Thread(new Runnable(){
        public void run() {
        // TODO Auto-generated method stub
        while(true)
        {
           Thread.sleep(60000) 
           //REST OF CODE HERE//
        }
    
                        }
    }).start();
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题