2013-05-09 6 views
0

Je suis confus au sujet de l'ajout d'un minuteur dans ce cas. Je veux envoyer "mService.sendAlert (mDevice, str2)" chaque minute quand "button_Timer" est cliqué.Ajout d'une minuterie dans Android

public void onClick(View v) { 
    switch (v.getId()) { 


    case R.id.button_Timer: 
     Log.e("MainActivity", "Clicked"); 
     if (mService != null) 

     { 
      str2 = Ef.getText().toString(); 
      str2 = str2.substring(0, 0) + "E" + str2.substring(0, str2.length()); 
      mService.sendAlert(mDevice, str2); 
     } 
     break; 

    default: 
     Log.e(TAG,"wrong Click event"); 
     break; 
    } 
} 

Merci à l'avance

Répondre

0

View et donc Button a une méthode appelée postDelayed() qui vous permet d'afficher un runnable au feu après une période de temps donnée. Vous pouvez l'utiliser avec un runnable pour gérer votre tâche une fois par minute.

// Declare this in your activity 
Runnable r; 

//change your onClick to make and post a recursive runnable. 
public void onClick(final View v) { //<-- need to make v final so we can refer to it in the inner class. 
    switch (v.getId()) { 
    case R.id.button_Timer: 
     Log.e("MainActivity", "Clicked"); 
     r = new Runnable(){ 
      public void run(){ 
       if (mService != null){ 
        str2 = Ef.getText().toString(); 
        str2 = str2.substring(0, 0) + "E" + str2.substring(0, str2.length()); 
        mService.sendAlert(mDevice, str2); 
        v.postDelayed(r, 60 * 1000); 
       } 
      } 
     }; 
     //fire the first run. It'll handle the repeating 
     v.post(r); 
     break; 

    default: 
     Log.e(TAG,"wrong Click event"); 
     break; 
    } 
} 
0
public void onClick(View v) { 
    switch (v.getId()) { 


    case R.id.button_Timer: 
     Log.e("MainActivity", "Clicked"); 
     if (mService != null) 

     { 
      str2 = Ef.getText().toString(); 
      str2 = str2.substring(0, 0) + "E" + str2.substring(0, str2.length()); 
      final MyTimer timer = new MyTimer(999999999,60000); 
      timer.start(); 
     } 
     break; 

    default: 
     Log.e(TAG,"wrong Click event"); 
     break; 
    } 
} 


public class MyTimer extends CountDownTimer{ 

    public MyTimer(long millisInFuture, long countDownInterval) { 
     super(millisInFuture, countDownInterval); 
    } 

    @Override 
    public void onFinish() { 
    } 

    @Override 
    public void onTick(long millisUntilFinished) { 
     mService.sendAlert(mDevice, str2); 
    } 
}