0

I have an Android application, written in Java. It uses a Java class that takes a few seconds to load (some .csv files and jars).

What is the idiomatic way to load that stuff?

I inherited the code, and right now it tries to load it in the background, but I think there are some race conditions causing bugs.

I just want a nice, synchronous, slow but reliable load (say, a splash screen) as the application starts.

I found many blog posts about implementing a splash screen.

Is there an official version?

The code that is loading in the background:

/**
 * Initialize staticAnthro if it is null.
 * This class loads CSV files, so do it in the background.
 */
static class InitInBackground extends AsyncTask<Void, Integer, Boolean> {
    @NonNull
    @Override
    protected Boolean doInBackground(Void... arg0) {
        startedInit = true;
        try {
            if (staticAnthro == null) {
                staticAnthro = new Anthro();
            }
        } catch (IOException e) {
            Log.e(LOGGER_TAG, "Error starting Anthro class", e);
        }

        return true;
    }
}
Twisha Kotecha
  • 1,082
  • 1
  • 4
  • 18
dfrankow
  • 20,191
  • 41
  • 152
  • 214

2 Answers2

0

First of all, using AsyncTask is outdated and may cause bugs such as memory leaks especially if it is a long running task. Imagine this scenario, your AsyncTask is started and in progress, but you rotate your phone, the activity has to be re-created, but since it still holds a reference to your AsyncTask, it won't be garbage collected - boom memory leak.

Read the second paragraph here for more information and alternatives.

If you can use Kotlin, take a look at Coroutines, otherwise try RxJava.

For the splash screen part: as far as I know, there are 2 ways how can you implement a splash screen, official way would be to define a new style in your styles.xml like this:

<style name="YourTheme.Launcher">
        <item name="android:windowBackground">
            @drawable/launch_background
        </item>
</style>

and then set your android:theme=@styles/YourTheme.Launcher in your AndroidManifest.xml.

The other way would be to create a splash View, which is being displayed until your background task finishes. This can be achieved with RxJava, Coroutines

0

I am agreed with @jakubas-trinkunas about using AsyncTask. But, as I can understand, the question is - WHERE should be loaded resources? My opinion - Application class How? so, you should decide by your self. IMHO, best way is to start a Service to do this, and wait on a SplashScreen until it will be done.

Artem
  • 303
  • 2
  • 9