Handler.sendMessageDelayed(msg, delay) not working correctly

百般思念 提交于 2019-12-10 13:36:53

问题


I have defined a splashscreen to be shown during loading. But depending on the internet connection it can takes only 600ms to load or sometimes 5000ms. So i defined that the splashscreen is at least shown 3000ms so that the user is not irritated by flackering screen.

I define the start of the splashscreen the following way:

 private void splashScreen() {
        setContentView(R.layout.splashscreen);
        splash = (ImageView) findViewById(R.id.splashscreenLayer);
        startSplashTime = new Date();
        new LoadingThread().start(); 
    }

In the LoadingThread I check the network and load data from the Internet:

private class LoadingThread extends Thread {

        @Override
        public void run() {
            checkNetwork();
        }

    }

As soon as loading is done, i send a message to my handler defined in the MainActivity:

public void stopSplash() {
        Message msg = new Message();
        msg.what = STOPSPLASH;

        Date endSplashTime = new Date();
        long time = endSplashTime.getTime() - startSplashTime.getTime();
        System.out.println("Time Splashscreen was displayed: " + time);
        if (time < SPLASH_MIN_TIME) {
            long delay = SPLASH_MIN_TIME - time;
            System.out.println("Delay Splashscreen for: " + delay);
            splashHandler.sendMessageDelayed(msg, delay);
        } else {
            System.out.print("Show Splashscreen now");
            splashHandler.sendMessage(msg);
        }
    }

Some code lines on the LoadingThreads are called by runOnUIThread(). Unfortunately, if time < SPLASH_MIN_TIME the message isn't delayed but send instantly. I think with sendMessageDelayed() this shouldn't be the case. Anybody knows why? The sysout shows that the delay time is calculated correctly. Thanks!


回答1:


maybe the error not in the delay. (don't know without more code) but the possible reason is: your download thread displaying another layout after your download, and splashscreen become invisible under your top layer. Splashscreen receive your message after delay, therefore you dont see it later.



来源:https://stackoverflow.com/questions/3076139/handler-sendmessagedelayedmsg-delay-not-working-correctly

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