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.


155 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

  88. Pingback: heine sneaker mit glanzeffekt goldfarben im heine online shop kaufen

  89. Pingback: mjartoria unisex bracelet de main menotte tib茅tain fait main tress茅 multirang enveloppez enrouler vintage cuir artificiel

  90. Pingback: tommy hilfiger buty tommy hilfiger 43

  91. Pingback: polo ralph lauren damen jacke bekleidung

  92. Pingback: r酶d hvid stribet onkel reje kjole fra ramasjang kluns

  93. Pingback: blusa farm preta estampada blusas adidas farm

  94. Pingback: React Element 87

  95. Pingback: oja futebo brasi eirista camisa oficia nike tottenham 2018 2019 i jogador manga comprida

  96. Pingback: moncler femme soldes doudoune moncler shiny thomas noir

  97. Pingback: uk trainers lebron 15 all blue nikelebron

  98. Pingback: cl 41068 s 807 w2 en stock lunettes de soleil femme c茅line cl 410

  99. Pingback: kozaki obuwie damskie modne kozaki koturn czarny br膮zowy 偶贸艂ty czerwony szary zamsz forma ne spotkania 1558244 2017

  100. Pingback: chanel frames on display editorial photo. image of glasses 57939576

  101. Pingback: 贸culos de sol de grife para o natal 2019

  102. Pingback: caixa mi k coco chane no e o7 be os deta hes

  103. Pingback: italia unif scarpe mary jane in velluto nere donna nero

  104. Pingback: ltb slim fit jeans molly online shoppen casual dames jeans mode

  105. Pingback: tenis nike star runner crian莽a loja dos sapatos

  106. Pingback: wholesale diesel jeans supplier

  107. Pingback: puma erkek g眉nl眉k y眉r眉y眉艧 36058001 puma flexracer black white 36058001

  108. Pingback: where to buy fitflop in usa

  109. Pingback: dolce gabbana sicilia jacket style thick jeans shirt denim cotton

  110. Pingback: converse chuck taylor all star y眉ksek siyah lacivert beyaz converse ayakkab谋 bayan converse 7469

  111. Pingback: luva de boxe everlast pro style preta tamanho 16 oz

  112. Pingback: hardloopschema asics

  113. Pingback: adidas 銈儑銈c儉銈?閫氳博 ray beams 銉偆 銉撱兗銉犮偣 beams

  114. Pingback: t锚nis vans authentic original promo莽茫o black friday queima r 199

  115. Pingback: how to identify good or bad quality of the leather bag

  116. Pingback: light brown women ray ban wayfarer sunglasses

  117. Pingback: z谩bavn茅 barevn茅 pono啪ky surf and sail od many mornings skladem na

  118. Pingback: nike nike air max sequent 2 g siyah kad谋n 100351960 instreet

  119. Pingback: chuteira adidas artilheira iii campo masculina decker online

  120. Pingback: very good package and very fast to shipping to australia

  121. Pingback: 锌谢邪褌褌褟 褕懈锌褕懈薪邪. 褑械薪邪 1000 谐褉薪. 屑邪褕懈薪薪邪 胁懈褕懈胁泻邪. 卸褨薪芯褔懈泄 芯写褟谐

  122. Pingback: nike fc barcelona trikot home la 2018 2019 f456 blau

  123. Pingback: vans old skool 92 pro black white red

  124. Pingback: blinged out converse for adults pearl

  125. Pingback: womens racer lite em trainers

  126. Pingback: converse chuck taylor all star hi looney tunes silvester tweety high top trainers white blacke tweety yellow shopping sites

  127. Pingback: chaussures de course 2017 adidas pride collection crazy explosive low pride core noir

  128. Pingback: original nba shirts

  129. Pingback: casio mens mq24 1e black resin quartz watch with black dial casio watches

  130. Pingback: 賲賱丕亘爻 乇噩丕賱賷賴 乇賵毓賴 賲賳鬲丿賷丕鬲 亘乇賯

  131. Pingback: netshoes camisa santos 2010 s n潞 masculina masculino

  132. Pingback: long and short of it tee little kids big kids like 9the north face kids

  133. Pingback: naketano hoody ng ii hellblau damen bekleidung hoodies

  134. Pingback: timex 谐芯写懈薪薪懈泻

  135. Pingback: what is a messenger bag used for and what are its benefits

  136. Pingback: womens adidas cloud neo

  137. Pingback: k枚p nattlinne my secret med fri frakt

  138. Pingback: ravn copenhagen fashion by caroline

  139. Pingback: brasiliense 茅 convocada para sele莽茫o de futsal ap贸s 18 anos

  140. Pingback: womens rain hat womens black rain hat rain cloche waxed canvas cloche 2 weeks for shipping

  141. Pingback: mpg playera negro cuello redondo y logotipo de la marca estampado en espalda playeras y polos

  142. Pingback: s lovky adidas messi adidas messi shoes

  143. Pingback: short jean et dentelle vinted

  144. Pingback: scott mens bike shorts suppliers

  145. Pingback: med 纬蠀谓伪喂魏蔚委慰 string marian

  146. Pingback: european and american style women two layers of water pearl soft leather shoulder bag mother bangalor

  147. Pingback: nuevo bal贸n para la final de la champions league 2017 2018

  148. Pingback: armani jeans damen jacke 4xl 50 schwarz sommer 眉bergangsjacke parka

  149. Pingback: uk trainers best online ski shop canada

  150. Pingback: mori lee 89088 two piece ball gown

  151. Pingback: pre owned air jordan vi6retro carmine 14 us size 10 100

  152. Pingback: acquista vendita scarpe diadora on line off79 sconti

  153. Pingback: o trova maglie nba nuove maglie nba per nike bianco kristaps porzingis new york knicks versione

  154. Pingback: uk trainers boys table and chairs

  155. Pingback: t锚nis vans authentic camuf ado bad kid ca 莽ados e acess贸rios infantis

Leave a Reply