views:

89

answers:

3

I, i have a service and i want that once it started, it performs is work every 30 seconds. How can i do that?

Tnk Valerio

+1  A: 

You can use a Timer.

I also found an example of another class called Handler (that is available for Android) that apparently should work better when using the UI.

Patrick
+1  A: 

Handler usage example for your Service (Bind part of the Service is missing):

import android.app.Service;
import android.os.Handler;

public class PeriodicService extends Service {

private Handler mPeriodicEventHandler;

    private final int PERIODIC_EVENT_TIMEOUT = 30000;

    @Override
    public void onCreate() {
      super.onCreate();

      mPeriodicEventHandler = new Handler();
      mPeriodicEventHandler.postDelayed(doPeriodicTask, PERIODIC_EVENT_TIMEOUT);
    }

    private Runnable doPeriodicTask = new Runnable()
    {
        public void run() 
        {
            //your action here
            mPeriodicEventHandler.postDelayed(doPeriodicTask, PERIODIC_EVENT_TIMEOUT);
        }
    };

    @Override
    public void onDestroy() {

        mPeriodicEventHandler.removeCallbacks(doPeriodicTask);      
        super.onDestroy();
    }
}
Desiderio