Splash screen with background tasks

2019-08-18 23:03发布

I am trying to make my application launcha splash screen for 5 seconds while initializing various web services in the background. Here is my code:

public void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    // Splash screen view
    setContentView(R.layout.splashscreen);

    final SplashScreen sPlashScreen = this;   

    // The thread to wait for splash screen events
    mSplashThread =  new Thread()
    {
        @Override
        public void run()
        {
            try {
                synchronized(this){
                    // Wait given period of time or exit on touch
                    wait(5000);
                }
            }
            catch(InterruptedException ex)
            {                    
            }
            finally 
            {

                finish();


                // Run next activity
                Intent intent = new Intent();
                intent.setClass(sPlashScreen, Splash_testActivity.class);
                startActivity(intent);
                stop();
            }
        }
    };

    mSplashThread.start(); 

    for (int i=0;i<100;i++)
    Log.d("splash test", "initialize web methods");
}

Now what I think should happen is that while the splash screen is displayed, the application should log "initialize web methods."

But what actually happens is that the log is added only after the slash screen disappears.

What am I doing wrong??

2条回答
乱世女痞
2楼-- · 2019-08-18 23:20

Run your Thread Using Handler or AsyncTask.

查看更多
我想做一个坏孩纸
3楼-- · 2019-08-18 23:34

Try to do it this way. This tutorial is simple and flexible. This is what you need:

// You initialize _splashTime to any value

// thread for displaying the SplashScreen
Thread splashTread = new Thread() {
    @Override
    public void run() {
        try {
            int waited = 0;
            while(waited < _splashTime)) {
                sleep(100);
                waited += 100;
            }
            }
        } catch(InterruptedException e) {
            // do nothing
        } finally {
            finish();
            startActivity(new Intent("com.droidnova.android.splashscreen.MyApp"));
            stop();
        }
    }
};
splashTread.start();

Note: This code is adopted from the above url.

查看更多
登录 后发表回答