1

What is the best way to implement an android Service (not IntentService) which polls a device using SNMP at regular intervals? I've tried implementing it with a Handler.postDelayed(Runnable) within onHandleIntent of IntentService. But later found it cannot be used in onHandleIntent() from this answer. My code just would not execute the runnable part.

make an IntentService not sleep until it executes a handler.postDelayed runnable

My code goes like:

public class MyPoller extends IntentService {

    //Variable declarations 
    protected Handler handler;
    public MyPoller() {
            super("My service");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
            .......
            .......
            runable = new Runnable() { 
                public void run() {     
                    //My code here
                    handler.postDelayed(this, poll_interval);
                } 
            }; 
            handler.postDelayed(runable,poll_interval);
     }

}

So I thought I could implement the same in a service, but I don't know how to implement this recurring task in a service also running it in a new thread. I found few answers demonstrating different ways of running recurring tasks in a new thread in a Service, but I'm confused.

Can someone suggest some way of implementing the same in a Service? It would be of great help. Thanks in advance.

Community
  • 1
  • 1
  • 1
    Have you tried using `AlarmManager`? – matiash Jun 11 '14 at 18:13
  • Nope. But from what I read, many people said it was not as efficient as the Handler and since the app is to be run on a phone, I took performance issues into consideration and so I didn't try. – noobnarayanan Jun 11 '14 at 18:23
  • That is true, but there other considerations. For example, if your service is killed the handler and everything you posted on it will be lost, while the AlarmManager will restart the service. In short, this probably depends on your specific use case (i.e. the value of `poll_interval` and how many times it will run). – matiash Jun 11 '14 at 18:26
  • I would say alarm manager or you could try sending your start service intent to your service again at the end of your Runnable instead of sending the runnable to the handler. – Chris Feist Jun 11 '14 at 18:29
  • ok maybe i will try with alarm manager..but is that the efficient one? is there any other better solution? and matiash, the app will poll the device(to check if it's online) at an interval of 5sec, and will poll continuously. Only if the device is offline for some timeout, the polling would stop. – noobnarayanan Jun 11 '14 at 18:36

0 Answers0