Android Developer - Alarm manager vs service - android

I am making an app that needs to execute a function each hour even the app is closed.
First of all, I thought to create a service, but during my tests, I realise that android sometimes kills my service. So I was looking for another solution and I found AlarmManager. I have implemented it and it seems to work but I have the doubt if it will happen the same the service or it will run forever? (Until reboot of the mobile...)
Another question, it is necessary to create a new thread to execute the process in alarm manager or it runs directly in other thread?

I have implemented it and it seems to work but I have the doubt if it will happen the same the service or it will run forever? (Until reboot of the mobile...)
It will run until:
the device is rebooted, as you noted, or
the user uninstalls your app, or
you cancel the events yourself, or
the user goes into Settings, finds your app in the list of installed apps, taps on that entry, and clicks the Force Stop button
It's possible that alarms will need to be scheduled again after your app is upgraded (I forget...).
it is necessary to create a new thread to execute the process in alarm manager or it runs directly in other thread??
Unless the work you are going to do will take only a couple of milliseconds, you will want a background thread for it. That leads to two possible patterns:
If you are not using a _WAKEUP-style alarm, use a getService() PendingIntent to send control to an IntentService every hour
If you are using a _WAKEUP-style alarm, you will need to use a getBroadcast() PendingIntent, and have it either invoke your subclass of my WakefulIntentService, or you will need to manage a WakeLock yourself to keep the device awake while you do your bit of work

No, Android won't kill scheduled alarms and they got executed as planned unless app is replaced or device is rebooted. Use broadcast receivers for these events to reschedule Alarms. There's no way to prevent Force Stop as it kills all of your app components and threads totally.
That depends on what Alarm Manager do. If it sends a broadcast, the receiver limit is 10 second.
If it starts an Activity, Service or Intent Service, there is no limit. For Activity and Services you must finish or stop it and for Intent Services until the process is finished. Be aware that you can't have another thread inside Intent Service and you'r limited to code inside the OnHandleIntent.
Also you must consider device state. If it's sleep and you are using Wake Up flag receivers won't need a wake lock, but others do. It won't take long for device to go back to sleep.
Don't waste system resources with a service because Alarm Manager do what you want.

Related

how to peridically start Intent service

I need to keep service running to monitor changes through content observer.
I also need to know , Can my alarms set for periodic intervals can be erased ?
If yes then When ?
Can task killers erase Alarms for version onwards 2.2 ?
If you want to keep a service running, use Service.startForeground. Then the Android system won't kill it, except under the most extreme circumstances.
You need to supply a notification which is continuously shown to the user so that they know they have a service running which is potentially using resources. This seems to be a deliberate (and sensible) design decision.
So long as you do that, and so long as your ContentObserver actually works, there should be no need at all for you to wake up your activity or service code using AlarmManager. Your service should just continuously run and your code should be called whenever the content changes.

What happens to a service started by BOOT_COMPLETE after system kills it?

What happens to a service started by BOOT_COMPLETE after system kills it for memory?
Will it ever be restarted without rebooting the phone? Is it possible to restart it somehow?
What is the best practice to avoid as much as possible an important service from being killed?
Will it ever be restarted without rebooting the phone?
Possibly. If it truly was because "system kills it for memory", and you return an appropriate value from onStartCommand() (e.g., START_STICKY), it should be restarted at some point in the future. If the service was killed due to user action (e.g., Force Stop in the Manage Services screen in Settings), it will not be restarted.
What is the best practice to avoid as much as possible an important service from being killed?
First, design your application to not rely on an everlasting service like this. 99.44% of Android applications do not need a service that runs continuously, let alone one that starts doing so at boot time. Android device users hate developers who think that their apps are sooooooooooooo important that they have services running all the time -- that's why we have task killers, Force Stop, and Android killing services due to old age. For example, if you are checking for new email every 15 minutes, use AlarmManager and an IntentService, not a service that runs forever.
If you can demonstrate -- to me and to your users -- that yours is among the 0.56% of applications that really do need a service that starts at boot time and runs forever, you can use startForeground(). This will indicate to the OS that your service is part of the foreground user experience. You will have to display a Notification, ideally to allow the user to shut down your service cleanly if and when the user no longer feels that it is justified.
If you need to restart the service then you should use AlarmManager to check up on the service in a separate BroadcastReceiver, but nominally when a service is killed by the system for memory it will not get automatically restarted.
You may want to take a look at START_STICKY
Use the AlarmManager to periodically send an Intent-- receive the intent and make sure your service is running.

Alarm manager, using wakelocks to ensure all code runs

I'm looking at using the Alarm Manager, and read this in the developer docs, which I don't really understand.
"If your alarm receiver called Context.startService(),
it is possible that the phone will sleep before the
requested service is launched. To prevent this, your
BroadcastReceiver and Service will need to implement a
separate wake lock policy to ensure that the phone
continues running until the service becomes available."
http://developer.android.com/reference/android/app/AlarmManager.html
I am specifically asking for which situations it could possible that the phone will sleep before the service is launched (as this is the part I don't comprehend)? Is it dependent on how fast the phone can execute statements? ie. it calls startService() which opens another thread and so the original thread could complete its work before the service has been made available?
Thanks
If you're starting the service from a BroadcastReceiver, you're only guaranteed that the device will not sleep during the receiver's onReceive(). According to this question, startService() is asynchronous, which means it will not block onReceive() from finishing while the service is being started. So if you need to make sure that the service starts, you have to implement your own WakeLock.

Clarification of AlarmManager behavior in Android

I see all the examples of AlarmManager being set by an Activity.
My question is this:
If my application sets a recurring AlarmManager, does that persist even after the application that started is is closed and removed from memory?
If not, how do I start an AlarmManager at a lower level that is started by Android at boot up and if it ever fails or dies or throws an exception is restarted without the user having to do anything?
Lastly, if the action I wish for the BroadcastReceiver to undertake has no visual components, do I still have to create a separate Activity for it? In my case I want there to be a background uploader that wakes up and looks into a folder and if it sees files in that folder, sends them off to the server. I don't need any feedback to the user.
So, my ideal would be to have a magical, OS based AlarmManager that calls an IntentService which just handles the uploading, but I'm unclear on how to get such an AlarmManager running in the first place.
TIA
Yes, AFAIK the alarms "survive" and keeps getting triggered, even after the activity that registered them ends. But they don't survive a phone reboot.
If I understands your problem correctly, I think you can achieve what your looking for by creating a project with a broadcast receiver that listens for android.intent.action.BOOT_COMPLETED intents and then (re-)register a repeating alarm, which in turns starts a (Intent)Service to do the uploading.
You don't need an activity, but you probably would want one anyway, to let the user temporarily disable the upload mechanism by checking off a checkbox, or something. It would probably also be nice to let the user choose the frequency of your alarm, i.e. how often the service should be started and look for new files to upload. This would also be a good place to register your alarm for the first time.
I agree with Nicolai that you'd have 2 broadcast receivers in your application :
one that re-register the alarm on boot
one that starts your service when triggered by the alarm
You could still have an activity but it shouldn't be started by the alarm receiver (hence the service) : instead, maybe launch a notification as you start your service, with the user having the possibility to launch the activity from the expanded message of the notification.
maybe also think about setInexactRepeating (instead of setRepeating) for your alarm, as well as using a worker thread to handle the long uploads (in case the user wants to use your activity in the main thread at the same time).

How can I ensure a service is started at 9am and stopped 9pm every day?

I have a service that will monitor location changes daily. What I know so far that to start a service at boot, I have to follow the linked tutorial. This way I can get the service started at boot, but to save battery I need it only between 9am-9pm.
Question is pretty simple, so I will repeat:
How can I ensure a service is started at 9am and stopped 9pm every day?
Use AlarmManager to set two alarms, each with a PendingIntent that will call startService() on your service, but with distinct action strings ('start', 'stop'). When onStart() of your service detects the 'stop' action Intent, it arranges for an orderly shutdown (e.g., stopSelf()).
This will fail if the user applies a task manager to you in Android 2.1 or earlier, since the technique they tend to use will wipe out your alarms (in addition to killing the service). In that case, the user is presumably voting for your service to not run, so you should try to accommodate the user's wishes.
CommonsWare is right. This is the best way.
You are writing an application and you had better not to change anything out of the application. If you want to add a system service(on boot started service), you need to modify the BSP and add your service to systemserver.java. It's not recommended.CommonsWare's suggestion can do this work.
As you said about the activity, you can start the activicy when you receive the boot broadcast. Then do what your want.....

Categories

Resources