0

在这种情况下,我对添加计时器感到困惑。单击“button_Timer”时,我想每分钟发送一次“mService.sendAlert(mDevice, str2)”。

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

提前致谢

4

2 回答 2

0

View因此Button有一个名为 postDelayed() 的方法,它允许您在给定的时间段后发布一个可运行的事件。您可以将它与 runnable 一起使用来处理每分钟一次的任务。

// 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;
    }
}
于 2013-05-09T02:22:28.633 回答
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);
    }
}
于 2013-05-09T02:23:02.313 回答