我有一个 SplashScreen Activity ,它调用 Asynctask 类来获取 Internet 上的信息。
我想等待我的 Asynctask 未完成(互联网速度连接期间的时间)
我的 Activity :
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);
}
从逻辑上讲, boolean 值在 onPostExecute
中变为假,因此 while 循环停止并且 intent 必须开始但 while 循环永远不会停止...
最佳答案
让我们使用简单的 interface
逻辑以安全的方式做您想做的事:
因此,我们添加了简单的接口(interface)
,并重新定义了您的MyAsnycTask
类的构造函数
,如下所示:
public class MyAsnycTask extends AsyncTask
{
OnTaskFinished listener;
// Our simple interface
public interface OnTaskFinished {
void TimeToNextActivity();
}
// Your MyAsnycTask class constructor
public MyAsnycTask(OnTaskFinished l) {
listener = l;
}
. . .
作为 onPostExecute()
中的最后一行代码,我们已经完成了我们正在做的任何事情。所以通过我们的 listener
告诉这个:
listener.TimeToNextActivity();
要使用我们之前添加的接口(interface)
,您的Activity
必须实现
它。所以我们实现它。在实现的方法中,我们使用 Intent
转到下一个 Activity
:
public class MyActivity extends Activity
implements MyAsnycTask.OnTaskFinished
{
@Override
public void TimeToNextActivity()
{
// Here go to next activity
Intent i = new Intent(this, MainActivity.class);
startActivity(i);
}
当我们修改 MyAsnycTask
类的 constructor
时,我们必须像这样初始化它:
MyAsnycTask process = new MyAsnycTask(this);
process.execute();
关于java - 无限 while 循环,而 AsyncTask 未完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58698927/