Android run thread en service de toutes les X secondes

Je veux créer un thread dans un Android service qui s'exécute toutes les X secondes

Je suis en train d'utiliser , mais le postdelayed méthode semble vraiment à la traîne mon application.

@Override
public int onStartCommand(Intent intent, int flags, int startId){

    super.onStartCommand(intent, flags, startId);

    startRepeatingTask();

    return startId;
}

private final static int INTERVAL = 20000; //20 milliseconds
Handler m_handler = new Handler();

Runnable m_handlerTask = new Runnable()
{
     @Override 
     public void run() {
         //this is bad
          m_handler.postDelayed(m_handlerTask, INTERVAL);
     }
};

void startRepeatingTask()
{
    m_handlerTask.run(); 
}

void stopRepeatingTask()
{
   m_handler.removeCallbacks(m_handlerTask);
   stopSelf();
}

Je veux faire un nouveau thread comme celui-ci:

public void threadRun()
{
    Thread triggerService = new Thread(new Runnable(){
        public void run(){
            Looper.prepare();
            try{
                    //do stuff here?

            }catch(Exception ex){
                    System.out.println("Exception in triggerService Thread -- "+ex);
            }//end catch


        }//end run
    }, "aThread");
    triggerService.start();      

    //perhaps do stuff here with a timer?
    timer1=new Timer();

    timer1.scheduleAtFixedRate(new methodTODOSTUFF(), 0, INTERVAL);
}

Je ne suis pas sûr de la meilleure façon de faire un thread d'arrière-plan à exécuter à un certain intervalle, la perspicacité apprécié!

OriginalL'auteur CQM | 2011-11-22