My activity is to download and display announcements (from announcements web-service). In order to keep UI responsive I do following actions in background threads:
1) upload XML (data are stored in XML),
2) process XML,
3) upload images.
Besides, I change priorities of UI and background threads to keep UI thread responsive:
in main thread:
Thread.currentThread().setPriority(10);
in background threads:
Thread.currentThread().setPriority(1);
Each announcement is put into a TableRow and each TableRow is put in TableView using handler. When user scrolls the TableView and is about to reach the end of the table, new rows are added and HTTP-GET for next announcements is sent (+ parcing (using XPath) + image uploading + filling table rows with content).
My problem:
when uploading and parsing is in process user interface is only partially responsive (there are a number of lags 0.1-0.5sec each when user scrolls TableView).
I want to make absolutely smooth scrolling which doesn't depend on data uploading/processing.
What has been done in a wrong way and what else can be done here? For example, if I diminish number of operations in handler, it should improve responsiveness... maybe like that. However, I see no heavy and resource-consuming instructions there.
UPDATE
I rewrote my code using ListView instead of TableLayout, since the former is considerably faster (as it turned out, I didn't know that). But I still have spikes when XML processing and ListView scrolling were going simultaneously. I made 2 experiments:
1) I removed all background processes - new rows were added to ListView upon scrolling down, but no data were processed for those rows (so they remained empty) - such variant worked great, no any spike, UI absolutely responsive.
2) 2nd experiment was to remove calls to ListView updates (XML file was processed but data found weren't passed to ListView adapter) - that time I had spikes. So I conclude those spikes are due to background threads and are not due to UI update calls. How can background threads slow my app if I make them have lower priority than priority of main one?
Is
Thread.currentThread().setPriority(some_int);
a correct way to set thread priority?
At some point, the UI thread needs to add these new objects, create new UI objects in memory, and add them to the draw list. What you could try is to pre-allocate as much memory as you need by making a lot of invisible Table Rows in your UI. This might solve some issues, as potentially the UI thread is trying to reallocate it's memory to make room for your new TableRows.
Also, you could try to use Thread.yield(), in your background threads. This informs the android OS that this thread is ready, and if needed allows the resume of the UI thread (if the UI thread is idle, it resumes instantly).