2012-07-15 9 views
6

Provare a utilizzare un Timer per eseguire questa operazione 4 volte con intervalli di 10 secondi ciascuno.Come arrestare un timer dopo un determinato numero di volte

Ho provato a fermarlo con un ciclo, ma continua a bloccarsi. Ho provato a utilizzare lo schedule() con tre parametri, ma non sapevo dove implementare una variabile contatore. Qualche idea?

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(); 
} 

risposta

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

Grazie, questa risposta ha reso più senso – jimmyC

+2

Nessun problema. Quindi contrassegnalo come la risposta corretta :) – Y2i

2

Perché non utilizzare un AsyncTask e solo esso Thread.sleep (10000) e la publishProgress in un ciclo while? Ecco che cosa sarebbe simile:

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(); 

anche come nota a margine, per le operazioni ripetitive più lungo termine, è possibile utilizzare 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); 

} 
Problemi correlati