Shared publicly  - 
Here's what not to do when writing an Android application, courtesy of Glu Mobile.

The game Bug Village has two services that it tells Android need to always be running. And as if that's not enough, the services are running in different processes. Together these two processes are almost 10MB, which in a lower-end device is 10% or more of the typical available RAM for cached background processes.

This is terribly rude. Don't do this unless you really need to.

If you are writing an Exchange client and need to maintain an active connection with an Exchange server? Yeah, that's why this is possible.

If you are writing a game? No.

And no matter what, for the love of all, don't use two processes to do this.
Georges Berenger's profile photoT Connors's profile photoRandy Sugianto's profile photoYarian Gomez's profile photo
An unconstrained platform can easily and accidentally be abused. With great freedom comes great responsibility, or something like that..
That comment should be copied to the feedback page in the market.
that cat does spread some knowledge about android
Hopefully this will give them a wakeup call.
Chet Haase
Maybe they're just extending the premise of double-buffering to processes.
It would be interesting to know how (and why) the devs finally gave birth to such a monster.
This game has curious permissions too..

Allows an application to have itself started as soon as the system has finished booting. This can make it take longer to start the device and allow the application to slow down the overall device by always running.


Access coarse location sources such as the cellular network database to determine an approximate device location, where available. Malicious applications can use this to determine approximately where you are.

are two reasons I never installed the game..
This is the first time I've seen sloppy design being called "rude". It was narrated in my head by the 90's era Olsen twins. It made me chuckle.

Note to self - Chuckling with a cold-demolished throat sounds terrible.
Tim Huang
It's good to know that "Editors' Choice" is a reliable mark of quality.
At least it's not as rude as Facebook's perma-wakelocks back in 2011... Still, this is the sort of thing I only expect to come from North American carriers at this point.
+David Razloga The first permission is the one it uses to have its services started as soon as you boot your device.

+Matt DelMastro I call this rude because it is being inconsiderate of the user and other applications on the device -- only thinking about your own app without considering how that will impact others by using more RAM that would be better put to use elsewhere.

One of the fun things about a platform is managing the developer's perspective of "my app is the most important thing and all I care about" across all of the applications. :)
I want to +2 this post. Get it?
Weird. On my Galaxy Nexus I don't have that blue glow. It's grey instead o.O
why is that game on "Editor's choice"?
+Dianne Hackborn I didn't mean that I wasn't sure what the permissions were for, just curious for a game to be needing said permissions..
+David Razloga Yeah, a game starting on boot makes no sense. (I'm assuming there is some better way to handle background notifications if it's a multiplayer game of some sort.) Coarse network location makes more sense - a lot of games are location-aware for various reasons, although based on looking at Bug Village, there seems to be no justification for it to have this permission.
Most games that request course location are doing that for their embedded advertising service(s).
I noticed that when i started playing it also. One company that annoys me is gameloft. Every one of their games pauses my google play music playlist on startup no matter if i have sounds for that game turned on or not. I dont play them because of it.
I guess I was a bit too optimistic on that one... (So I guess that means they aren't using AdMob?) - I wonder, if I fake out the location service to report Antarctica, what ads would I get? ;)
this is not the only one, every glu mobile game has services running in background, every glu mobile game is created to squeeze people's wallet, every glu mobile game is a bad copy of original game with the only purpose to gain money. money money money, that's why I hate them, that's why not a single glu mobile game will ever touch my fuckin' phone.
What's better than one instance of Dalvik? Two instances of Dalvik!

I hope you guys sent Glu an official letter or email notifying them of their mistake(s) and giving them a chance to correct it before calling them "rude" in a public post.
The game eats memory like pac-man on power pellets. Even playing it on Chrome it runs a bit slow.
I enjoy seeing bad programming pointed out! Google served!
Services are a really confusing and weird part of Android SDK. For iterprocess communication it makes sense. But the most typical use case is to do some work in background, for example download something.

Is there any reason to use a Service for background work instead of a singleton? Yes, starting a Service decreases the probability that the process will get killed. But thats basically the only advantage of using a Service instead of a singleton. The big drawback is that communicating with a Service (via binding or via broadcasts) is asynchronous.

So I decided to start doing this: when I would normally use a Service I will use a simple singleton. When starting / stopping the background work I will call 2 utility methods: increaseProcessPriority() and decreseProcessPriority(). These methods will start / stop a dummy Service to tell the system not to kill my process.

Do you think this is a good practice +Dianne Hackborn ?
+František Hejl That sounds really dangerous, what if you forget to call decreaseProcessPriority()? And since this is implemented with a service, why not just implement this functionality with a service?
+Jim Avila That's a pretty useless criticism without any information on what is supposedly broken/buggy about them. I've found GTalk to be one of the best written and mobile-optimized IM applications I've used. Compare to, for example, Skype, which seems to use the same protocol on mobile devices as it does on the desktop (Confirmed with Wireshark traces, I'll pull up the link tomorrow and add it to this post), leading to frequent device wakeups and massive battery drain. Similarly, Dianne had very specific technical information on WHY the app in question was badly designed - and anyone who is remotely familiar with how Android works can easily recognize Bug Village's behavior as bad design. I spend most of my time in the kernel and not userspace, and even I can recognize double-popping services as senseless and not justifiable in any way.
+Jim Avila I promise you that we're just as critical of Google's own apps, usually much more so. :)
+Jim Avila I have had no such problems with my tablet, my Galaxy Player 5.0, or any of my phones. The only time I find myself signed out of Google Talk on my phone is when AT&T is having a bad day and dropping network connections right and left - when this happens nothing else (Foursquare, Facebook, the browser) is working right either. The only time I find myself signed out on my tablet is when I take my tablet with me "on the go" and access gtalk too soon after connecting to wifi. Really, tell us how you expect Google Talk to magically communicate with its servers on a wifi device when there is no wifi connection? Mobile network engineers would love to know your secret to always-working wifi that doesn't cost anything - it would change the world! Blame your network provider for providing poor service, not Google.

As to G+ and "tablet layout" - it seems to be laid out just fine on my tablet (Galaxy Tab 10.1). Special "tablet editions" of apps are just a sign that the app was badly designed to begin with and can't properly adapt to larger screens.

I'm beginning to suspect that maybe your tablet is just flaky...
+Dianne Hackborn forgetting stopSelf() is similarly dangerous I guess...

What I want is to get rid of the overhead of using a Service (asynchronous communication, startId, start flags). With your second question, do you suggest this: MySingleton extends Service, use this as a normal Java singleton, not as a Service and call startService(...) and stopSelf() instead of the 2 utility methods? This is simpler and cleaner I admit.

By the way, doing background work (I don't mean just Services) is increadibly tricky to get 100% right on Android, ie taking orientation changes into account and not leaking Context. This should be 10x simpler.
+Jim Avila This post is about applications (especially games) running services and processes, consuming device resources, when they don't need to. Could you please not hijack it for unrelated stuff? (This is also rude, btw.)
+František Hejl I really wouldn't worry about overhead. There are a couple IPCs that happen when you do startService() and stopService(), but you'd need an IPC or two anyway to tell the system process to call into the system to have it keep your process around. Unless you are starting and stopping a service multiple times per second, the overhead is just not significant.

It is hard to address doing background work without a more specific description. If your background work is something like downloading a file, the natural way to do this is with a Service, and there should be no issue with orientation changes because only activities are restarted. You have already isolated your persistent state in a service; if your activity wants to show UI about that state, whatever the current instance is can just bind to the service to make calls on it. (And have a look at the current sample code in Service for doing this, if you know the two are in the same process there is no aidl or anything it is very simple.)

If your background work is tied to an activity, then an easy way to do this is to encapsulated it in a Fragment (this doesn't need to generate a UI) and use Fragment.setRetainInstance().
+Dianne Hackborn I love you! Anyone who's ever heard of Android should follow you and all of +Glu Mobile games are this way along with others that tap joy in general promote for glu points 
Thank you +Dianne Hackborn for posting about that. This is exactly why I have uninstalled all my Glu Mobile games... I am strongly suspecting they are doing that for actually contacting some backend servers (for Ads or other stuff).

And btw Glu is also pushing their Ads in the notification area (See Contract Killer: Zombies)
I am mad at the number of apps abusing services (ie. needlessly using them), and also abusing start on boot (often just to check their settings only to see they need to do nothing).
And yes Services may be needed, but for example, why the stock email app always runs in background when I have an exchange account defined, but explicitly set updates to manual only, no sync?! I have to delete the account to avoid it being restarted!
Same problem for a lot of apps (Plume, Listen, Beautiful Widgets even with no widget installed,...)
And about unneeded start on boot, developers often argue "do not worry, it does not do anything so won't consume resources" .... but yes it does (especially memory), and when you have 20 apps started on boot, even to do nothing, it hurts (and they can even get killed and restarted because of scarce memory ). Same abuse is seen with events like connectivity change,...
I end up using "Autostart" with root to unsubscribe some apps to some events... sad.
Notification ads? That explains the second service probably. Evil!
I congratulate +Dianne Hackborn for calling +Glu Mobile out on this. But this doesn't look good for editors choice apps. Almost every app on the list makes the same or similar mistakes. You should make this a regular article, calling out "rude" apps, and don't give them editors choice if they are not well written apps/games.
Glu stuff really does seem... needy. Once you install any of their apps, your notification bar is spammed heavily. They make some great games, they look and play really well, it's the extra stuff that puts me off wanting to install new games from them
All of those processes make me don't want to install Glu game anymore, install like 5 of them and you're fucked
That's where I am thankful for Android's sandboxing and permissions system. You can spot apps like that right before installing them. I cannot count how many apps I wanted to install but finally renounced because they wanted to access my address book or phone number for no good reason. Now image how much crap must be installed on systems that do not enforce such fine-grained permissions.

My only concern is that phone state and phone number should be split into two separate permissions.
That's every Glu game for you. They should be banned from the market if you ask me.
Don't need banning, just shaming a bit so they get better hopefully. The games they produce ARE good
The permission thing can also be troublesome the other way around: my player offers an alarm clock, and since AlarmManager tasks aren't restored at reboots it needs a quick check at startup. But people think I'd do all kinds of evil with it... Similar goes for phone status. If the music should be paused during a call (esp. on devices with older versions than FroYo), it needs a permission that also would allow to get the caller's phone number...

The Google+ app sometimes transfers about 20MB in background, even if I didn't even start it that day. IMHO that's rude, too. My data limit is reached pretty fast thanks to that, and it probably drains more battery than an unnecessary service doing nothing...
+Mirko Schenk that is probably instant photo uploads or update checks. Check your sync settings and only download updates and upload photos over Wi-Fi. Going over your limit is no ones fault but your own.
+Stewart Gateley I turned off instant photo upload and notifications, and I run the app very rarely when there's no WLAN. It seems to do scheduled background updates, and there's no option to turn that off.
Ironically, Google Maps is running 3 services right now on my Galaxy Nexus, eating up 15 mb.
+Dianne Hackborn - I fully agree. I've just never heard it characterized quite like that before. It was cute and caught me off guard.
Why the user cannot choose the active service?
I'd suggest a way that the system gives automatically a rating based on efficency (resource consumption and so on..) of the app. It would be as important as users ratings
+Dianne Hackborn you should definitely do a roundup of offenders that do this also why does 3 processes constantly run under Google services? I have an idea as to what they are but would like to hear from you also why is maps always caching 3 separate things when I've never opened it not use latitude?
+Anthony Garrett a quick look at my running apps shows Google Services using two background services constantly, and a third one that starts and stops itself repeatedly.

The first, NetworkLocationService. Since I have network location always on makes sense. Presumably polling location so that apps can more reliably use last known location or 3rd party location updates. I would rather have 1 Google service than 100 network aware apps all running their own location service. Though Google Maps runs a persistent NetworkLocationService as well that cannot be stopped. Another editors choice app rudely using resources?

The second service is Google Messaging Framework. This is C2DM, aka push notifications and other xmpp packets Google uses to communicate with the Google apps on your phone, such as Android Market. Again, I would rather have 1 Google service and push framework than each app using their own broken implementation.

The third, that starts and stops is Event Log. A service writing system events to the log.

No need for alarm.
+Stewart Gateley I'm not alarmed and definitely comfortable with permissions and those particular services but simply wish it wasn't a break down but just one like you mentioned.

The topic today is rude resource hogging apps in which also happen to have editor choice? These games an apps are great minus freemium which is exactly like dlc for PS3 and XBOX which is suppose to help does the opposite.
Leaving services running unnecessarily is something quite a few devs do by mistake or on purpose (bad design). Some examples in addition to bug village are +Spotify (when not playing music), DoggCatcher, Flickr and FlickrFolio. I think Chrome beta leaves a couple of services running permanently as well. I guess the api is simply too difficult to understand and use correctly.
+Anthony Garrett Some applications can get along with a single service, and is a common pattern to have a single multi-purpose service running in parallel with your foreground application.

With a background service which is started by a system broadcast instead of your application, you want them to have a single purpose so they can stop themselves when they are no longer needed.

The event log service is a great example, it gets spawned, does what it needs and exits. Mixing logging, c2dm and location tracking into a single background service would be a poor choice on many counts and this is before even considering what happens when the OS or user kills it.
+Johan Appelgren yes, Chrome has services left running when you enable desktop syncing. If you disable syncing they are shutdown.

There are a number of very poorly written popular apps, and pretty much every popular game is trash when it comes to respecting the os, user prefs and other apps. But most people fail to realize that tons of running services and bad battery life are a result of their own actions.
As far as I can tell the primary reason that two services are kept running all the time is because the application (Bug Village --- sorry back to previous topic) uses them for C2DM-like functionality.
+Johan Appelgren c2dm only works in one direction, and I hope to god Google would never sync bookmarks, passwords and open tabs through c2dm. That also only works with certified devices and background data enabled.
Can somebody tell me how services effect battery life in Android?

This is what I think, but I may be wrong:
Example. I have an sms app that has a service running all the time.
I think it will only start a thread on certain events like android.provider.Telephony.SMS_RECEIVED where it then does what it needs to do and then it will close the thread again. And when no events happen, it will not do anything. So as battery life is concerned it will only drop when you constantly get sms but it won't drain battery if you don't. Am I right?
+Wadim Halik The service should be probably be started by a broadcast receiver and stop itself when its done.
+Stewart Gateley You don't send data using c2dm. And for local changes you don't need a service running all the time either. Only when syncing.
+Wadim Halik As a general rule, services by themselves are unrelated to battery life. All a service is at this level, is a way for an application to tell the system "hey I'd like my process to be kept around if you can." If your process isn't doing anything, then it isn't going to use any battery, just sit there in RAM. It's what it does while being there that matters -- doing networking, holding wake locks, running the CPU, etc.

Also the sitting there in RAM can however build up to have an impact on battery life. If one application has one service running, then you use a little RAM and maybe can only keep 5 instead of 6 processes around in the background. However, if 10 applications are all insisting that they need to stay running, then you can get to the point where you can't keep any background processes around so the system has to do more work as other things are happening, bringing up application processes more often when before it could re-use one it had recently launched.

Worse, if so many applications insist they need to be running that there isn't enough RAM to keep just all of them around, then the system will start thrashing as it evicts services to run other services and starts cycling through them. There are mechanisms to avoid this spiraling out of control (as it sees that not everything can be kept running it will throttle down how much it tries to keep running at once), but it's definitely not a good situation to be in and will negatively impact the battery life of the device.

A quick way to tell how you are doing on RAM is to go to Running Services and see how much "free" RAM it shows there. This is actually the RAM it has available for background/cached processes -- under normal circumstances we'd like to have enough RAM to keep say 5 or so moderately sizes cached processes around. For things to stay in good shape when running heavy-weight applications like the web browser it is nice to have say 100MB free RAM available when viewing this from settings.
+Dianne Hackborn I always look at cached processes and I've wondered why do I have 1GB of ram in my Galaxy nexus and 1GB in my Xoom but the tablet always has more free ram like 430mb compared to 363mb
+Dianne Hackborn Thanks for the great explanation! I guess I was right in one point. And now I see the good side of having my minfree settings at 16-24-32-90-100-110 MB.
Android really is amazing. I love how I already have ICS on my 1 year old LG O2X.
+Dianne Hackborn sorry for replying late and thanks for answer.

I meant developers overhead – it's just harder to use a Service than not, it makes code more complicated, especially because of the need of asynchronous communication.

Even with setRetainInstance() it's too complicated in comparison with other platforms. I wish it was more straitforward. Creating a REST client in a proper way is pretty hard.
+Anthony Garrett Certain peripherals require memory to be reserved for them, these result in some of the system memory being claimed for those devices. For example, the video decoder needs buffer memory, and I believe that most if not all mobile GPUs are similar to "budget" desktop GPUs in that they share system RAM with the main operating system.
+Andrew Dodd I don't think so. My O2X has got 512 MB ram. By default 128 MB are dedicated to the GPU. There are some custom kernels with 32 MB shared memory, but I think OEM's don't put that into their firmware. My kernel actually only gives 96 MB dedicated RAM to the GPU, because I think 96 MB is enough if even Tegra games work.
+Anthony Garrett Those devices use completely different chipsets. As Andrew says, they all have memory set aside for various pieces of hardware (GPU, Camera, DMA buffers, etc). Also if you have a cell radio, its baseband processor shares the same memory so more RAM needs to be set aside for it (for both its code and data). I wouldn't be surprised if the LTE baseband of the GN needs quite a bit of RAM (if you have LTE on the Xoom I think that is a completely separate piece of hardware with its own RAM). Also the way the two GPUs work is very different -- Tegra 2 reserves a block of memory that is shared across all processes and only allocates out of an individual process's memory when that is full, while SGX pre-allocates about 8MB in each process that opens the OpenGL driver. So direct comparisons between them is hard.

If you want to get an idea of where memory is being used across the Dalvik processes, "adb shell dumpsys meminfo" will give you a summary. Also "adb shell procrank" for higher-level data across all processes.
+Dianne Hackborn I'm fairly certain the GNex LTE baseband is a separate chip, just like the Xoom. OMAP4 has no integrated baseband - I think only Qualcomm CPUs have integrated baseband/applications processor on a single chip. The HSPA+ GNex appears to use the same XMM6260 that the Galaxy S II uses. I'm fairly certain some memory in the OMAP4 is reserved for IVA video encode/decode, just like Samsungs reserve a fairly decent amount of memory for their MFC codec engine.
+Andrew Dodd I'm not talking about them being on an integrated chip; I don't think I have ever worked on a device with the baseband integrated like that. However, every device I have worked on has a separate CPU for running the baseband, but shares its RAM with the main system RAM (which is carved out from the RAM available to the kernel). I am pretty sure the GN is the same way, though I am not a kernel level engineer so shouldn't say for sure. And yes, there is a significant amount of RAM reserved for the various hardware either way.
+Dianne Hackborn Wow, I'm really impressed how much you know about hardware, I thought software was your only field.
Please keep posting how you bust/explain myths and rumors about Android you stumble across. Your posts are really usefull!
It's like these desktop apps that each install an auto-update process, plus one that pre-loads the app. Adobe's Acrobat reader is selfishly forcing itself in memory on start, making low end PCs crawl to a stop as they run out of memory already on startup. I've banned Adobe's products from my pcs because of it. And yes, there are good enough alternatives that don't do that.
You are awesome. Rings extended.
+Dianne Hackborn, nice post (I wonder why didn't I see this earlier).
AFAIK, Android phones send a lot of usage statistics to google, like battery use, and probably memory usage, service and its durations, etc. Does this affect Google Play rankings? And.. if I remember correctly, bug village had been a featured app.
+Dianne Hackborn  Would it be completely undesirable or unfeasible to disable certain abilities in Android, while allowing developers dubbed good citizens to access them? Am I being naive as to the complexity of such a system?
Add a comment...