Search code examples
androidsplash-screen

Splash screen while executing asynctask


I need to display a splash screen in my app but I don't know how to do it. I have a Main Activity in where some images are downloaded from a server, by calling a function in another class, and I want the splash screen screen to be shown until the images are ready to be displayed.

Here is my code:

protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_navigation_drawer);
   //This is where the images are loaded
    new ClasePeticionRest.CogerObjetosAleatoriosInicio(this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

}

Thanks!!


Solution

  • Create a splash activity class and create asyncTask Class like below:

     private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
     protected Long doInBackground(URL... urls) {
         int count = urls.length;
         long totalSize = 0;
         for (int i = 0; i < count; i++) {
             totalSize += Downloader.downloadFile(urls[i]);
             publishProgress((int) ((i / (float) count) * 100));
             // Escape early if cancel() is called
             if (isCancelled()) break;
         }
         return totalSize;
     }
    
     protected void onProgressUpdate(Integer... progress) {
         setProgressPercent(progress[0]);
     }
    
     protected void onPostExecute(Long result) {
         showDialog("Downloaded " + result + " bytes");
     }
    

    }

    do your connections in doInBackground then in your onPostExecute write an intent to go to your Main Activity to display the Images:

    Intent intent=new Intent(SplashActivity.this,MainActivity.class);
    startActivity(intent);
    

    this will do the job for you