如果传递5秒,则开始动画

时间:2015-08-05 08:15:16

标签: java android timer

如何检查Java(Android)中是否已经过了5秒。

if (passedTime >= 5) {
    startAnimation();
} else {
    Log.d("TAG", passedTime);
}

2 个答案:

答案 0 :(得分:0)

您可以使用System.nanoTime()来衡量已用时间。

例如,你可以这样做:

long start = System.nanoTime();
while (System.nanoTime() - start < 5000000);
StartAnimation();

或者,如果它不是主线程和线程没有其他目的而不是启动动画:

try {
    Thread.sleep(5000);
    startAnimation();
} catch (InterruptedException e) {
     // handle Interruption Exception here
}

此外,如果线程正在做其他一些事情,你可以这样做(但不会令人犹豫5秒);

long start = System.nanoTime();
bool doStuff = true;
while (doStuff) {
    if (System.nanoTime() - start >= 5000000) {
        StartAnimation();
    }
    // Do other stuff here
}

你开始一个自己开始动画的线程(在我看来可能是最好的解决方案):

new Thread(new Runnable() {
    public void run() {
        try {
            Thread.sleep(5000);
            // Make sure animation will run on UI Thread!
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    StartAnimation();
                }
            });
        } catch (InterruptedException e) {
            // Handle exception
        }

    }
}).start();

编辑:

阅读完最后评论后: 我会把那个逻辑传递给startAnimation:

// Class variable:
long lastAnimationStart = 0;

void StartAnimation() {
    if (lastAnimationStart = 0 || System.nanoTime() - lastAnimationStart >= 5000000) {
        lastAnimationStart = System.nanoTime();
        // Animation stuff here
    }
}

答案 1 :(得分:0)

您应该使用处理程序并向其发布延迟消息。像这样:

private static final int MSG_START_ANIMATION = 1337;
private Handler mAnimationHandler = new Handler() {

    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case MSG_START_ANIMATION:
                startAnimation();
                break;
        }
    }
};
private final ViewPager.OnPageChangeListener mOnPageChangeListener = new ViewPager.OnPageChangeListener() {
    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        mAnimationHandler.removeMessages(MSG_START_ANIMATION);
        mAnimationHandler.sendEmptyMessageDelayed(MSG_START_ANIMATION, TimeUnit.SECONDS.toMillis(5));
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
};

另外,请阅读此博客文章,了解如何通过内部处理程序类泄漏上下文:Android Design Patterns