Timeout detection for eventlisteners in Android

2019-08-29 13:35发布

问题:

I set up event listener, for example: setOnClickListener like this

    Button stopBtn = (Button)findViewById(R.id.stop);
    stopBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            doMagic();
        }
    });

I would like to set this listener a timeout event on 10s if button is not pressed. Use case: i have button1 that activates this stopBtn listener for 10s and if timeout comes it becomes deactivated and i need to press button1 to make stopBtn active again.

Im probably doing it wrong:

    final Handler myHandler = new Handler();
    startBtn = (Button)findViewById(R.id.start);
    myHandler.postDelayed(new Runnable() {
        public void run() {
            startBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Log.i(TAG,"runned");
                }
            });
        }
    }, 10000);

After 10s im still able to click it and that is probably cos event listener is still attached. How can i detach it even if i don't know if its fired or not.

回答1:

A delayed Runnable posted on a Handler could manage that:

myHandler.postDelayed(new Runnable() {
 public void run() {
   if(something happened) {
     // magic work
   } else {
     // turn off the event
   }
 }
, 10000);

You can init the Handler as an instance variable by using this code:

final Handler myHandler = new Handler();


回答2:

Delayed actions can be arranged by using a Handler. Specifically check the 2 methods: postAtTime(Runnable, long) and postDelayed(Runnable, long).

It is easy to create a Handler, just use its default constructor Handler handler = new Handler() within the Activity.onCreate(Bundle state). Then wrap your desired action into a Runnable and pass to the handler.