Android app taking forever to download web content

2019-04-12 20:12发布

I'm new to Android development and am trying to make an app that simply downloads the source code of a given webpage as a string and displays it in the log. I have it working, and for google.com, it works fairly quickly. For my desired webpage, however, it takes EIGHT MINUTES, even though my computer's web browser can load it in only a few seconds. During these eight minutes, four messages are displayed over and over again in the log, with varying values. They are:

  • W/art: Suspending all threads took: x.xxxm
  • I/art: Background stcky concurrent mark sweep GC freed xx(xxxxB) AllocSpace objects...
  • I/art: Background partial concurrent mark sweep GC freed xx(xxxxB) AllocSpace objects...
  • I/art: WaitForGcToComplete blocked for xx.xxxms for cause HeapTrip

Can someone please explain what is going on and how I can get this content to download significantly faster? Is it a memory issue of some sort? Do I need to use a BufferedReader of some sort?

Log messages:
Click here for a log screenshot messages.

Code:
Click here for my code.

1条回答
地球回转人心会变
2楼-- · 2019-04-12 20:48

Finally figured this one out. The problem is that String is an immutable class, meaning garbage collector needed to clear out each String that was created when reading the downloaded content from Java's Heap Memory, which was taking forever.

The fix is to create a new StringBuilder() in the first line of the doInBackground method, use that StringBuilder in place of the String throughout the method, and then at the end, convert the StringBuilder to a String (StringBuilder.toString()).

查看更多
登录 后发表回答