My Activity in onCreate()
performs long computations that take some time.
In the same onCreate()
I call setContentView()
to set the appearance of the activity.
The point is that, since it takes a while to performs the above mentioned computations the screen of the Activity loads only after long time.
Please, any suggestion on how to avoid this?
I have tried to call setContentView()
in onCreate()
and start the computations in onResume()
, but again the Activity screen is loaded only at the end.
There is no other way than to use e.g. an AsyncTask. The reason is that the actual rendering does not take place asynchronously; in other words, setContentView will only set some data but nothing will be displayed at that point in time.
AsyncTask, however, is not necessarily meant for "long" computations. But if your app relies on the result, and no other computations take place in parallel, it may still be the simplest way for you to achieve what you want. If not, you may have to use a Thread even.
Update Since everybody keeps bombarding the original poster with more use AsyncTask answers of various quality, I'd like to stress one more time that AsyncTask is intended for short operations (to quote the reference: a few seconds at the most) while the OP has given no indication on how long his computations really take. Also, an AsyncTask is a one-shot-only object which can only run once.
One more very important point to consider is the following. Android assigns AsyncTask a background task priority. This means that, besides the lower scheduling priority, the computations in AsyncTask will take ten times as long as if they were performed in the foreground, because Android runs all tasks which have background priority with an artificial limit of 10% CPU cycles. However, AsyncTasks can be lifted out of this group by raising its priority "just a little bit". For an AsyncTask, it would be done like so:
public R doInBackground(I... is) {
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND +
Process.THREAD_PRIORITY_MORE_FAVORABLE);
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With