Threading in Android - java

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.
I placed a refresh menu on it, if user tried to refresh the content, the download thread will be created and started. The problem is that how can I control the thread order, I need to accept the latest request's response and abandon previous thread requests if there were some other requests still running because the request parameters may have been changed by user. Currently I was using a threadId to do this thing, when a thread finished, it will check its threadId, if it was the latest recored one, it then takes control and render the response. My question is that is there any other proper better solution for this?
Do I need to stop threads when user exit the app? I remember that some book said that do not try stop thread manually and wait itself finish is a good practice, is that true? Should I stop them by calling "stop" or "interrupt" method?
I read some documents around threading in Android and found the class HandlerThread, what is it? In what kind of situation I need to use it?

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 interrupting 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)

You can use an IntentService to start your background operations, the service will operate as "work queue processor" and will execute your calls in order.

Related

Android Activity will close Looper & Handler?

Sorry but, I'm quite a bit confused after reading this.
If let say, I have a single Activity and inside it,
I tried to make an inner Class implementing Thread that has looper and handler.
My question is;
If I finish() my activity. Is that close any Looper / Handler i just created last time?
I'm afraid the Thread is still running background altough the Activity is already closed -> ended.
After finish, you don't have to care about Handlers attached to the Main Thread, because it's Looper (and the Thread itself) is managed by the system, and it will quit when it is necessary.
However if the Handler is attached to a separate Looper that is not managed by the system (for example a Thread with a Looper started by you), it will be there in case you have not stopped the relevant Thread (that has the Looper). This true in general for all Threads, the fact that the Thread has a Looper does not change the situation.
So the important think here is to stop every Thread that you started manually.
As an addition:
You can always check your running Threads in Eclipse. Just attach the
debugger and go to the Debug view. All Threads will be listed there.
Take a look at HandlerThread.

Stop the Running Thread in Android?

I am using the thread for login on Server and I want to stop the Thread as the user press back button, I am using stop() and destroy() method and these methods crashing my application, I think these Methods are depreciated that why I am facing this problem. Please Give me the way to stop thread without using stop() and destroy().
Thread.stop() is deprecated since java 1.1 (~17 years ago...). Java of this method explains the reasons in details. This means that you should never call this method. It is still there for backwards compatibility with code written when I was young.
But what to do if you want to "cancel" the operation done in thread? The answer is that you (developer) should care about this yourself. How? It depends on your application. If for example your thread opens i/o stream you can close the stream. If your thread performs series of operations in loop you should check special flag that indicates that thread should exit and update this flag according to needs of your application (in your case when user presses "back" button.
If you still have problem please try to give more details what does your thread do and you will probably get concrete recommendations how to stop it.
For background thread in android try to use service.
I mean you start a service and put a thread in that service.
If you want to stop that service then pressed back button try "Bound" Service. You will get basic idea here.
http://developer.android.com/guide/components/services.html
Only use a thread if you want to do work repeatedly for a long time. I have never needed to start a thread.
You should look at using an AsyncTask.
AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.
It works by using a Thread from the ThreadPool. AsyncTask's are easy to stop, have a method to override for background tasks and one to override for post task work which is suitable for updating the UI (as long as the task was started by the UI thread).

AsyncTask stop working android

Im using lots of AsyncTask for searching,parsing and more in my application. I use AsyncTask because i need to update ui before and after and it pretty easy with it.
The problem is when im proberly using new thread while the old ones didn't die properly and then the thread stop working.
How can i avoid this problem?
May be a better way of doing it is, following a sequential process? Something like this
You start the second asynctask in the onPostExecute() of first. Similarly you start the 3rd asynctask in onPostexecute of second.
So that way, you have more control over it, and the memory is managed well (even in devices having lesser memory).
Thanks
I think you can use signals . i like to use CountDownLatch where you can initialize your latch in one thread and count down it in once it is about to complete the task ., On other thread call await() which will be blocked until previous thread doesn't call countDown().

How to get the main thread in java?

So I have a long running process that I want to encapsulate as a Runnable and dispatch it in a thread. To be more specific, I have a POST web service that creates a file in the file system but the creation of the file can take a very long time.
In the resource method of my web service, I want to be able to dispatch a thread to do the file creation and return the status 200. I don't think I can just do Thread.join because this would mean that the current thread would have to wait for the file creation thread to finish. Instead, I want to join the file creation thread to the main thread. Question is, how do I get the main thread in java?
I am not sure whether I get you right. Here is what I understood:
You want to preform a possibly long running operation (file creation)
you do not want you service method to block while that task is exectued
you want the task executed in a thread that exists outside the boundary/lifetime of the single request.
Am I right so far?
If sou really recommend you look into the newer concepts in java.util.concurrent. The concepts described there should give you enogh information tackkle this
Basic credo: Don't think in threads, think in tasks.
General Book recommendation: Java Concurrency in Practice by Brian Goetz
You will need to process the request asynchronously. A separate thread will be created for doing the heavy work and the request receiving thread will be free to process other requests. Please checkout following articles.
Asynchronous processing in Servlet 3.0
Asynchronous support in Servlet 3.0 spec
Asynchronous Support in Servlet 3.0
When you spawn the file-creation thread, you need to pass it some kind of reference to the parent thread, so it can communicate back (i.e. you provide something to enable a callback).
This could be the actual Thread object (obtained using Thread.currentThread, as someone said in a comment) or some other object that you use to signal when the file-creation thread is done.

How can create a task that pops up the busy label and is cancelable while executing?

I am writing an application in java (1.6) using swing. I currently have a JXBusyLabel on a JXLayer over the content area of my program acting as a busy indicator. I want to provide a way to allow others working with me to create a task that pops up the busy label while it's executing. The catch is, the task must be cancel-able. What is the best way to expose the functionality I desire?
Some ideas I've come up with:
Raw access to setBusy()
This is obviously the easiest for me but requires users know and understand swing threading issues.
public <T> Future<T> execute(Callable<T>)
Wraps the callable in a FutureValue that is run() on a separate thread and returns that FutureValue. The question then becomes, how to keep track of all FutureValue's generated and how to ensure that they can be cancelled. (e.g. cancel(true) always cancels)
I have never used the concurrency package in Java before and it didn't exist back when I 'learned' Java. So I am open to completely new and different ways of implementing this functionality.
Edit:
Clarification of my question. I know about SwingWorker. I've just never used it. What I want to know is this:
Given a Callable (Java version of a closure?) How can I:
Return the value of call() to the user w/o blocking (I think I need to use a Future for this)
Tell the JXLayer to lock (starts painter), execute the supplied callable, and then unlock the JXLayer (stops painter)
Ensure that, no matter what thread calls my busyExec() function, the GUI remains responsive and the background task completes. (NOTE: If I return some sort of Future object and they call get() on the event thread, it can/will block and that is ok)
I guess my main stumbling point is how to implement #2. Should I have busyExec() spin off a new thread that blocks until no background tasks are running? Should I try for some sort of queue. Is there an object that will do this all for me already?
The SwingWorker (of Java 6) implements Future so it seems like it has the ability to cancel tasks via the cancel method.
More information on SwingWorker from The Java Tutorials:
Lesson: Concurrency in Swing
Worker Threads and SwingWorker
Canceling Background Tasks
Okay. For anyone interested here is what I am currently using to implement my request.
I have a method that will take a Callable<T>. It then creates a FutureTask<T> this will be returned to the caller as a this as a Future<T>. The JXBusyLabel and JXLayer are told to start painting and to lock the ui. The FutureValue and Thread (see below) is enqueued in a special list. A Runnable is created that: calls run() on the FutureTask, removes the FutureValue (and thread) from the list, and if the list is empty, unlocks the JXLayer and stops the JXBusyLabel. This Runnable is launched in a new Thread with normal priority.
When the user hits the cancel button. The list is iterated over and the FutureTasks are all canceled and removed from the list if they could be cancelled. First try cancel(false), then cancel(true). If both those means fail, the user is prompted with a warning asking them if they want to Thread.stop() the task and explains that this could make the app unstable. If yes, stop() the thread running the task. This might bring the app down. In all cases, the UI is unlocked.
The documentation for other team members states that they must be aware that the task can be killed. They are not to call get() until isDone() is true. They are explicitly told that this will basically force them to block until the task is done or cancelled. So they can't call it from the event dispatch thread.
Other solutions are still welcome

Categories

Resources