Why does the handler not trigger a warning as expected?

I need my application to trigger a warning at a specified amount of time after a user clicks a button. In the documentation, it looks like the Handler is what I need, and using it seems like a dead brain.

However, I found that despite using postDelayed, my program starts immediately. I know that I am missing something obvious, but I just do not see it. Why does the code below make the phone vibrate right away rather than wait a minute?

 ...

   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
source share
3 answers

This is because you are doing it wrong. Just view the stream:

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);
+3

run() Vibrate:

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

- Runnable,

...

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

v = () getSystemService (Context.VIBRATOR_SERVICE);

button.setOnClickListener( OnClickListener() {

        @Override
        public void onClick(View v) {

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

...

0
source

Source: https://habr.com/ru/post/1772700/


All Articles