Android: Timer/Delay Alternative

2019-06-27 23:03发布

问题:

I want to make an image be visibile for 60 ms and then be invisible, then I want another image to do the same.. and so on. I don't think I'm using the Timer right.. because when I run the app both images turn on at the same time and don't disappear when I press the button that uses this function.

Here's some sample code..

timer.schedule(new TimerTask()
        {
            @Override
            public void run()
            {
                LED_1.setVisibility(View.VISIBLE);
                                    // LED_1 is an ImageView
            }
        }, 60);
        LED_1.setVisibility(View.INVISIBLE);

timer2.schedule(new TimerTask()
        {
            @Override
            public void run()
            {
                LED_2.setVisibility(View.VISIBLE);
                                    // LED_2 is an ImageView
            }
        }, 60);
        LED_2.setVisibility(View.INVISIBLE);

Is there another alternative? I've tried examples like.. Android app How to delay your Service start on phone boot

and

http://www.roseindia.net/java/beginners/DelayExample.shtml

But it's not doing what I want..

Anything I'm doing wrong? Or is there an alternative way that I can do this?

Thanks.

-Faul

For Good.Dima..

            int delayRate = 60;
        final Runnable LED_1_On = new Runnable()
    {
        public void run()
        {
            LED_1.setVisibility(View.VISIBLE);
                    handler.postDelayed(this, delayRate);

        }
    };

    handler.postDelayed(LED_1_On, delayRate);

    final Runnable LED_2_On  = new Runnable()
    {
        public void run()
        {
            LED_1.setVisibility(View.INVISIBLE);
            LED_2.setVisibility(View.VISIBLE);
                    handler3.postDelayed(this, delayRate);

        }
    };

    handler.postDelayed(LED_2_On, delayRate);

回答1:

You can try to use Handler, it posts smth into UI thread, it can post with a delay postDelayed



回答2:

The problem is that both timers have a 60 ms delay and in the run method of both you set them to be visible. You need to change one of the run methods to set it to invisible.



回答3:

You are creating two events which both fire 60 ms from now.

You instead could set the first event to fire in 60ms and the second in 120ms, or have the first event trigger a submission of the second event 60ms from when the first runs.