0

i have this IntentService code which run a service once:

protected void onHandleIntent(Intent intent) {
    final ResultReceiver receiver = intent.getParcelableExtra("receiver");
    String command = intent.getStringExtra("command");
    Bundle b = new Bundle();
    b.putString("results", results);
    if(command.equals("query")) {
        receiver.send(1, Bundle.EMPTY);
        try {                   
            results = sendGetMessage();
            b.putString("results", results);
            receiver.send(2, b);
        } catch(Exception e) {
            b.putString(Intent.EXTRA_TEXT, e.toString());
            receiver.send(0, b);
        }    
    }
    this.stopSelf();
    Log.d("ServiceFinished", "ServerConnection.java Service has finished");
}

i want my sendGetMessage() function to run repeatedly every 5 seconds until i stop the service.. how can i do it ?

Asaf Nevo
  • 11,338
  • 23
  • 79
  • 154

2 Answers2

3

You would want to put it in its own Thread and loop it forever.

Thread thread = new Thread()
{
    @Override
    public void run() {
        try {
            while(true) {
                Thread.sleep(5000); // for the 5 seconds requirement
                results = sendGetMessage();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
};

thread.start();
ajacian81
  • 7,419
  • 9
  • 51
  • 64
  • This is also a bad solution: the system can choose to kill your thread eventually... – Kristopher Micinski Mar 22 '12 at 00:35
  • @AsafNevo, I added a line that will let it run every 5 seconds. – ajacian81 Mar 22 '12 at 09:26
  • @ajacian81 can you please help me implement the code you've written in the code i've written ? – Asaf Nevo Mar 22 '12 at 16:42
  • This still absolutely kills battery life, which will have users screaming away from your app and force closing it like crazy... – Kristopher Micinski Mar 22 '12 at 17:47
  • @Kristopher Micinski i thought about it and you're right, i will change the interval of server connection to about 30 seconds.. and it sends and receives a really short package so the connection won't be more then few seconds depending on the internet speed – Asaf Nevo Mar 22 '12 at 18:00
  • Good. Few apps need any kind of responsiveness to this granularity (and most of those shouldn't be on mobile devices anyway). Thirty seconds should be fine, and using a background service on an alarmservice can prefetch data for you to keep things up to date when a user updates an app anyway. – Kristopher Micinski Mar 22 '12 at 18:16
0

There are many alternatives but I prefer to use ScheduledExecutorService. See sample code below:

ScheduledExecutorService scheduleTaskExecutor = Executors.newScheduledThreadPool(1);

// This schedule a task to run every 5 seconds:
scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
  public void run() {
    // Do the actual job:
    results = sendGetMessage();

    // In case if you need update UI, simply do this:
    runOnUiThread(new Runnable() {
      public void run() {
        // update your UI component here.
        myTextView.setText("refreshed");
      }
    }); // end of runOnUiThread
  }
}, 0, 5, TimeUnit.SECONDS);

Remember to finish/close your runnable task properly before stop your service.

yorkw
  • 40,926
  • 10
  • 117
  • 130