I want to run a network request once user closes an app i.e. onStop and onDestroy is called on app's activity. The problem is I also want to wait for response from server and save some data locally after I get it so the whole procedure may need to be finished after the app is fully closed.
Is there any kind of background service in Android which won't be terminated after app is closed and will be waiting for requests's completion (for some reasonable time at least)?
The solution is Non UI fragment. Here is an example I have created:
https://github.com/kadymuhammad/Non-UI-Fragment .
You can also see this answer https://stackoverflow.com/a/21336010/5186466
Using Asynctask inside a Non UI fragment will continue to run even if the activity is paused but i will stop if the app task stopped.
The perfect solution is to use Service or IntentService classes.
Check this out :
http://www.tutorialspoint.com/android/android_services.htm
Related
I need to upload data to the server repeatedly (say after every 10 minutes). The application will check in the local SQLite DB if there's any unsynced data and will upload it.
If I call an AsyncTask from a Handler repeatedly, will it work even when the app is paused (user navigates to another application)?
How can a Service be used to do this (as service can be run in the background)? Should I use Service or IntentService?
An AsyncTask can run after the calling app is destroyed, however, if it calls onPostExecute() it will crash the app if this method updates the UI. Handlers will also continue to run. However, the JVM process may be killed off at any time. AsyncTask is only supposed to be used for short tasks lasting a few seconds.
A Service is not married to an activity and can outlive it should the app be destroyed. This is where you should be updating your server.
A good tutorial: http://www.vogella.com/tutorials/AndroidServices/article.html
If I call an AsyncTask from a Handler repeatedly, will it work even when the app is paused (user navigates to another application)?
When Android kills an app, can a function be stopped halfway?
"AsyncTask may continue running but may or may not to be fully functional"
How can a Service be used to do this (as service can be run in the background)? Should I use Service or IntentService?
I guess it is better to use service to do this. (i am not so sure anyway)
What is the difference between an IntentService and a Service?
My app is synced with data that is received using an asynctask. When data is received I update a listview and generate a notification. It works great but in case the app is in pause mode, I want only to generate a notification. I want it to continue executing this asynctask even after onPause (if the user switched to another app or pressed the home key).
I read a lot of posts here about how to repeat an action but never saw a reference to what happen when/if the app goes into pause mode.
Why not start a service that runs a background thread?
The service will continue running even if you are not using your app.
When the onStop() of your main activity is called, start the service.
The thread in the service sleeps and every so often connects to the server and checks for updates.
In the onCreate() of the service, start the thread.
In the onStartCommand() (which is called if the service already exists) of the service, check if the thread is alive. If not, start the thread.
Guide for creating services: https://developer.android.com/guide/components/services.html
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
I've created an application which does synchronization with the server.
I've already have a code, which does synchronization once user pressed a button. Now it is time to add Service there.
I have the following questions with regards to the services on android:
will the service be started if user never run application before? (i.e. just installed that)
when the service will be started first time? can I start it from onCreate of the main application?
if user presses Synchronize button in the application, should I start that Service or should I have different process for the same? How can I check then that background synchronization is not happening at the same time?
should I use ASyncTask, even if the service is started as
startService(new Intent(this, ServiceSync.class));
The preferred approach to syncing data in Android is providing a SyncAdapter to perform the sync. You have a very nice summary of the required steps in this post.
You will also find these articles useful.
Edit:
1-2-3: You can use a bound service to manage the interaction and service methods from your activity. You have full working samples in the link provided. Basically, you bind to the service in your activity's onStart method and unbind onStop.
Remember that a service runs on the UI thread, so every time-consuming task such as fetching data over the network must be done in a separate thread.
4: You don't need an AsyncTask here.
I have developed an android 2.1 application. In that I am using AsyncTask for doing background processing. It gets the data from the WebService.
The Problem is : When I leave the application, the background service remains active only.
When I go to Settings->Applications->Running Applications it shows me that the application is running. I have to forcestop that application.
Is there any way to stop the background tasks automatically when user leaves the application ?
AsyncTask has a cancel method (http://developer.android.com/reference/android/os/AsyncTask.html#cancel(boolean) )
Invoke it when your Activity is going to stopped (onStop) state, or maybe paused - onPause depending on your needs, see Activity lifecycle for further explanation here: http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle