3

我正在为应用程序制作 SplashScreen ...当应用程序启动时,它会启动 LoadingActivity ...睡眠 3 秒,完成();然后启动 MainActivity。Splash 用于更新数据库。如果数据库已经更新,无论如何我都希望启动 3 秒。

我正在使用以下代码:

protected void onPostExecute(Void result) {
    super.onPostExecute(result);
    try {
        Thread.sleep(3000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    } finally {
        Intent intent = new Intent(LoadingActivity.this, MainActivity.class);
        startActivity(intent);
        finish();
    }
}

这是一个坏习惯吗?为什么?该应用程序在 AVD 中运行良好。

4

3 回答 3

6

在 UI 线程上休眠总是一个坏主意。在这种情况下,您位于onPostExecuteUI 线程上。

把你的睡眠投入到你的doInBackground方法中AsyncTask,你不会在那里得到任何 ANR(Android 没有响应)。

用户不喜欢等待启动画面,所以最好不要等待。但有时需要启动画面(即由于合同)。

于 2013-08-03T19:55:45.007 回答
5

是的,这是不好的做法,onPostExecute()在 UI 线程上调用,所以基本上你会阻塞你的 UI 线程整整 3 秒。我怀疑你想显示一个启动画面。你可以这样做。

new Handler().postDelayed(new Runnable(){
    @Override
    public void run(){
        Intent intent = new Intent(LoadingActivity.this, MainActivity.class);
        startActivity(intent);
        finish();
     }
},3000);

或者,如果您想坚持使用,请AsyncTask覆盖并在doInBackground()其中睡觉并正常启动。ActivityonPostExecute()

于 2013-08-03T19:55:54.580 回答
-4

如果这是在程序的最开始,您可以执行一个 while 循环,直到 System.currentTimeMillis() 高于程序开始时的 3000。

于 2013-08-03T19:53:26.450 回答