Android: Timer/Delay Alternative

爱⌒轻易说出口 提交于 2019-12-10 16:46:22

问题


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.



来源:https://stackoverflow.com/questions/6284095/android-timer-delay-alternative

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!