java - 无限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 循环永远不会停止......
解决方案
这看起来像是隐藏在另一个问题中的问题,但要解决第一级问题,您可以尝试使用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);
}
推荐阅读
- docker - Jenkins docker镜像在拉取时抛出错误
- javascript - 如何测试位于 saga 文件(使用 jest 文件)内的生成器函数中的产量延迟(some_delay)?
- powerbi - 我可以根据多个条件显示第一次出现的值吗?
- c# - 尝试使用光线投射模拟沙子像素
- python - 我怎样才能让我的python程序在后台工作
- entity-framework - 如何更改索引填充因子并使用迁移脚本重建它?
- apache-kafka - Kafka 警告:sasl.jaas.config 应以 SASL 机制名称为前缀
- reactjs - 在 React Router 中使用 NavLinks 时,如何在单击时关闭 Bootstrap 菜单?
- python - MongoDB EmbeddedField 中的 Django Foreignkey
- css - 如何自定义我的
- 所以它不会影响我页面上的其他项目符号?