i make an emergency application that will send a SMS to the 5 people when volume down key or menu key is pressed. 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?? so i can runs some procedure when a button is pressed 5 times before 3 seconds.. Thanks..
This is how you can use the Timer using TimerTask:
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();
使用java.util.Timer
和java.util.TimerTask
类。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.