What will happen if tasks take long time in onStop() - android

Consider I want to save some data in database in onStop() method of my app and I use AsyncTask to execute queries , or doing any kind of tasks that take long time to perform , so what will happen ? Does activity wait to complete task ? my tasks will be done correctly ?
p.s: I want to do this (saving data in onStop() ) because I dont want to execute query each time user click on a button and change something , I want to do it at the end .
thanks in advance .

An AsyncTask started in onStop will run to completion. There shouldn't be any problems with that. If it takes a really long time it may be restarted before it finishes, which could cause issues in your program depending on how you coded.
If the onStop function itself takes too long, you could trip a watchdog timer and your app may be killed.

First asynctasks are guaranteed to run to completion. but you should note that they can work tightly in synch with UI and you can modify some ui elements in the call backs of asynchTask (onProgressSubmit(), onComplete()...) but if you UI thread is not available on the event of these callbacks you may get an exception.
Second in some rare situations (low memory) in old APIs prior to API11 on stop method may not get called so it is better to save you data in another call back such as (on pause).

Related

Scheduling my AsyncTask

I can see this has been asked before, but I am still struggling to find an answer.
I have a button that executes my AsyncTask. The AsyncTask has a loop that runs in the doInBackground, fetching some data from a server.
This all works really well, but it only works when a button is pushed at the moment. I want this to run every hour, after the button is pushed, until the user presses a second button that stops the process.
Can someone help me with how I can go about executing my AsyncTask every hour please?
I was trying to use a broadcastreceiver, but this wouldn't work and I read that this is not a good idea also.
The AsyncTask has a loop that runs in the doInBackground, fetching some data from a server.
A loop within doInBackground() is not an appropriate use of AsyncTask. AsyncTask is for "transactional" sorts of work, so the AsyncTask's thread can be returned to the thread pool in a timely fashion. If you want to have a Thread that runs for a longer period of time, use a Thread, possibly managed by a Service.
I want this to run every hour, after the button is pushed, until the user presses a second button that stops the process.
Use AlarmManager to set up your every-hour schedule. Please consider using inexact alarms to reduce the battery cost of this work. If you use a _WAKEUP-style alarm (e.g., ELAPSED_REALTIME_WAKEUP), you will need to use a WakefulBroadcastReceiver and an IntentService for your work, moving your doInBackground() logic from the AsyncTask to onHandleIntent() of the IntentService.
This sample project demonstrates the process, though in this case, the events are set up on first run of the app and on reboot. In your case, you would schedule the events and cancel the events when the button is pressed.

Run code on a timer even when app closes bind with ui thread? - Android

I am working on this part of an app where the user is supposed to press a button and then a timer shows up in a ListView. When the timer goes to 0, a method needs to be called. However, if the timer is pressed, the method call is cancelled. This is simple enough right, but the kicker is, the timer countdown and method call need to happen even if the app isnt running. the user can press the button again to add another timer to the listview and have its own proccess.
Ive used AsyncTasks a lot in previous apps and feel like this wouldn't be useful in this situation because to my knowledge the lifecycle of the asynctask is as long as the activity.
Ive looked into handlers and services but haven't really implemented them before, Im not really sure which would be better to handle this.
Im looking for the best way to implement this?
in Actviity.onDestroy include asynchTask.cancel(true). It will trigger InterruptedException which you can catch in AsyncTask doInBackground, so that if the task has been interrupted you don't call the method.
Another way (less efficient and therefore less recommended): before calling the method check if(actvity.isFinishing())

Async task stopped when App terminates (onDestroyed is called)

I have an activity in which I do server sync with a back end server using a subclass of asyctask.
Given it is a network task and might take couple of seconds. I am afraid of the following scenario to take place.
The activity starts, and whenever the asynctask should start to run, it does so.
The onPrexecute() is called, executed, and over. Than the doInBackground() is called, and is done so, however, just when the method is being executed, the user presses the home button and swipes the app from the RECENT APPS. (this ofcourse causes the app to terminate and all the onDestroy methods get called of the alive activities..(Correct me if I'm wrong on this one)).
In my onPostExecute() method, I am inserting the data to DB and updating the VIEWs.
But since the app is 'terminated' the onPostExecute() method never runs.
my questions are :
When the user presses the home button and gets out of the app and swipes the app, is doInBackground halted at that moment ? that is, it is cut in the middle and does not continue what it does ?
What happens to the data that I was going to get from the server and put inside the DB ? Is it advisable to do put the data in the db inside the doInBackground ?
AsyncTask is a background task it will continue to run even if the app is closed and onDestroy() is called. The problem would be when the task enters onPostExecute() and tries to update any views associated with the activity it is bound to, as that activity no longer exists. If you're concerned about this, one thing I've done is to keep a reference to that AsyncTask in the calling activity, and then call the method myAsyncTaskReference.cancel(true) to cancel it in the onDestroy() of the calling activity.
Yes, I would put the DB operations in the doInBackground() method, as that runs in the background on a separate thread, and doesn't require a reference to the app activity.
Have you considered using a service for this type of thing instead? I would strongly recommend an IntentService, which is a subclass of service which is specifically designed to perform a single task in the background (similar to AsyncTask), and then kill itself once completed. It's quite easy to implement and usually only involves overriding one method - onHandleIntent() - which is called when the service starts.
It can handle all your DB operations and it has no reference to an activity and so the problem you're worried about in #1 would never occur. If you need to update a view, you can have your IntentService generate a broadcast once it's completed, and your Activity can register for that broadcast and update it's views accordingly when it receives it. And if your activity is no longer around once the broadcast is sent then it doesn't matter and nothing will fail.
When user presses 'Home', your Activtiy will pause but doInBackground will NOT, but may or may not terminate by system when system feels like it. Activity's onPause will be called. Your Asynctask doInBackGround will NOT halt. It will continue to run until the system kills your App process.
Yes, Db operations can take long. Its advisable to put in doInBackground because it runs on another Thread. onpre/onpostexcute runs on the main thread. If you are worried that System may terminate half way of your db operations, you shouse set Transcation, and only when you are done, you called commit.
Check out this post, I have tested it.
no, it doesn't stop.
It is relly better to put it to datastorage of some kind and then work with it
It is always better to use service for such goals. AsyncTasks just don't fit here. Ask your service to do the work, and then you may start or quit activities as you wish to.
If swiping app from recent stack, it is equivalent to close the app hence it will kill all tasks related to the process so async task will also get killed by the android system. ( even intent service is also get killed)
It is device dependent also. Manufacturers customised removing app from recents behaviour

Detect when Android kills an AsyncTask

If I have an AsyncTask running indefinitely and Android decides it needs to kill the task either to free up memory or because the device is going into sleep mode (the user presses the power button), is there some way within the AsyncTask to get a notice from the OS that it is about to be killed off, so that action can be taken to complete any outstanding task?
To give you a short answer:
an AsyncTask lives as long as the process it is tied to lives. The OS will never kill an AsyncTask if its process is still running (even in background).
Also please note that the AsyncTask runs independently from the Activity that started it. The Activity may be destroyed and the AsyncTask still lives until the process is destroyed.
EDIT
You need to call the isCancelled() inside the doInBackground() method in order to make sure that when the AsyncTask is destroyed by the OS, the doInBackground finishes so that the onCancelled() method is executed.
So to sum it up: in the doInBackground method always check the isCancelled boolean function. If it returns true, then return from the doInBackground. Automatically, the onCancelled function will be executed instead of onPostExecute. There you may place the code you want to execute prior to its death.

Android background thread and activity relation?

My android app uses AsyncTask to download some data from a website.
But when I press the back button of my android device immediately after the activity starts, worker thread's onPostExecute method is called, which is wierd because android called onDestroy method prior to onPostExecute and the onPostExecute method runs on the main UIThread which I think doesn`t exist anymore.
Can anyone help me what I don`t understand?
An AsyncTask is basically executing what you want in the background as a separate thread from the UI. So when you quit the UI this doesn't necessarily mean that you've killed the AsyncTask. It will continue it's regular life cycle and end in onPostExecute. If you want to kill the AsyncTask too then you will have to call the cancel() function for the AsyncTask.
Know this though, you cannot actually kill an AsyncTask this will be done by Android itself. So you will have to wait a while till the current task is killed (if you call cancel()) for you to restart this particular AsyncTask.
You should also read up on onCancelled() methods. For more information checked out the documentation.
If I've made any mistakes, please correct me.

Categories

Resources