Search code examples
androidurioncreate

Improving performance by loading URI after activity is created


I've got an app with an activity that may or may not load a streaming MP3. I'm using the wonderful AudioWife library to do so. However, this causes a really significant delay when the activity is opened. This is extremely annoying on slower devices or connections (the screen sometimes even turns black for seconds). The delay does not occur when there's no streaming mp3. The delay isn't caused specifically by AudioWife, since the code I used before caused the same delay.

The problem is obviously that I'm loading an URI onCreate(), so the activity waits until it retrieved the meta information such as length.

Here's the part of my onCreate()

if (showMusic){
    LinearLayout musicContainer = (LinearLayout) findViewById(R.id.MusicContainer);
    musicContainer.setVisibility(View.VISIBLE);
    Uri uri = Uri.parse(mixLink);
    AudioWife.getInstance().init(getApplicationContext(), uri)
    .useDefaultUi(musicContainer , getLayoutInflater());
    [...]
}

I'd like the heavy lifting (the loading of the mp3) to start after the activity is created, to prevent the activity from freezing.

I've tried putting the code above into an ASyncTask, to no avail, since the line that causes the problem (init()) needs to be run on the graphical thread. If I put the part of the code in doInBackground() the app crashes. If I put that part of the code into onPostExecute() the app doesn't crash, but the delay is still there.

Thanks in advance.


Solution

  • Assuming that you are starting tha AsyncTask in the onCreate(), you will still see a delay because the operations executed by the task in the onPostExecute() will be queued on the UI thread, which means it will be concurrent with the UI stuff.

    Said this, I suggest you to simply start the AsyncTask with an arbitrary initial delay.