2011-08-27 27 views
0

我做了一個緊急應用程序,當按下音量降低鍵或菜單鍵時,將向5個人發送短信。 這是我檢測按鍵代碼時,活動推出:如何在android中創建一個每5秒將計數器變量重置爲0的計時器?

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

大家已經知道如何創建計時器(或其他)在android系統重置我計數器變量到零每3秒?所以我可以運行一些程序,當按鈕被按下5次之前3秒..謝謝..

回答

7

這是如何使用的TimerTask使用定時器,

Timer timer = new Timer(); 

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

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

要取消,您可以使用timer.cancel();

希望這有助於你的計時器。

+0

它很好地suri .. ..非常感謝您的幫助..有一個美好的一天suri .. :) –

+0

同樣給你有一個美好的一天:) –

1

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

+1

你可以給我一些鏈接或例子如何實現該類?謝謝.. –