Android 异步任务和
您好,我的应用程序中有一个名为 OnCreate() 的 AsyncTask,它通过网络检索一些数据并在下载时显示不确定的进度条。
问题是当我启动应用程序时,屏幕保持空白,直到 AsyncTask 完成。 代码就是这样的。
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
loadData();
//Several UI Code
startAsyncTasks();
}
private void startAsyncTasks(){
new ConnectingTask().execute();
}
Hi i have an AsyncTask in my application called in OnCreate() that retrieve some data over the web and display an indeterminate progress bar while downloading.
The problem is when i start the app the screen remain blank until the AsyncTask is finished.
The code is something like that.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
loadData();
//Several UI Code
startAsyncTasks();
}
private void startAsyncTasks(){
new ConnectingTask().execute();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
OnCreate() 在 Activity 显示在屏幕上之前执行,因此整个数据下载过程在显示 Activity 之前执行。
解决方案可能是在 OnStart() 方法中启动 AsyncTask,而不是在 OnCreate() 中(也被覆盖)。 OnStart() 在 Activity 将要显示在屏幕上时执行(请参阅 Activity 生命周期)。
这是我在我的应用程序中实现的情况并且它有效。您应该在 OnStart() 方法中显示进度对话框,并在适当的时候在 AsyncTask 中更新和关闭它。
这就是它在我的应用程序中的样子:
缺点可能是 OnStart() 在第一次活动调用时被调用,而且在恢复它之后(例如最小化应用程序后)也会被调用。因此,AsyncTask 可以执行几次,与 OnCreate() 相反,OnCreate() 仅在创建 Activity 时(而不是恢复 Activity 时)调用一次。
如果您使用 AsyncTask 中的对话框对此类活动进行 jUnit 测试,也可能会出现一些问题 - 如果您这样做,请告诉我 - 将发布一些解决方案
OnCreate() is executed before the Activity is being shown on the screen, so the whole data download process executes before showing the activity.
Solution could be to start AsyncTask in OnStart() method instead of in OnCreate() (also overriden). OnStart() is executed while activity is going to be shown on the screen (see activity lifecycle).
This is the case I have implemented in my app and it works. You should show a progress dialog in OnStart() method, and update and dismiss it in AsyncTask in proper moments.
This is how it looks in my app:
The drawback could be that OnStart() is called on the first activity call, but also after restoring it (for example after minimizing the application). So AsyncTask can be executed few times in opposite to OnCreate(), that is called only once - when activity is created (not when it is restored).
There can also be some issues if You do the jUnit test of such activity with dialog in AsyncTask - let me know if You do - will post some solution