简体   繁体   English

Android AsyncTask和

[英]Android AsyncTask and

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. 嗨我在我的应用程序中有一个AsyncTask,在OnCreate()中调用,它通过Web检索一些数据,并在下载时显示不确定的进度条。

The problem is when i start the app the screen remain blank until the AsyncTask is finished. 问题是,当我启动应用程序时,屏幕保持空白,直到AsyncTask完成。 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();
 }

OnCreate() is executed before the Activity is being shown on the screen, so the whole data download process executes before showing the activity. OnCreate()在Activity显示在屏幕上之前执行,因此整个数据下载过程在显示活动之前执行。

Solution could be to start AsyncTask in OnStart() method instead of in OnCreate() (also overriden). 解决方案可能是在OnStart()方法中启动AsyncTask而不是OnCreate()(也是覆盖)。 OnStart() is executed while activity is going to be shown on the screen (see activity lifecycle). 当活动将在屏幕上显示时执行OnStart()(请参阅活动生命周期)。

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. 您应该在OnStart()方法中显示进度对话框,并在适​​当的时刻在AsyncTask中更新和关闭它。

This is how it looks in my app: 这是它在我的应用程序中的外观:

  1. AsyncTask is started in activity OnStart() along with showing dialog box AsyncTask在活动OnStart()中启动,同时显示对话框
  2. Data is being downloaded in inner class extending AsyncTask 数据正在内部类中下载,扩展了AsyncTask
  3. After data is downloaded the dialog box is dismissed and further data processing initialized (OnPostExecute()) 下载数据后,对话框被解除,并进一步初始化数据处理(OnPostExecute())

The drawback could be that OnStart() is called on the first activity call, but also after restoring it (for example after minimizing the application). 缺点可能是在第一次活动调用时调用OnStart(),但在恢复它之后(例如在最小化应用程序之后)。 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). 因此AsyncTask可以与OnCreate()相反执行几次,只调用一次 - 创建活动时(而不是在恢复活动时)。

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 如果您使用AsyncTask中的对话框对此类活动进行jUnit测试也会出现一些问题 - 如果您这样做,请告诉我 - 将发布一些解决方案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM