0

I have created a custom control panel for a video player. Now I want to give a effect like default MediaController where the panel becomes visible when the screen is touched and it becomes invisible again after the last touch time. I can use this type of code for that.

Thread thread = new Thread() {
            @Override
            public void run() {
                try {
                    Thread.sleep(60000);
                } catch (InterruptedException e) {
                }

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // make the panel invisible 
                    }
                });
            }
        };

I can start the thread when the screen is touched and make it invisible after 60 seconds. But in my case, if the user touches the screen again in between this 60 seconds, the panel should vanish after 60 seconds from the last touch. How to consider this case also?

dev_android
  • 8,698
  • 22
  • 91
  • 148

2 Answers2

1

I would recommend using a combination of Runnables and a Handler. You can do Handler calls using postDelayed() to do something after, say, 60 seconds.

Here's an example:

private Handler mHandler = new Handler();

mHandler.post(showControls); // Call this to show the controls

private Runnable showControls = new Runnable() {    
   public void run() {
      // Code to show controls
      mHandler.removeCallbacks(showControls);
      mHandler.postDelayed(hideControls, 60000);
   }
};

private Runnable hideControls = new Runnable() {
   public void run() {
      // Code to hide the controls
   }
};
Michell Bak
  • 13,182
  • 11
  • 64
  • 121
  • i used this:-showControls = new Runnable() { public void run() { // Code to show controls mHandler.removeCallbacks(showControls); controlpanel.setVisibility(View.VISIBLE); mHandler.postDelayed(hideControls, 10000); } }; hideControls = new Runnable() { public void run() { // Code to hide the controls controlpanel.setVisibility(View.INVISIBLE); } };// But it is working as per the first touch, it seems that the system cannot cancel the runnable in queue. where is the problem in my code? – dev_android Sep 28 '11 at 12:46
  • 1
    You can cancel a Runnable simply by calling mHandler.removeCallbacks() on the Runnable. – Michell Bak Sep 28 '11 at 13:29
1

Simply delete/cancel current timer.

Btw, you should not do it by Thread, but by posting message to a Handler. Such future timer task doesn't need another thread.

Pointer Null
  • 39,597
  • 13
  • 90
  • 111