VSB
VSB

Reputation: 10375

Android Splash screen with data load and delay

I got an activity which should do 2 different things in parallel act as SplashScreen Activity:

  1. wait for 1.5 seconds to display app splash screen
  2. copy some files from assets to device storage in background

Activity implement initial delay (task1) by a handler and file copy (task2) by AsyncTask

Problem: delay of this activity should be such that which both task complete and then start next activity. I should note that these two task are running in parallel in background and time of copying files may differ each time (some times longer than 1.5seconds, some times shorter).

In other word starting next activity must be synchronized by finishing of both background tasks.


So, How this can be implemented?

Upvotes: 0

Views: 1642

Answers (2)

Curtis Shipley
Curtis Shipley

Reputation: 8090

I think the easiest thing to do is in the beginning of your async task, get the current time. When you're done with the work, get the current time again. If this is less than 1.5 secs, then do a Thread.Sleep() for the difference.

Start the next activity in the postExecute(). Something like this:

private class DoStuffAsync extends AsyncTask<Void, Integer, Long> {
     protected Long doInBackground() {

        long start = new Date().getTime();

        // copy assents

        long end = new Date().getTime();

        if ( end-start < 1500 )
           Thread.sleep( 1500-(end-start));

         return totalSize;
     }

     protected void onPostExecute(Long result) {
         startActivity( new Intent(Activity.this, NewActivity.class));
     }
 }

Updated: Fixed math problems.

Upvotes: 3

TheIT
TheIT

Reputation: 12219

Your design is solid. The detail that you're after to sync the handler and AsyncTask chimes from the realization that both will be executed from the UI thread and therefore you don't need to worry about any concurrency issues. The easiest way then to check whether your new Activity should be started, would be to create two boolean flags. One for the 1.5s timer and the other for the file copy task. Then when either process finished, it checks whether the other flag is set to complete, and if it is, a new Activity will be launched, otherwise the completed task will set it's completed flag to true and when the remaining task completes it will launch the Activity.

Upvotes: 1

Related Questions