简体   繁体   English

如何在Android中创建一个将计数器变量每5秒重置为0的计时器?

[英]How to create a timer in android that reset a counter variable into 0 every 5 second?

i make an emergency application that will send a SMS to the 5 people when volume down key or menu key is pressed. 我制作了一个紧急应用程序,当按下降低音量键或菜单键时,将向5个人发送短信。 this is my code for detect a keypress when the activity launched: 这是我在活动启动时检测按键的代码:

package com.application.tpa;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.widget.Toast;

public class main extends Activity {
    /** Called when the activity is first created. */
    int ctrMenu=0,ctrkeyUp=0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        //startService(new Intent(main.this, PAservice.class));
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_MENU)) {
            ctrkeyUp=0;
            ctrMenu++;
            if (ctrMenu==5)
            {
                Toast.makeText(this, "You pressed the Menu button!", Toast.LENGTH_LONG).show();
                ctrMenu=0;
            }
            //return true;
        }
        else if ((keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)) {
            ctrMenu=0;
            ctrkeyUp++;
            if (ctrkeyUp==5)
            {
                Toast.makeText(this, "You pressed the Volume Down button!", Toast.LENGTH_LONG).show();                     
                ctrkeyUp=0;
            }
            //return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}

has everyone know how to create timer (or whatever) in android to reset my counter variable into zero every 3 second?? 有没有人知道如何在android中创建计时器(或其他方法)以每3秒将我的计数器变量重置为零?? so i can runs some procedure when a button is pressed 5 times before 3 seconds.. Thanks.. 所以我可以在3秒之前按5次按钮时运行一些程序。

This is how you can use the Timer using TimerTask: 这是通过TimerTask使用Timer的方法:

 Timer timer = new Timer();

        timer.schedule(new TimerTask() {
            public void run() {

               // add your stuff here
                }
            }
        }, 3000, 3000);

To cancel the timer you can use timer.cancel(); 要取消计时器,可以使用timer.cancel();

使用java.util.Timerjava.util.TimerTask类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM