Funky Monkey Software | Development, Applications and Chimps

Archive for March 2011

My friend FlabbyRabbit (over at HackThis) recommended that I start blogging about my software projects so that I can help other people with their projects and have something to look back on when everything is finished. For this reason, I've decided to start writing about ADM (my Android Download Manager) as I develop it, documenting my trials and tribulations as I go along.

So What's going on in the world of Android and downloading at the moment? Well, ADM still doesn't really do much in all honesty. Currently, you can add URLs to the database and ADM will check them for you to see if they are online (provided the relevant downloader plugin is installed).

I've had quite a lot of trouble getting the threaded parts of the application to talk to each other in a meaningful way. The need for threads in an application that does a lot of networking is fairly obvious. The user doesn't want to be sat there waiting for something to happen for hours with no progress dialog. Users want results. Therefore, I've put in a system that goes off, downloads the data and then returns it to the GUI thread while the GUI sits with a progress bar, waiting patiently for some useful input.

Unfortunately, my first attempts at this were met with a rather nasty looking exception "CalledFromWrongThreadException". This basically states that a secondary thread is not allowed to alter a view that was created by a primary thread. That is, if Thread A creates a layout and Thread B goes off and does some work, Thread B is not allowed to update the layout directly.

"So how can we get around this?" You might ask. Well Google have kindly provided a nice answer for you: Handlers. Handlers can be used as a 'proxy' between the two threads, passing information from B back to A. Therefore I can simply implement a handler within my first thread with the following code:

    // Define the Handler that receives
    // messages from the thread and
    // update the progress
final Handler handler = new Handler() {
public void handleMessage(Message msg) {
//progress has been made, update the thread GUI
            updateGUI();

}
};

Then, the second thread (thread B) can just call:

Message msg = mHandler.obtainMessage();
msg.arg1 = total;
threadA.handler.sendMessage(msg);

So there you have it. I'll be posting some screenshots of ADM soonish :)

· · · · ·

Theme Design by devolux.nh2.me