I have an activity that listens to a udp broadcast and triggers an alarm if a certain threshold is reached. But when I exit the app, I no longer receive the notification. How do i keep the app running in the background so that it will send a notification when the threshold is crossed? I have read a bit on services but I am not sure how the logic would work in a relationship between an activity and service. Should the service always be running, should the service start when the app closes? I want the app to trigger an alarm even if another app is running.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
How do i keep the app running in the background so that it will send a notification when the threshold is crossed?
Your activity should start a service, when the user asks for this monitoring to go on. That service would be the one that has the socket and the thread for monitoring for UDP broadcasts. Your activity should also have the means for the user to stop this monitoring, if and when the user no longer wants it.
Bear in mind that your service will not run forever. It can go away at any time, either due to user action or an OS decision. However, it will be available for far longer than will your activity.
Should the service always be running, should the service start when the app closes?
Apps do not "close" in Android.