I am currently developing Android app, it needs download content from internet. I use thread to do that and then call runOnUiThread method to update GUI.
Rather than starting a new thread for every refresh action I would create a single thread for all the background download work that loops and downloads content as lined up in a queue. That ensures that you don't download content concurrently and also saves resources.
In the GUI you simply queue a refresh request whenever the user prompts you to and can abort a running download by calling HttpRequestBase.abort
on the http method instance. The background thread should receive and catch a SocketException
and move on to the next queued request.
To end the background thread you just have to end its loop. You can use the Looper
and Handler
classes to help you with all of the above, the HandlerThread
class you mentioned is simply a handy class to create a thread that has a Looper
.
The problem with interrupt
ing a thread is that it won't break you out of a blocking I/O request and handling an InterruptException
correctly can be complicated. So depending on the situation I would say yes, it is better practice to end the thread by returning from its run
method.
i discover this week AsyncTask, and i replace Thread by AsyncTask in some place in my program,
You have doc & sample here, really easy to use :
http://developer.android.com/reference/android/os/AsyncTask.html
when i was using thread GUI was lock, and now it's not locked.
And it's possible to cancel a AsyncTask (but i never try)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With