首页 > 解决方案 > 无限while循环,而AsyncTask没有完成

问题描述

我有一个 SplashScreen Activity,它调用 Asynctask 类来获取 Internet 上的信息。

我想在我的 Asynctask 未完成时等待(互联网速度连接期间的时间)

我的活动:

public static boolean test = true;

[...]

final Liste en_ce_moment = new Liste("En ce moment au cinéma", nowMovie);
mesListes.add(en_ce_moment);

//call my Asynctask file 
fetchNowMovie process = new fetchNowMovie();
process.execute();

while(test)
{

}

Intent i = new Intent(SplashScreenActivity.this, MainActivity.class);
startActivity(i);

我的异步任务:

protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);

        SplashScreenActivity.test = false;

        SplashScreenActivity.nowMovie.clear();
        SplashScreenActivity.nowMovie.addAll(list);

    }

从逻辑上讲,布尔值变为假,onPostExecute因此 while 循环停止并且意图必须开始,但 while 循环永远不会停止......

标签: javaandroidloopsandroid-asynctasksplash-screen

解决方案


这看起来像是隐藏在另一个问题中的问题,但要解决第一级问题,您可以尝试使用CountDownLatch而不是静态布尔值:

CountDownLatch latch = new CountDownLatch(1);
fetchNowMovie process = new fetchNowMovie(latch);
process.execute();

latch.await();

Intent i = new Intent(SplashScreenActivity.this, MainActivity.class);
startActivity(i);

您必须接受闩锁作为 AsyncTask 构造函数的一部分:

private final CountDownLatch latch;

public fetchNowMovie(CountDownLatch latch) {
    this.latch = latch;
}

// ...

protected void onPostExecute(Void aVoid) {
    super.onPostExecute(aVoid);

    latch.countDown();

    SplashScreenActivity.nowMovie.clear();
    SplashScreenActivity.nowMovie.addAll(list);
}

推荐阅读