2013-05-09 35 views
0

在这种情况下,我很困惑添加一个定时器。我想每次点击“button_Timer”时发送“mService.sendAlert(mDevice,str2)”。提前在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; 
    } 
} 

感谢

回答

0

View,因此Button有一个名为postDelayed()方法,使您可以发布可运行给定的时间段后触发。你可以使用它和一个可运行的程序来处理每分钟一次的任务。

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