Overhead of Services in Android (how many should I create) - android

Does anybody know how big the overhead for services in Android is.
And if there are any other argument helping me with the following design decision.
I have two SQLite Dbs, one storing actual data (basically read only product inventory), the other storing settings, lists of selected items, etc.
Now I created a service to take care of manageing these databases, for two main reasons:
I want to be able to "save on close" (settings), which is possible with the onDestroy
It takes some time to load the data, so a quick close of the app keeps the data in memory
From a design perspective, I could either:
Create one service handling both DBs
Create two services, each handling one DB
It feels cleaner to create a seperate service for each DB, e.g. extending a generic base class to take care of shutdown, timers, etc. It also allows me to configure them independent (which is NOT required right now).
On the other hand, I do not want to start going down this road, and then, when I am used to doing stuff like this in "services" discovering that there is a limit of 3 or 5 services.
So how is the Overhead of e.g. 5 running services, vs. one service hosting 5 different features? Any ideas?

The number of services effectively supported by Android should be nothing to worry about in your situation. Having seen lists of running services in some task managers, I tend to say that up to ~100 "running" services should be no problem on most devices.
However, I'm not sure if what you're trying to do actually should be implemented in a service. Can you elaborate why you think you need a service?
I want to be able to "save on close" (settings), which is possible with the onDestroy
Can't you do this in your normal Activity lifecycle callbacks?
It takes some time to load the data, so a quick close of the app keeps the data in memory
What do you mean by "quick close"? Are you trying to build some sort of cache for the DB data?

From the Android dev docs...
Use services sparingly
http://developer.android.com/training/articles/memory.html#Services

If services are RemoteServices then they are launched in a separate process which add overhead and is memory intensive.
Try using a single service for both the scenarios.

Related

How to prevent memory leak in android?

I started a few months ago to program in android doing my first app that consists of taking orders like a waiters app.
As it was the first app you can imagine that i wasn't aiming for the optimization but that was a big mistake. I've deployed app in some restaurants and till this moment all was going well.
The issue:
Now the app was installed in a restaurant where they take a lot of orders for a single table they can get up to 10 minutes where they take orders and yesterday i've got a call where they said that the app was crashing on tables with a lot of people.
Now i'm trying to simulate what happened in my company.
The App:
The app consist of the Main screen where the user can choose to enter in settings or in the orders then there is another "login" activity and then the "main" where there is an alert that asks for the number of table then the waiter takes order and send it.
After sending i'm just "resetting" the activity or better by clearing the recyclerView out of items and settings all values to 0 but i think that it's produce a "little" memory leak.
Conclusion:
Now i would have as more as possible suggestions on how can i improve my app performance or better how could i prevent memory leak or even if it's possible to "recreate" the activity in someway after the waiters send the receipt so i could "save" some memory or idk.
Actually here is a screen of profiling, i don't know it it's could help
Good practices to avoid memory leaks IMHO:
avoid storing android context statically in helper or data classes
remember to unregister broadcast receivers once their job it's finished. A good practice is to register inside onResume() method and unregister inside onPause() method
prefer the usage of LiveData for your "model" classes
use LeakCanary library to detect any potential leak
be careful with the usage of static variables, remember to set them to null once are no longer useful to the application, that way they would be eligible to be garbage collected.
You can find an interesting article about this topic on Medium
First of all you seem to not have a CrashReport library on your app. So first thing to do is to add Crashlytics to your app.
Get clear, actionable insight into app issues with this powerful crash reporting solution for Android
Then if you think you have leaks on your app, I suggest you use CanaryLeak
A memory leak detection library for Android and Java.
Once Crashlytics in place you will know where the issue comes from. It can give you as far as the line of code that crashes your app.
Do you have any subscribers to events which is not unsubscribed? This is a common pitfall for memory leaks. I suggest that you use a memory profiler to profile the memory usage. This article gives you an introduction if you are using android studio:
https://developer.android.com/studio/profile/memory-profiler
As highlighted by the others, without specifics, it is hard to know what is the cause of the memory leak.
I wrote apps for Android tablet at restaurants in Beijing (Lily's American Diners), and I struggled with leaks for a long time. The problem is you have tablets Android tablets running for 14 hours a day so you have to have very robust architecture so things do leak and get torn down by the OS.
1) Canaryleak and Crashylytics are good ideas. I used ACRA.
2) Try to avoid popups, global variables, all the obvious things.
3) I use a background service to handle uploading data to the server, downloading menus from the server, printing to POS printers.
4) For network operations, use OKHTTP, it makes all the Async network operations cleaner.
5) For image loading, use Square Picasso. it makes all the image cashing cleaner.
6) In your lifecycle architecture,minimize activities. I use 1 single instance activity for the splash screen initial load and 1 single instance activity if they choose to do the manager operations, setttings, etc., then, there is 1 activity that runs the whole day long and handles everything. Within that activity, I use a ViewFlipper to quickly change "pages" (views) for each of the following operations:
a) choosing items from the menu
b) showing the ticket of selected items
c) showing large pics of the dish or special options for each dish
d) showing a successful sent order
e) showing an unsuccessfully sent order
f) showing the choose table screen for customers or waiters, whoever does it.
g) showing daily specials
The other big issue is persistent storage so orders and menus don't get lost, etc during the long running operation of these kinds of apps. i made extensive use of shared preferences.
Good luck.
There are many different possibilities, for example:
Database remains opened
Data cannot encapsulate properly.
From Shared Preference
These are common possibilities from where the data may leak.

Multiple intent services and activities accessing the same data

I need a shared list of computers made available to all my app's activities. The list of computers needs to be upated by two background tasks of some kind, one that blocks on a socket waiting to receive data, and another task that periodically purges computers from the list. What is the proper Android way of doing this to avoid running into activity lifecycle problems? Specifically,
Can/should I use a singleton to maintain and expose the list to the activities and background tasks? (I'm familiar with thread synchronization issues and am prepared to deal with that.)
Can/should I use the IntentService class (two separate instances for the work I need to carry out) or is there a better way? Do I need to use a BroadcastReceiver in that case or could I still store the list in some common place, like a singleton?
How do I avoid keeping my services running when my application is put in the background?
Updated answer for updated question
You can use a Singleton if you don't have a problem with losing your data when your app get's killed (e.g. when you can rebuild the data on restart). In this case you should check that all your components run in the same process (which is default).
You should not use IntentService for intra-app-communication, however bound Services might be an option here
If you bind services from an Activity and unbind them in onPause, they get automatically stopped (if there are no other bound contexts and they weren't started with startService)
If you think your tasks are too complex to accomplish in the same Service, I would recommend two Services bound by an Activity and backed by a ContentProvider which e.g. can be backed by a database.
Old answer
The issues you expierenced might be a problem of Thread-safety (or the lack of it)
Two Intent Services just to share data within an application is definetly way over the target
A broadcast is the right way to notify components of a change
You might want to take a look at Content Providers
Another solution might be a service, which can be bound by all your other components
You can use Database to maintain the UDP packets with timestamp.
Also periodically check the last sync time from Database to check whether UDP packet is coming or not. Hope you know how to use Database.

In Android, should a contact sync adapter run in a separate process?

In my app, I'm using a contact sync adapter, but it has a lot of information that it shares with the main app. There are settings that the adapter needs to work proplery (like login information and if the user changes any sync settings), so I currently have it running in the same process, and it communicates with the main ap using getApplicationContext(), and then I have some shared variables in the Application that the sync adapter is using during the sync process.
But in the training document, and a few tutorials online, the sample adapter is set up to run in its own process -- it's using android:process=":sync" in the manifest. Is that necessary? And if it does run in a separate process, how can I communicate back to the main app?
In our context, due to fast searching requirement, we are using remote service to hold a huge database in memory.
The reason we are using remote service, instead of local service is that, we believe running the service in separate process, will make us harder to hit maximum memory per process limitation (The limitation is vary based on different devices and OS version).
In our initial design, we are using AIDL. Later, we switch to Messenger. I cannot recall the reason behind. I will check back our source code history log to figure out why. But, I think it is mostly, Messenger is less complicated than AIDL, and we do not need the multi-thread capability provided by AIDL.
Running Service in its own process may be helpful
1) if you want your service to withstand your main app's process destruction (but START_STICKY is more than enough for that case),
2) if you'd like to designate this process for all "sync" tasks of your application (as stated in the tutorial),
3) if you want other apps to use your Service.
To communicate with the Service running in separate process, you use Bound Services.
However, running Service in separate process increases the complexity of communicating with it, so consider if any of cases mentioned above relates to your app purposes.
I think it should be separated, but it's not required.
In general, separating a Service process is well worth to consider if it may be used independently from system components or other applications. In this perspective, the lifecycle of the process should be managed independently from other components such as Activity in the same app, so Android can mark which process is currently used easily and precisely to decide which process to be killed in case of a memory shortage. Also the service can keep running even if the front activity crashed unexpectedly.
It's hard to maintain sharing data between separate processes. For login credentials and preferences, I guess you may go with a combination of SharedPreferences and OnSharedPreferenceChangeListener.
When the application starts, it may cache different things, in particular for the UI. By splitting the sync logic in a different process, you allow the UI process to be killed when the device is running low in memory, which will free these UI caches.
Hence, this technique is primarily of interest to apps that run services for a long time. Typical examples:
the service that plays music in a music app
the service that uploads the video in Youtube
However:
this increases the complexity of the app
if done incorrectly, it can actually increase the overall memory footprint of the app

When to use and when not to use a Service in Android

I have been developing for Android for little less then 2 years, and I am still puzzled by this seemingly simple question.
When should one implement a service?
From my experience there are some rare cases but I am questioning this because on every phone there are quite a lot of them running and I doubt it's just a poor application design.
This is essentially core of my question but following are some of my experiences and thoughts about the subject which can explain my question in more detail.
In all apps that I have developed only one really required a service. It was a background sound recorder and I was using it as Foreground service with notification since I wanted buttons to be able to control it (like music players do for example).
Except this I never really saw a requirement for the constantly running service because:
A) Intent listeners (Manifest registered BroadcastReceivers) are quite a useful feature and using them as you know is usually enough for many use-cases (for example showing notifications).
B) If scheduled execution is a must one can subscribe to alarm events.
C) I know that service in Android is quite different then for example in Windows since in Android services are just a "package" to organize your code in and have a the system manage the lifetime of the object. Services use the Main Thread but it's customary to spawn new threads in them.
D) In the development documentation services are suggested for network communication and background calculations but I don't get why you should not just use AsyncTasks for that. I am a big fan of these and use them extensively for lot of things from downloading data from the internet to doing FFT calculations under time critical conditions.
E) I get the usefulness of Foreground services but why are people using background services so much (excluding the system apps).
Those are my thoughts about the SERVICE and I hope someone with more experience will be able to explain these PROS and CONS (along with others that I probably missed).
When should one implement a service?
When you have work -- delivering value to the user -- that:
Needs some time to complete, perhaps longer than you have time for in the component wishing the work to be done, or
Is delivering that value under user control (e.g., music player, controlled by play/pause buttons in a UI), or
In rare cases, needs to be running continuously, as it delivers value continuously
there are quite a lot of them running and I doubt it's just a poor application design
Some are likely to be poor implementations, either due to technical misunderstandings, or other concerns (e.g., making marketing happy) trumping making users happy.
It was a background sound recorder and I was using it as Foreground service with notification since I wanted buttons to be able to control it (like music players do for example)
That is a reasonable use for a service, IMHO.
Intent listeners are quite a useful feature and using them as you know is usually enough for many use-cases (for example showing notifications)
I assume that by "Intent listeners" you mean manifest-registered BroadcastReceivers. In that case, if the work to be done by the BroadcastReceiver will take more than a millisecond, that work should be delegated to an IntentService for completion. onReceive() is called on the main application thread, and it is not safe for a manifest-registered BroadcastReceiver to fork a bare thread, as the process could go away shortly after onReceive() returns. However, in these cases, the service is usually short-lived (e.g., do some network I/O and disk I/O, then go away).
In the development documentation services are suggested for network communication and background calculations but I don't get why you should not just use AsyncTasks for that
An AsyncTask is a fine solution for background work that is:
Requested by the UI (activity or fragment), and
Will take less than a second or so, and
Is non-critical
For example, if you are downloading avatars to show in a ListView, AsyncTask is probably a fine choice, whether you use them directly or use some image-fetching library that uses them internally.
Conversely, if the user buys an MP3 through your app, and you need to download that MP3 file, an AsyncTask is not a good solution. That could easily take over a second. While the download is going on, the user could switch away from the app (e.g., press HOME). At that point, your process is eligible to be terminated... perhaps before your download is complete. Using an IntentService to manage the download is a signal to the OS that you are really doing work here, adding value to the user, and so the process will be left alone for a little while.
Note that if the background work might take 15+ seconds, WakefulBroadcastReceiver or my WakefulIntentService is probably a good idea, so the device does not fall asleep while you are trying to wrap up this bit of work.
I can name some of the Service uses from my experience:
to implement
location listener,
sound module, generating various voices
in app content updates,
API, provide services to other apps
in app billing
Communication with webservices (if requests frequency is high)
actually (excluding 5.) they all are working for the whole app duration, they are using some of the other android services, also they manage their state. I suppose one of the important thing here is state management during application life cycle changes.
I prefer to look at AsyncTasks in a same way as Executors (ExecutorService), they should be executed sequentially and for small tasks.
In the android website, you can find a table when to use Service, Thread, or WorkManager (the new API for scheduling jobs, currently in alpha as of this comment posted). https://developer.android.com/guide/background/#table-choose
The website also state that you need to use started service only as last resort. The Android platform may not support started services in the future. Refer to this link https://developer.android.com/topic/performance/scheduling#services
You should avoid using started services that run perpetually or perform periodic work, since they continue to use device resources even when they aren't performing useful tasks. Instead, you should use other solutions that this page describes, and that provide native lifecycle management. Use started services only as a last resort. The Android platform may not support started services in the future.
If you consider UI and bound services, u would think that both can exist and not be doing anything for certian periods. In such scenarios, your UI can be recreated a lot of times however service does not. And this is where service is important. Lets say you are processing images and then rotate device you want processing to continue while UI is being recreated. You recording a voice and then rotate device. These are one of the places where I find service very important. (Having lot of heavy data processing, interaction with web, that could be few seconds)

Proper use of Android Services with RESTful API

I'm currently learning to develop for Android and I'm having a somewhat hard time figuring out when and how to use services. I have already seen the numerous questions asked about very similar things, but I can't quite find the exact answer to my questions.
I have an app which talks to a restful api. I fetch several lists which I would like to cache in memory and only update if the user hits a refresh button, or certain activities are created. If a list is refreshed, sometimes several activities need to be notified, so that they update their content (if they are on screen at the time). I store the data I retrieve in value objects.
On a non-android app I would usually create a sort of dataproxy class in a singleton pattern. I could ask the dataproxy to update its data via http request, and then it would send some kind of system-wide notification as soon as the data is changed, so the interested views can all be updated. I hope this makes sense.
My question is now: How do I do this the android way? Do I bind and unbind to a dataproxy service, which I can actively ask to fetch certain data? Should I do my non-persistent caching in this service or somewhere else? Do I need AIDL, or can I just use normal objects for moving data between a service and an activity? Although I find the android dev guide pretty well written and useful, I haven't found much information on services best practice.
Thank you in advance!
How do I do this the android way?
You assume that there is a single "android way".
Do I bind and unbind to a dataproxy service, which I can actively ask to fetch certain data?
You can either bind, or send commands via startService().
Should I do my non-persistent caching in this service or somewhere else?
If you're sure that you only want it to be in RAM, I'd lean towards static data members. Make the service be the "do-er", not the store.
That being said, I'd treat this more as a synchronization pattern, with the real store being a database or directory, with a cache in RAM. Users will find this less frustrating -- under your current plan, if they are in your app, then take a phone call for a while, they'll have to have you download all the data again.
Do I need AIDL, or can I just use normal objects for moving data between a service and an activity?
If they are all in the same process, normal objects is fine via binding, or use Intent extras for the command pattern.
Now, back to:
How do I do this the android way?
Option #1: Wrap your store in a ContentProvider and use ContentObserver for changes.
Option #2: Have your service send a broadcast to your package when the data changes, so the foreground activity can find out about the change via a BroadcastReceiver registered via registerReceiver(). Other activities simply grab a fresh look at the data in onResume() -- the only one that immediately needs to know of the data change is the one the user is interacting with, if any.
Option #3: Use the binding pattern with the service, and have the foreground activity register a listener with the service. The service calls the listener when data is updated. Once again, ather activities simply grab a fresh look at the data in onResume()
Option #4: Cook up your own listener system as part of your static data members, being very very careful to avoid memory leaks (e.g., static reference to an activity or service that is destroyed, preventing its garbage collection).
There are probably other options, but this should get you started.
The Google IO session mentioned by Andrew Halloran:
http://www.google.com/events/io/2010/sessions/developing-RESTful-android-apps.html
Check out the Google I/O session videos. I implemented REST api calls the easy BUT wrong way. It wasn't until watching this Google I/O video that I understood where I went wrong. It's not as simple as putting together an AsyncTask with a HttpUrlConnection get/put call.

Categories

Resources