Invoke a custom code on internet connectivity in Android - android

I want to get latest updates from my server when I turn on the internet and generate a notification, but when the app is closed/killed/swiped from recent items, there is no way to keep my service alive and listening to network change event so that I can ping my server, I'm not sure how to do it and how other apps such as whatsapp does it when we receive new notification the moment we turn on mobile internet.
Any help is appreciated, thanks in advance.

Making clear what #GobuCSG commented. You have the following options:
Run your application all the time via a foreground service and listen for wifi connected broadcast. This is not a good solution and wastes battery life.
Schedule jobs using the WorkManager API.
The WorkManager API was developed specifically for the purpose you specified. The API allows you to set required conditions for your job to run, such as network connectivity. It also persists scheduled jobs through device reboots, so you don't have to. The only downside is that you don't have fine tune control of when the code runs, as one of the goals of WorkManager is to save battery life by delaying and batching jobs.
EDIT:
Another option is to use push notifications. This is useful if your are developing a messaging app and you want your server to push a message to the client so they can be notified of a received message. But, if all you need to do is establish contact with your server once a day, then you should use WorkManager.

Related

App monitor location on background service

I would like to make an app that always works in the background (from boot up), which sends GPS coordinates to a server. This app should ALWAYS be active and should never close.
Should I use the services? I would like to use UDP sockets to send coordinates but I accept alternatives. I would also like to avoid using the google API.
Thanks a lot :)
If your app need to run in the background , you need Service and you need to make it a foreground service which means you need to show a notification to the user as long as your application is running.
To open app on device boot, from Android O, its not allowed. You will get an IllegalStateException.
The main reason for this is to prevent exactly what you are trying to achieve.
Its not good to keep running an app in the background and its especially bad to keep tracking users GPS coordinates and send it to the server.
Because it will drain the battery very soon.
However it is possible to keep a foreground service running which can take the GPS coordinates and send it to the server. But for that user has to open your App first.
Please refer to
https://developer.android.com/about/versions/oreo/background#services
Other alternative is to use JobIntentService which will schedule your tasks in smart ways to avoid draining users battery and data.
Regarding UDP sockets , it depends on your backend.

Android migrate background service to jobscheduler

we have a project which uses background service to retrieve real-time events from server. we use s websocket connection to retrieve data. but now in Android Oreo or higher, os starts to showing battery Warning.
my concern is that if we migrate to jobscheduler does it stop after sometime. we want to show a notification if event happen
i tried job scheduler and it offers recurring invokes. but our connection is real-time so if jobscheduler stops we don't get data.
so how other apps handle this (example WhatsApp )
what is the best way to keep our connection live and retrieve data ?
thanks advance
my concern is that if we migrate to jobscheduler does it stop after
sometime.
Yes. During doze mode all the scheduled jobs are deferred until maintenance window is made available by the OS.
what is the best way to keep our connection live and retrieve data ?
You shouldn't maintain a persistent connection with your server and permanently run background service. Starting from Android O you won't be able to run Services in background. OS will terminate all the services and any attempts to start service in background will result in IllegalStateException
Your requirement seems that you need to use FCM. The basic idea is, instead of constantly asking server for data, let server notify the app about data availability. For more details and implementation steps, refer to official document.

Best Practice for network operation at regular intervals?

I am making an application which contains performing network calls to look for updates. Can anyone help with some best practices to perform this task. I can make a service to run on background and perform network operation using Handler at regular intervals but this would consume a lot of data and battery. Is there any other way to do this?
Use an AlarmManager or JobScheduler (depending on API level), and pick a sane frequency. Doze mode will stop you from going too insane.
You could work with Push Notifications from any server when the backend recognizes an update. It's better for the server itself to listen to updates at a regular interval of time rather than the app, because of the reasons you listed.
When the app receives a push notification, it would mean that it needs updating.
There are a couple of options for you:
Azure Notifications Hub: https://learn.microsoft.com/en-us/azure/notification-hubs/
Firebase Cloud Messaging: https://firebase.google.com/docs/cloud-messaging/

Parse.com Push Service Battery Impact

I cannot use GCM and I am looking for solutions to support Push service in my application.
I saw PPNS from Parse.com and I am now using it. I starts a consistent websocket connection and checks the connection every 15min. And it also checks it on every device wake-up.
What is the approximate battery impact of just this PushService system?
Is anyone using it and tested it?
TL;DR: That's how push notification works. Don't worry about the battery usage if it's a required feature in your app.
Long version:
From what I understand (and indeed, have developed on my own App using my own MQ), that's what most/all other APIs that handle push notifications do, i.e. they maintain a persistent connection to an MQ of sorts (ActiveMQ, MSMQ, etc.) and subscribe to a specific topic which "pushes" messages to clients.
All of them require a WakeLock in order to keep this connection live in the event the phone is "sleeping" or network connection is recovered in order to make sure notifications are delivered. Some of them even maintain some level of persistence in case a message arrives when connection is lost so that they can playback the messages when they reconnect (although this would be an expensive feature in terms of server resources).
Your users most likely already have a WakeLock in one/many of their installed apps (WhatsApp, Skype, etc. -- You can check this by looking at the permissions WhatsApp requires for instance. One of them would be "preventing the phone from sleeping").
This in turn means that adding an extra WakeLock will have no material effect as the phone never REALLY goes to complete sleep anyway. If yours is the only app that has this WakeLock, then there would be a real cost to the battery but it's unavoidable unless you make sure you persist messages in the queue and only display notifications when the user unlocks the phone which is (1) expensive to maintain on your queue and (2) not very convenient as the user will miss notifications unless they're already actively using the phone so background notifications will go amiss.
I also don't imagine battery life would be hugely impacted if you're simply pinging the server every 15 minutes or so (the interval is usually the keep-alive time for the underlying message queue).
This link should help you understand how a local implementation for messaging works and should give you an idea why the ping is necessary and why you would want to maintain that WakeLock:
http://dalelane.co.uk/blog/?p=1599
edit: added TL;DR

Keep a permanent connection (same LAN) in the background, without using GCM

I need to keep an open connection in the background, even when the app is not running. It's not possible to use GCM because the connection will be in the same LAN as the server, and the device may not have a working Internet connection.
The connection will be some kind of local Push, so the device will just get some short relevant data from time to time (in addition to the keep-alive messages).
My use case is quite specific so I can consider that the battery is not an issue. I may show a huge red warning saying that enabling the feature will drain the battery, or just disable it if the device is not charging.
On the other hand, is quite important that the process with the connection is not "randomly" killed by Android.
I thought about implementing this with a service, but I would like to hear opinions from someone else. Maybe there is a better way to do it, considering the constraints mentioned before.
"even when the app is not running"
That means that your app is not running, and it doesn't have a process. Without using a third part app (such as the GCM service) that awakes your app, nothing can reach you.
You can, however, have a service that remains active and keeps a connection to a server (say, for instance, an XMPP server) to receive notifications and wake up this or that activity.
You can also do that in a separate application.
You can add robustness with a regular watchdog started by the alarm manager, for example.

Categories

Resources