2010-11-02 26 views
3

我需要我的應用程序在用戶按下按鈕後的指定時間內觸發警報。這些文檔使得它看起來像Handler是我需要的,而且使用似乎已經死了。爲什麼不按預期觸發警報?

但是,我發現儘管使用postDelayed,我的例程立即運行。我知道我錯過了一些明顯的東西,但我看不到它。爲什麼下面的代碼會讓手機立即振動而不是等待一分鐘?

... 

    final Button button = (Button) findViewById(R.id.btnRun); 
    final Handler handler = new Handler(); 

    button.setOnClickListener(new OnClickListener() { 

    public void onClick(View v) {    
     ... 
     handler.postDelayed(Vibrate(), 60000); 

     }   
    }); 
... 

    private Runnable Vibrate() { 
    Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); 
    v.vibrate(300); 
    return null; 
    } 

回答

3

那是因爲你是做了錯誤的方式。只看流量:

handler.postDelayed(Vibrate(), 60000)會立即調用Vibrate()方法,然後它運行振動器的東西。其實Vibrate()返回null?你認爲處理程序會用空引用做什麼?你很幸運,它不會拋出NullPointerException。關於如何正確實現處理程序的例子太多了......只需在Google上多加一點點。

private class Vibrate implements Runnable{ 
    public void run(){ 
    Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); 
    v.vibrate(300); 
    } 
} 

然後:

handler.postDelayed(new Vibrate(), 60000); 
2

你需要寫一個run()方法振動:

private class Vibrate implements Runnable { 
    public void run(){ 
    Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); 
    v.vibrate(300); 
    //return null; don't return anything 
    } 
} 
+0

我不喜歡downvoting ......不過,你最好解決您的答案。在這種情況下,振動()作爲一種方法,而不是一個類。 – Cristian 2010-11-02 17:43:28

+1

排序,謝謝你的提醒。 – fredley 2010-11-02 17:46:28

0

你是使用Runnable的匿名對象,最簡單的方法,

... 

最終Button按鈕=(按鈕)findViewById(R.id。 btnRun); final Handler handler = new Handler();

Vibrator v =(Vibrator)getSystemService(Context.VIBRATOR_SERVICE);

button.setOnClickListener(新OnClickListener(){

 @Override 
     public void onClick(View v) { 

      handler.postDelayed(new Runnable() { 
       public void run() { 
        v.vibrate(300); 
       } 
      }, 60000); 
     } 
    }); 

...

相關問題