2012-07-15 22 views
6

Intentando utilizar un Timer para ejecutarlo 4 veces con intervalos de 10 segundos cada uno.Cómo detener un temporizador después de cierto número de veces

He intentado detenerlo con un bucle, pero sigue estrellándose. He intentado usar el schedule() con tres parámetros, pero no sabía dónde implementar una variable de contador. ¿Algunas ideas?

final Handler handler = new Handler(); 
Timer timer2 = new Timer(); 

TimerTask testing = new TimerTask() { 
    public void run() { 
     handler.post(new Runnable() { 
      public void run() { 
       Toast.makeText(MainActivity.this, "test", 
        Toast.LENGTH_SHORT).show(); 

      } 
     }); 
    } 
}; 

int DELAY = 10000; 
for (int i = 0; i != 2 ;i++) { 
    timer2.schedule(testing, DELAY); 
    timer2.cancel(); 
    timer2.purge(); 
} 

Respuesta

12
private final static int DELAY = 10000; 
private final Handler handler = new Handler(); 
private final Timer timer = new Timer(); 
private final TimerTask task = new TimerTask() { 
    private int counter = 0; 
    public void run() { 
     handler.post(new Runnable() { 
      public void run() { 
       Toast.makeText(MainActivity.this, "test", Toast.LENGTH_SHORT).show(); 
      } 
     }); 
     if(++counter == 4) { 
      timer.cancel(); 
     } 
    } 
}; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    timer.schedule(task, DELAY, DELAY); 
} 
+0

Gracias, esta respuesta tiene más sentido – jimmyC

+2

No hay problema. Entonces márcalo como la respuesta correcta :) – Y2i

2

Por qué no utilizar un AsyncTask y sólo tiene que Thread.sleep (10000) y el publishProgress en un bucle while? Esto es lo que se vería así:

new AsyncTask<Void, Void, Void>() { 

     @Override 
     protected Void doInBackground(Void... params) { 

      int i = 0; 
      while(i < 4) { 
       Thread.sleep(10000); 
       //Publish because onProgressUpdate runs on the UIThread 
       publishProgress(); 
       i++; 
      } 

      // TODO Auto-generated method stub 
      return null; 
     } 
     @Override 
     protected void onProgressUpdate(Void... values) { 
      super.onProgressUpdate(values); 
      //This is run on the UIThread and will actually Toast... Or update a View if you need it to! 
      Toast.makeText(MainActivity.this, "test", Toast.LENGTH_SHORT).show(); 
     } 

    }.execute(); 

También como una nota al margen, para tareas repetitivas más largo plazo, considerar el uso de AlarmManager ...

1
for(int i = 0 ;i<4 ; i++){ 
    Runnable runnableforadd ; 
    Handler handlerforadd ; 
    handlerforadd = new Handler(); 
    runnableforadd = new Runnable() { 
     @Override 
     public void run() { 
      //Your Code Here 
      handlerforadd.postDelayed(runnableforadd, 10000);       } 
    }; 
    handlerforadd.postDelayed(runnableforadd, i); 

} 
Cuestiones relacionadas