maxt
maxt

Reputation: 11

Android Async Task or not

In my android application, I need to execute some operations, like creating some files in the internal storage and download some data from a server on start of the app. Only when these operations are finished, the rest of the application can work properly. So it’s my intention to show an image and a progress bar when the app is opened, and after all these operations are done, a new activity is opened.

Now, I know it’s common to put potentially long running operations like downloads and file reading/writing into async tasks. However, in my case, I can’t really continue until these operations are finished, so do I need to use Async Tasks, or is it ok for the application to block in this case?

Or should I start an Async Task and then wait for it, using the get() method?

Thanks for advices, I'd really like to do this the right way.

Upvotes: 1

Views: 80

Answers (2)

Niki van Stein
Niki van Stein

Reputation: 10724

You need to put it in an async task or different thread. Internet requests on the main ui thread will create a fatal error on the newest (android 4+) systems.

It is always better to show a loading image or progress dialog than showing a hanging white screen.

For all long blocking jobs, async is required.

If you have the splash screen as your main activity, add this code for your async task:

 private class YourTask extends AsyncTask<URL, Integer, Long> {
     protected Long doInBackground(URL... urls) {
         int count = urls.length;
         //Do your work here
         //Note that depending on the type of work, you can change the parameters
         //of the async task.
         return count;
     }

     protected void onProgressUpdate(Integer... progress) {
         setProgressPercent(progress[0]);
     }

     protected void onPostExecute(Long result) {
         //Put here the code when your job is done, for example:
         //start a new activity (your real main activity).
     }
 }

After that, in your oncreate method of the activity, call

 new YourTask ().execute(url1, url2, url3);

Upvotes: 1

Eldhose M Babu
Eldhose M Babu

Reputation: 14510

You care create a splash activity which should be your launcher activity.

Then in the splah, start an async task for downloading and all, then after the completion of the task, you can move to your desired activities.

You can also use a thread for this purpose; in that case, you need to handle the task completion callback using a handler or runOnUIThread mechanisms.

Better to use Async task for this.

Upvotes: 1

Related Questions