Run my code in background every 1 sec effectively in Android

I have to run a bit of code in the background every one second, the code will call a webservice which searches a database and returns a value to the application. My question is which method would be the most effective to do this? I have read up on Timers, Threads, AsyncTask and Services and each seem to have their pros and cons. Please can someone tell me which would be the best to use considering execution time and battery life.

Thanks

Update: I decided to use Aysnc task to run my code in the background while using a TimeTask to trigger the AsyncTask at regular intervals. This way the operation is destroyed when I leave that particular activity

Answers


You will have to create a new Thread so that the call don't lock up the device if the call takes longer than expected. The AsyncTask is an easy way to use multithreading, but it lacks the functionality of repeating tasks. I would say that you are best of either using a Timer or the newer ScheduledExecutorService. If you chose to use the Timer you create a TimerTask that you can hand it. The ScheduledExecutorService takes a Runnable instead.

You might want to wrap the thread in a Service (The Service does not provide a new Thread), but this is not always necessary depending on your needs.

As suggested in comment, you can also use the Handler.postDelayed(). Although you still need to create a new thread and then call Looper.prepare() on it:

  class LooperThread extends Thread {
      public Handler mHandler;

      public void run() {
          Looper.prepare();

          mHandler = new Handler() {
              public void handleMessage(Message msg) {
                  // process incoming messages here
              }
          };

          Looper.loop();
      }
  }

(Code from Looper docs)

Also; calls to a webservice every second seems way too frequent, especially if the user is on a slow connection or there are data that needs to be transferred, try to reduce the calls as much as possible.


You should use the service to do the background operation but in your case you want to run code in 1 sec here is the example of service using handler it call in every 1 sec.

public class YourService extends Service {
private static final String TAG = "Your Service";
private final Handler handler = new Handler(){
    @Override
    public void handleMessage(Message msg) {

}
};
@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public void onCreate() {
//  Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
    Log.d(TAG, "onCreate");

}

@Override
public void onDestroy() {
    super.onDestroy();
//  Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
    handler.removeCallbacks(sendUpdatesToUI);   
}
 private Runnable sendUpdatesToUI = new Runnable() {
        public void run() {
            /// Any thing you want to do put the code here like web service procees it will run in ever 1 second
            handler.postDelayed(this, 1000); // 1 seconds
        }
 };
@Override
public void onStart(Intent intent, int startid) {

    handler.removeCallbacks(sendUpdatesToUI);
    handler.postDelayed(sendUpdatesToUI, 1000);//1 second       
    Log.d(TAG, "onStart");
}

}

and service can't run every time android idle the service within 3 or 4 hr i suggested you to use the foreground service to use your process long running.


For operations like this I tend to use a Service component. for the task itself i use an AsyncTask which will wait a set time before it repeats itself (using a while loop).


I think it's not only one solution, so it's up to you. You can try start thread with this run method:

private final int spleeptime = 1000;
public boolean running;

@Override
public void run() {
    while (running) {
        try {
            int waited = 0;
            while ((waited < spleeptime)) {
                sleep(100);
                waited += 100;
            }
        } catch (InterruptedException e) {
        } finally {
            // your code here
        }
    }
}

Need Your Help

Jsonix-schema-compiler cannot convert .xsd file to JSON Object

json xml xsd jsonix

I converted a few .xsd files to a JSON Object with the jsonix-schema-compiler, but there is one .xsd with qualified namespaces.

Failed to load map using google map android api v2

android google-maps xamarin

I got this following error when loading google map android api v2