Android: can't decide how to manage background task - android

I have a task which I need to run in the background in my Android app. It reads data over the network and populates a database. It can take several minutes to run.
Once it's started, it needs to complete successfully without interruption. (Otherwise I'll end up with a broken half-populated database.) I realise I can never guarantee it will always complete, but I want to make it as hard as possible for the system to kill off this task. For safety I guess I will have it populate a temporary database, and then only swap out the old database for the new one on successful completion of the import.
It's a modal operation; it does not make sense for the user to be interacting with the app while the import is in progress.
My first attempt is using an ASyncTask with a Progress dialog to achieve the modality, but this obviously breaks the "don't interrupt" requirement. I could work around the screen-rotation issue with ASyncTasks, but I don't think that goes far enough.
At the moment I'm not sure if this should be an ASyncTask, a Service, an IntentService, some combination of these, or something else entirely. Can you help me decide?

I'd run it as a service and additionally I'd also have a clean SQLite DB on my server populated with the data the clients are going to retrieve so I can generate a kind of signature. Have the clients check for the correct signature of the DB. If the signature is not matching the servers signature then reinitialize the database filling process.
This is just an idea tho. I have no idea whether it'd be possible with what you are trying to do or not.

You are better off with services in that case. The Android runtime will leave it alone working as long as enough memory is available. In the case it kills the service, you can save the state in a bundle, and the system will restart the process as soon as possible, so you can resume the process, if possible for your solution:
Android Fundamentals, Service Section
Then it is easy to communicate with the service, like showing the progress/ notifications etc, using a handle registry like proposes by Mark Bredy in his Android Service Prototype

Related

What will happen when my application swipe( killed) from list of recent applications?

My application is receiving calls(using CsipSimple) it's working fine,
But my problem is when i am getting call, On that time, am killing the
application from list of recent applications.calling notification also killing(Not showing).
What will Happen when swiping the app from recent applications?
is there any override method to be invoked?
What is the behavior of 'SERVICE' Component?
All objects going to be null?
Please guide me, Your help will be appreciated.Thank you in advance.
When your app is killed by that method, it is force Garbage Collected, so every value that wasn't stored in a Db or in Shared Preferences or some form of storing data would be deleted with no chance of recovery. If you want your app to perhaps restart in the background to do background processes when it is killed, you would need to add a Service that would do minor things like send little data here and there, if you hug too much resources even with a service, Android now does a good job of cutting you off completely. And I heard there could possibly be a feature that sorts of blacklists you.
This tutorial does a good job of explicitly explaining the Service type.
http://www.vogella.com/tutorials/AndroidServices/article.html
try using no. 5 in the Table of Content of the tutorial.
Android gives a guide on what to do and what not to do when using a service with this https://developer.android.com/training/best-background.html
And this is a more specific Tutorial with explicit details on doing downloads from
http://javatechig.com/android/creating-a-background-service-in-android

Downloading data on Android app first run

I have a language translation app that needs to download some initial data on the first run. When the app is first launched, the first step is to get a list of currently supported languages from the server. The user then selects which they wish to install, and the rest of the tables are then downloaded.
I check if the languages are present in the local db, and if not, connect to the server and download them as JSON. The user cannot do anything until this data is retrieved from the server.
If there is no network connection, a dialog should prompt the user to go to their WIFI settings. If there is a network error with the download, another dialog would then prompt the user to retry now, or wait until later. If the download succeeds, a new Intent is launched to send them to choose the languages to install.
I have this mostly functioning (my AlertDialogs aren't showing), but the question is whether this is the proper way to accomplish this. I've currently set it up as an AsyncTask, but I've seen plenty of posts with responses yelling about how an AsyncTask should not be used when the UI depends on it. Fair enough, but an AsyncTask seems to be the recommended method for downloading data.
Is an AsyncTask the correct way to download the data, or is there a preferred alternative?
How to best deal with this on the UI, as it depends on this data? A splash screen? I'd rather not, but it seems something should be there, and I need somewhere to display the AlertDialogs if necessary.
Is an AsyncTask the correct way to download the data, or is there a preferred alternative?
No, AsyncTask is not a good solution for networking because:
You need a component from where you start this task. Activity is not a good choice because your network request will be tied to the UI and it will be hard to handle screen rotations, etc.
AsyncTask works on a global serial executor by default. It will block all other async tasks in the app until it finishes. So you will have to provide your own executor to avoid that.
The process level would be Background Process according to http://developer.android.com/guide/components/processes-and-threads.html
With a Service you can achieve Service Process which is better.
Use Service instead. You can implement any threading you want inside. You can use a regular Thread, a ThreadPoolExecutor, a Handler, or some third party solution. Service provides you great flexibility.
Regarding your second question, take a look at material design spec first: https://www.google.com/design/spec/material-design/introduction.html
Come up with some ideas and then ask a separate question if that is still not clear.

How to structure an application properly on background processes

I have an application that uses a webservice to get information and save the changes made ​​by the user.
currently I have one service that runs while the application is open, and it has public methods for each operation. the trouble is that service is growing considerably and I'm thinking refactor, but the question is what is the best way?
I can think of the following options:
Deferred services the current service and that all are initialized at boot time application
Create small services and that these are initialized by local broadcast
although I have doubts about performance. Can give me some clue or example about which method is better, do not really care that changes are instantly synchronized, these are stored locally and can be synchronized when possible. Data sent are not many, so the synchronization is relatively fast
Synchronization processes are something like
Check if there is new data (I have several types of data, these are the ones that are growing)
Synchronize user preferences
Most likely there's no point of having Service running all the time. Instead, I'd go for IntentService. If possible, I'd also condifer using push notification (like GCM) so the server could let my app know that there's new data to fetch (or maybe even send it to me if you'd fit in the GCM payload limit).

Is it possible to save to database right before an Android application closes?

In an Android library I'm writing, I have a queue which has elements constantly being enqueued and dequeued. A required specification is that no elements in the queue are lost. So, if the application closes, I have to save the queue somehow.
I have two options:
1) Ideally, I could save the queue into a SQLite database when the application closes. However, I'm not sure how to detect this, or even if it's possible. In this manner, I can reload the queue elements which were never dequeued back into the queue the next time the app opens. If someone could tell me how to detect the application close from a library (not an Activity), it would be very helpful.
2) If that's not possible, I could write the queue straight into the database for every insertion and removal. However, this is terribly inefficient, and is too slow for my library.
What's the best way to handle this problem?
So, if the application closes, I have to save the queue somehow.
Update the persistent store when entries are added to the queue. For example, Square's Tape offers a persistent queue implementation.
However, I'm not sure how to detect this, or even if it's possible.
It is not possible. The closest thing that Android has to "application closes" is when the process is terminated, and you are not notified about this in advance.
However, this is terribly inefficient, and is too slow for my library.
It works for Square. Their app has been downloaded millions of times and has a ~4.5 star rating on the Play Store, and it uses Tape.
Note that AFAIK Tape does not write to SQLite, though.
You can't detect when an Application is closed, however this work should be done in a Service in which you can override the onDestroy() method.
In onPause event, do the following
if (isFinishing()) // This tells you the app is closing.
Only in this case save it.

When will one need to create a separate process in a Application?

I was reading a article in Android developer blog Process and Threads which talks about creating new process for specific component of Application. But I failed to understand when will creating a new process in my application becomes a absolute need. Could you please help me understand following doubts I have in this regard.
When as a developer I should feel I need to have a separate process for a Android component/s?
Does introducing a new process has any side effect on application's overall performance?
Any other info is greatly appreciated.
Thanks,
SKU
Having a separate process can be useful if there are components of your application that do not necessarily need to both be running to be useful to the user, and the background task is critical to application "correctness" (either now or in the future). The classic example of this is an app that has a service where the service saves or uploads some data that is critical to your application (critical meaning the only way to get the data back is to have the user re-enter it!). The service might be responsible for doing something like uploading or saving data, while the activity is just the interface for the user. So developers should decouple these two components to prevent problems that may arise from my next point..
Android was designed to run in a resource (especially memory) constrained environment, so processes deemed unimportant are killed periodically to open up memory for important ones by the "low memory killer" (LMK) (if you Google this you'll get tons of information on the topic). Things like foreground processes are understandably given a higher priority since they're currently in use, but they're sometimes killed off as well for reasons like consuming too much memory. Now, imagine you need to save off some data to a database after the user does something in the app and you use a service to do so to ensure that it is done even if the user navigates away from the app. Unless you create the service in its own process the process containing both the activity and the service is likely to be killed since the process belongs to a non-foreground activity.
However it is not always necessary to place the service in its own process, oftentimes simply giving the service its own thread will suffice; it's very application specific. I would only place a service in its own process if it took longer than maybe a few seconds (long enough for the user to navigate away from my application and for the LMK to step in) to perform some task in the background and that task related to the "correctness" of my application (I.E. saving data for later). For something like caching, stick to threads, since if the process gets prematurely killed you can just recreate that data later.
Another reason to have a separate process is if you're running a global service (a service that can be used by applications other than your own) that maybe you provide an interface with via an Activity for configuration.
As for the performance question, there will definitely be a performance hit for something like this. Interprocess communication is not cheap, so you should really only use a separate process if you fit into a specific use case, like the ones mentioned above. Also, there's a certain amount of memory overhead for maintaining a process, so that's another performance hit.
1.)You need to do something on seperate process or thread when you don't want your app to behave slowly. As by introducing threads you force your app not to run on UI thread. Thus making your app responsive to other events. For Example : you can use threads when you have to fetch some data from web service so that it happens in background and doesn't effect your app.
2.)Threads should not be used..We should use AsyncTask or loaders rather in android.
1.) In android 4.0 (and possibly 3.0, not sure though) The device does not let you use the HTTP Agent in the main thread, for this slows the UI..
This is when threads come in handy.
Also with the use of functions that need alot of cpu, if these are run in the UI thread, the UI will lag and not respond until the function finishes.
2.) as stated at 1, it will actually improve the visual performance of your app ;)

Categories

Resources