我对在这种情况下添加计时器很困惑。我想在点击“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;
}
}
提前致谢
答案 0 :(得分:0)
View
因此Button
有一个名为postDelayed()的方法,允许您在给定的时间段后发布runnable。您可以将它与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;
}
}
答案 1 :(得分: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);
}
}