How can I run background operations correctly without creating memory leaks or blocking other threads? I first used asynctask, but it uses a thread pool which blocks after 5 tasks in background, and passing weak references don't fix the problem of memory leaks. So I need to transfer data between client and server. I think I should use a class that implements Runnable, and in the activity I start the runnable with ExecutorService (singleThreadExecutor). Then I call submit. I need to get the "Future" from the ExecutorService to be able, to cancel the Thread if the activity call onStop(). If someone has a better solution for this, please help me. The requirements are that it should block other threads, and I should be cancel able if the activity is destroyed.
AsyncTask are for my point of view the best way to deal with Threads.
I don't know what kind of operations you want to do, but check the intent service
Runnable are running on the main thread, so if your activity die, it dies too, or you can wipe the stack handler.removeCallbacksAndMessages(null);.
Play with Thread can be tricky, be aware of what you do :)
In this case, you need to set up a loop that check for interrupted exception :)
Good Luck !
Related
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.
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).
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().
In my android app I am having a thread in which I fetch data from a web service.
So normally it works well, but sometimes if the connection is too slow it kind of hangs.
So is there any way by which I can set some time say 1 min, and if the thread process is not
completed in 1 min. then I would like to stop this thread and display a message to the user that connection is weak/slow and try later.
Please help !!
This is a bad idea. The Thread.stop method is deprecated for good reasons.
I suggest you do the following: Set the network time-outs according to your preferences. If this doesn't help, I suggest that you simply throw away the reference to the thread, (ignore it, let it die out and get garbage collected) and respond with a nice message about network failure. You can very well start a new thread for trying again.
I don't know whether it is supported in Android, but this is exactly what the Future objects returned from an ExecutorService are supposed to do for you. In particular, the cancel(boolean) method can be used to interrupt the task if it has started but not finished.
The tasks should be written to be aware that they may be interrupted, and abort cleanly if they have been. Most of the framework IO methods can be interrupted, so you just need to worry about your own code.
you can use the method : Thread.interrupt();
the method Thread.stop() is deprecated
Create a stop method like this, and call interrupt subsequently.
public void stop() {
Thread currentThread= someThread;
someThread= null;
currentThread.interrupt();
}
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.