Android Services: Recommendations when using AIDL for continuous service and low current drain impact

Last month a lot things happened.. I lost my dad, moved to another location .. thus, this blog was not the priority but was not forgotten.

This post is related to some issues I have observed in some Dalvik implementation and some recommendations is you want to create a service that must remains running all the time even after a device power on/off or reset.

Suppose you need to create a “light” service that must be:

1) starts when every time your devices boots.

2) contains very nice parcelable objects using aidl syntax sharing them thru IPC

3) is used to monitor something every X minutes but cannot impact the current drain.

4) the service must use the “uptime”, I mean, must reports “how long” is running

5) must be able to receive interruptions and reports them

A good application of this service could be an alarm central unit for your car. You could create this project using your old Android phone and transforming your old phone and hidden it in your car. You can also connect this old phone disassembling a 12V charging and connecting in some spot using the terminals of your battery.

So, let’s go to some mistakes.. see the list below:

Mistake 1) SystemClock.elapsedRealtime() versus System.currentTimeMillis()

If you are an old J2ME programmer probably the first option you can have in your mind to track your “uptime” is the System.currentTimeMillis(). However, if the user change the time/date the System.currentTimeMillis() is impacted!

The correct option on this case, is the SystemClock.elapsedRealtime() that will bring to you the total milliseconds after boot and it is not impacted with date/time.

Mistake 2) Wrong UPTIME

In the Mistake 1, you realized the importance of SystemClock.elapsedRealtime() but if your service need to auto-start when the devices boot, you should register the intent BOOT_COMPLETE.

So, it is very common to see developers using the UPTIME using directly the SystemClock.elapsedRealtime(), but remember! It is not only your service that starts after boot and of course, if UPTIME is something that must be precise your need to reduce the time waste to start your service.

So you need to do something like:

long TIME_IN_MS_WHEN_STARTED = SystemClock.elapsedRealtime()

then when you need to evaluate your uptime:

long UPTIME = SystemClock.elapsedRealtime() - TIME_IN_MS_WHEN_STARTED

I now, sounds ridiculous but it is very common mistake in real time systems.

Mistake 3) Using wakelocks instead RTC Alarms

If your system cannot be invasive, avoid the consume of the battery, but your need to monitor some inputs periodically, wakelocks is really the worst because will prevent your phone to sleep consuming a high current all the time. The best option on this case is to use the RTC of your device to wake up your service.

AlarmManager am = (AlarmManager)getSystemService(Context.ALARM_SERVICE);

 Intent intent = new Intent(receiver.ACTION_REFRESH_SCHEDULE_ALARM);

 PendingIntent pi = PendingIntent.getBroadcast(getBaseContext(), 0, intent, 0);

// After after time_in_sec seconds
 am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * time_in_sec, pi);

Then to cancel the timer you need:

public void cancelTimer()
 if (timerRunning) {
 timerRunning = false;
 Intent intent = new Intent(getBaseContext(), MyReceiver.class);
 PendingIntent sender = PendingIntent.getBroadcast(getBaseContext(), 0, intent, 0);
 AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

Mistake 4) No memory, crazy Dalvik killing everything and your service was not restarted !!! DAMNIT!! WHY ?

This is very tricky… there are situation that your system may be affect by “low memory” event, and the Dalvik decides to kill everything not in use including the background processes. Sometimes you will be able to the in logcat messages like “Too many background processes”, “Low memory”, and believe it is something you cannot control due to many variables in your device (sometimes many horrible software implementations installed in your system too).

When the Dalvik kills the services, as son we have decent memory available the Dalvik tried to restart everything again. Then you have a great surprise! Even you using a AIDL service, your client was not able to receive the UNBIND event, even a “service disconnect” error, and you are completely lost.

Why ? Well.. I tell a specific situation that I could realize some Dalvik implementation failing.

Suppose your service was using a periodically RTC event (like described on Mistake 3 previously) and then your service contains a receiver like the line:

Intent intent = new Intent(receiver.ACTION_REFRESH_SCHEDULE_ALARM);

Then, just after Dalvik killed you service, the RTC generates an event. Even your service already killed, the receiver will receive the intent. On this case, if you are accessing something already destroyed with your service, for example, an object that makes reference some memory in native side (NDK implementation) or your parcelable object are null at this time, your service will not be RESTARTED !!!

This is scenario that I could realize some implementation are failing. How to fix this issue ?

Make sure when your service is destroyed to cancelled the alarm:

 public void onDestroy() {
 // TODO Auto-generated method stub


and be precocious that in your receiver make sure the objects you are accessing are not null.

If you do this, the Dalvik will be able to re-start the service without problem.

Mistake 5) Saving all the time your data

If you need to save data, be reasonable.. Sometimes it is better to save in cache (RAM) and in specific amount of time save it. If you have summarized info to be save and the data is very few, try to use a light mechanism.. For example, SharedPreferences is lighter than SQL Lite on this situation.

Mistake 6) Problem with exceptions and tombstones

If your system access external devices and you have special NDK implementation on your system, make sure you are not masking any problem on your native side. For example:

try {

 int result = my_obj.my_native_call();
 } catch (MySpecialException e) {
 Log.e(TAG, "Ops... a problem !!");
 } catch (Exception e1) {
 Log.e(TAG, "other problem caught!" + e1);


If you have a problem in your native call, maybe none of the exceptions above will be caught but the failure is not on java context but in your native context.

On this case, if you did not insert decent logs messages on your native side, you will need to check the tomstones files.

You are able to see the tomstones dumps in your logcat also.


87 thoughts on “Android Services: Recommendations when using AIDL for continuous service and low current drain impact

  1. Pingback: rouge argent jordan 20

  2. Pingback: wall 3 pink pow uk trainers

  3. Pingback: descuento adidas harden ls

  4. Pingback: vert rouge nike air max 1 ultra morie

  5. Pingback: jordan 2018 olive yellow uk trainers

  6. Pingback: celebrity sneaker watch nas graces london in air jordan xi cool grey

  7. Pingback: jordan retro 4 2016

  8. Pingback: amarillo amarillo adidas y 3 qasa sandal

  9. Pingback: nike roshe run women

  10. Pingback: uk trainers adidas x 17.1 fg collegiate navy

  11. Pingback: cute off the shoulder dresses maroon

  12. Pingback: wholesale big and tall legend alex collins 34 baltimore ravens jersey

  13. Pingback: nike mercurial victory v tf bright mango metallic silver hyper turq 2016topmarksjoinery

  14. Pingback: nike air pegasus 83 nike air pegasus 83 mens

  15. Pingback: moncler vests women quilted warmer body navy blackmoncler kidsmoncler coats on saleretailer

  16. Pingback: hombre adidas originals zx 850 entrenadores negro blanco adidas

  17. Pingback: thank flying civil air patrol

  18. Pingback: adidas eqt zapatos para correr support nuevos york sneakerb0b

  19. Pingback: toe booties

  20. Pingback: whit plaid skirt red skater skirt white black grey pleated skirt pleated uniform skirt

  21. Pingback: aquatherm by santana canada wren snow boots waterproof for women in black

  22. Pingback: mizuno wave bolt 4 volleyball wosize walmart co

  23. Pingback: converse wine claret red leather velvet winter side zip chuck taylor all star high tops sneakers converse shoes

  24. Pingback: ronaldo brazil autographed jersey christiano nike bas coa

  25. Pingback: womens nike air royalty high wineberry leopard

  26. Pingback: 40 jerseys black gray

  27. Pingback: black kids boys adidas tops cf8555blk

  28. Pingback: adidas originals eqt rf support 93 bb1319

  29. Pingback: under armour shoes tumblr mizuno wave fang

  30. Pingback: official manchester city fc socks mens size 6 11

  31. Pingback: the north face m dubs insulated jacket herren jacke blaubraunorange gre xl marke the north face farbe schwarz gren m xl geschlecht

  32. Pingback: jordan son of mars white club purple black available on ebay

  33. Pingback: turning a smartphone into a headup display for any

  34. Pingback: black bathing suit cover up dress coolibar

  35. Pingback: air jordan 6 rings pink size 9

  36. Pingback: rabbitgoo short dark brown wig curly wave women flapper bob wigs heat friendly cosplay party costume hair wig 11dark brown

  37. Pingback: rojo blanco mbt kisumu 3s

  38. Pingback: womens air max 97 ultra pink newjordans2018

  39. Pingback: air jordan 17 rainbow

  40. Pingback: rayban glasses protect eyes and at price1299 click the picture right now

  41. Pingback: columbia baby girls double trouble jacket baby clothing ap

  42. Pingback: understanding a little about hair extensions could spare you time and cash particularly with all the contrasting types and fashions accessible in today s

  43. Pingback: won t wick up smelly water the ground that would make them uncomfortable and disgusting so goes a major problem with diy flip flops

  44. Pingback: cowichan knit eagle hat brown

  45. Pingback: copper jordan 17 shoes

  46. Pingback: metal round steampunk sunglasses brand designer retro vintage sunglasses oculos de sol masculino affiliate

  47. Pingback: australia outlet store black shoes boots sneakers asos asos wide fit brogue shoes

  48. Pingback: amazon puma womens tape dress french terry clothing

  49. Pingback: adidas crazy byw x performance

  50. Pingback: puma womens sandals flip flops purecat slide sandals discount eur41

  51. Pingback: Birkenstock UK

  52. Pingback: air jordan 11 ll cool j custom

  53. Pingback: cabo flutter top maxi dress

  54. Pingback: boys toddler air jordan retro 5 440890b 133 finish line toddler swag

  55. Pingback: uk trainers adidas crazy 1 adv primeknit pure platinum

  56. Pingback: adidas originals zx flux multicolor knit various designs

  57. Pingback: nike flyknit air max mens shoes 19 nike air max nike

  58. Pingback: air jordans 4 retro 11lab4 red patent leather

  59. Pingback: nike lunar tiempo sky hi black

  60. Pingback: nike black baskets nike air max thea ultra baskets p00206145

  61. Pingback: spurs jersey number 1 jersey

  62. Pingback: nike sb surplus beanie obsidian dark obsidian neptune green white at a great

  63. Pingback: hockey goalie helmet decals prohockeylife

  64. Pingback: colosseum mens florida state seminoles two face t shirt

  65. Pingback: guess w74k11k72f0 womens dress

  66. Pingback: reebok john wall season iii 3 zig escape images weartesters

  67. Pingback: foxbury womens ladies chunky faux fur bobble hat trade me

  68. Pingback: no comments yet on the it bag for men by fendi mbfw

  69. Pingback: new balance mens m700 competition xcountry running shoe black spike 8.5

  70. Pingback: mens shirts casual formal shop now religion clothing

  71. Pingback: cheap mens nike kd 6 nsw lifestyle shoes black brown red australia for sale wholesale

  72. Pingback: joran air homage sneaker t shirt presented in a unique design to match your bling needs

  73. Pingback: givenchy cuban fit peacock cotton jersey t shirt black mdax0 men clothing givenchy wallets

  74. Pingback: 2018 17 mulberry womenmen textured leather pouch canada outlet store

  75. Pingback: fashion new balance ml999cra limited elite gris noir rouge homme chaussures model

  76. Pingback: scala pearl cuff beanie cap beanies

  77. Pingback: 榛沯k绱旀绱旇壊閲濈箶闁嬭~鐧借ク琛暦琚栭珮鑵扮櫨瑜惰绱旇壊瀛哥敓鏍℃湇鐝湇 闇插ぉ鎷嶈常

  78. Pingback: burberry sanbridgess suede wrap trench trench fluide

  79. Pingback: sneakers athletic camper peu senda lace up flat womens shoes women ylxxvrvlnq

  80. Pingback: rg da moda roupas para todas as ocasi玫es

  81. Pingback: when at t started sending out the ice cream sandwich for the htc vivid we got more than a few readers asking where was the update for its lte launch

  82. Pingback: discount new air jordan 12 red october cheap jordan 12

  83. Pingback: jordan flight fleece pants kids black

  84. Pingback: uk trainers social status x new balance 1600 winter in the hamptons

  85. Pingback: original new arrival 2018 adidas predator 18.3 ag mens soccer shoes sneakers

  86. Pingback: nike jordan lifestyle flight tech fleece full zip hoodie in black

  87. Pingback: scarpe uomo e eganti pe e b u nere c assiche francesine derby

Leave a Reply