Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/201.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 在开始另一个活动之前,使用Thread.sleep(毫秒)等待一段时间是否是一种不好的做法?_Java_Android_Thread Sleep - Fatal编程技术网

Java 在开始另一个活动之前,使用Thread.sleep(毫秒)等待一段时间是否是一种不好的做法?

Java 在开始另一个活动之前,使用Thread.sleep(毫秒)等待一段时间是否是一种不好的做法?,java,android,thread-sleep,Java,Android,Thread Sleep,我正在为一个应用程序制作一个SplashScreen。。。当应用程序启动时,它开始加载活动。。。睡眠3秒钟,完成();然后开始主活动。Splash用于更新数据库。如果数据库已经更新,我希望飞溅仍然为3秒无论如何 我正在使用以下代码: protected void onPostExecute(Void result) { super.onPostExecute(result); try { Thread.sleep(3000); } catch (Inter

我正在为一个应用程序制作一个SplashScreen。。。当应用程序启动时,它开始加载活动。。。睡眠3秒钟,完成();然后开始主活动。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中运行良好。

如果这是在程序的最开始,您可以执行while循环,直到系统运行。currentTimeMillis()比程序开始时高出3000。

在UI线程上睡眠总是一个坏主意。在本例中,您位于UI线程上的
onPostExecute

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


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

是的,这是一种不好的做法,
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()
并在其中睡眠,然后在
onPostExecute()
中正常启动
活动。

如果您在主UI中运行睡眠,则您正在冻结UI,这将导致Activity不响应错误(ANR)。使用处理程序postdelayed函数。在主线程上执行阻塞操作总是一个坏主意
postdelayed
就是答案。这是一个比睡觉更糟糕的主意。你能给我一个建设性的评论,告诉我为什么吗?睡3秒钟只会阻塞UI,而照你说的做会让处理器使用率在整整3秒钟内达到100%。这就是为什么情况更糟。设备上可能还有其他应用程序在后台运行服务。除了阻止UI线程之外,您还阻止它们执行任何工作,例如。因此“更糟”。我没有提到,但是Splash需要更新数据库(如果过时),然后告诉他们你在做什么,并且只在你需要的时候呆在那里以完成它。我没有提到,但是Splash需要更新数据库(如果过时)。。。所以我需要异步,对吗?是的,然后你需要
AsyncTask
,在
doInBackground()
中同步数据库,然后在
onPostExecute()
中启动下一个
活动。