AsyncTask stop working android - java

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().

Related

Android run correct background operations

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 !

Is there standard implementation for thread block/resume in java SE?

I need to block execution of a thread until resumed from another thread. So I wrote my own implementation using wait() method. Which seems to be working, but it is far from simple.
Is there any ready to use solution? Preferably in java SE 6? Or do I have to use my own implementation? I couldn't find any.
Update
More specifically. I need work->block->external release->work->end behavior from thread 1 and ability to release block from thread 2.
have a a look at the classes in java.util.conucurrent ...
CountDownLatch might be a solution for your problem if i understand your problem correctly.
I need to block execution of a thread until resumed from another thread.
Not enough information. Do you need an on/off switch that is controlled entirely by one thread and obeyed by the other? That might be a good application for a Turnstile: Pause thread from another thread(s) and also stop/start it yet from another thread
Or do you need "one-shot" behavior? (i.e., the "background" thread does one thing each time the "foreground" thread gives it permission to go.) That would be a good application for a java.util.concurrent.Semaphore.
Or, do you need some other behavior?
using an ExecutorService and calling invokeAll might also be an option.
http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html
this way lets you also specify a timeout in which all tasks should have been finished. Which is generally a very good idea, if you want to have a responsive application.
Inspired by other answers, I found two solutions:
First:
Create Semaphore with no (0) permits:Semaphore semaphore = new Semaphore(0); in first thread. And share reference to it with your second thread.
Do some work in the first thread and call semaphore.acquire(); when you wish to stop execution.
Some time later call semaphore.release(); from second thread to unblock the first one.
Second:
Create CountDownLatch with initial count 1: CountDownLatch countDownLatch = new CountDownLatch (1); And again, share reference to it with both threads.
Call countDownLatch.await(); when you wish to block execution of the first thread.
The first thread can be resumed by calling countDownLatch.countDown(); somewhere in the second thread.

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

To use or not to use a SwingWorker versus a regular Thread

I have a start and stop button. I want to be able to start and stop a task as many times as the user wants to. I was able to get this working properly with a regular thread by doing a wait() when the stop button was pushed and then a notify() when the start button was pushed to start the thread again. This worked great. However... I extended thread. My boss told me to never extend thread and that I should use a SwingWorker. But I noticed that a SwingWorker can only be executed once. Or can it be executed more than once in the same session..?? Can somebody help me in the right direction here?
You very rarely need to extend Thread. What you should do is pass a Runnable to a Thread constructor.
For my tastes SwingWorker adds too much coupling to code, and should be left to demos where it works very well.
You can just create a new instance of your SwingWorker each time you want to run the logic. Personally, I don't see much benefit to SwingWorker for your problem as you described it. Not to say it won't do fine...
You don't need a SwingWorker for what you doing. SwingWorker is used for cases when you have to run something in background thread, update your GUI (like progress) without locking i down.
What you did already is fine.

Threading in Android

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.

Categories

Resources