I'm writing an app that detects audio from the headphone jack and broadcasts Intents when certain audio conditions are met (specifically when it detects the reading of a card swipe through an auxiliary audio device).
My app has no Activities, it's just an Application and a Service.
Everything works nicely except that the Service is cleaned up by Android after a relatively short time period (~ a minute).
I'm curious what I need to do to tell Android that this is a useful Service and that it should leave it alone unless it REALLY needs its memory back. I realize that I can create an Alarm that wakes up every couple of seconds and fires up the Service if it notices that it's not there, but that seems like a kluge. Is there a more Android(y) way to keep it alive than that?
Use START_STICKY to keep your service around.
Example Use:
http://developer.android.com/reference/android/app/Service.html#LocalServiceSample
More Info:
http://developer.android.com/reference/android/app/Service.html#START_STICKY
That means that your app will never run, on any Android 3.1+ device, unless you have some tie from some other application that is going to manually launch your service.
Don't name your company after a geometric shape -- it's been done. :-)
You are welcome to use
startForeground()
to declare it to be a foreground service. The tradeoff is that you will need to show aNotification
, ideally one that allows the user to stop the service. Bear in mind that users may not appreciate thisNotification
, but you are stuck with it, particularly on Android 4.3+. You may be better served by switching from a service to an activity, so the user can launch that, swipe a card, and process whatever the transaction is.I tried AlarmManager. It works. I used Contex.startService() in the AlarmReceiver. And I can check if my service is running so as to decide if start the service again. So even though my service is stopped by users manually in settings or killed by some cleaning app, the service can be started again. Here is the main code below.
You will not able to restrict the user to manually kill your Service from Settings, running services. Even as device administrator.
You can add boot receiver, screen locker and whatever events, which will re-launch the killed service, and app if it would be also you can relaunch the service with a flag settings if is killed with an app killed Advanced task killer.