I need to maintain an open, two-way communication channel between an Android app and an external server. I know that I can use GCM for this, but for various reasons that don't pertain to Android, itself, I would like to use websockets, if at all possible.
Can anyone point me to a comparison of resource/battery usage stats when using GCM versus a java-based websockets client under Android?
Thanks in advance.
Since multiple applications use GCM which uses a single socket connection to the Google cloud, making your application use GCM for notifications should not affect battery life at all since it just uses an existing connection. On the other hand, what ever process you create using websockets, that battery usage will just be added on top of GCM.
Also, if you need to maintain your connection even when the application is not in the foreground it will be necessary to create your application as a foreground service. GCM handles this for you.
Update
A device that has no other applications using GCM is a very rare case since many essential applications like gmail use GCM. I do not have exact numbers of the battery usage of GCM. But the battery usage of C2DM (GCM's predecessor which uses the same underlying communication model) is mentioned in this video around 4 minutes in. I actually had a similar question about the battery usage of a persistent socket connection to an external server (Android persistent socket connection rules). Although it is not a websocket I would image the battery usage to be similar. But again since GCM is built in at a much lower level of the OS, I would image it to be more optimized than a custom solution.
Unless you have some company policy against using a third party server or some very specific specifications, I would recommend using GCM. I would also encourage watching the entire video about C2DM as well as this video for GCM.
Related
I've always used GCM for push notifications in android apps, but for security constraint i'm obliged to avoid GCM and use local push server, i've found a lot of answers for this question but none of them is well structured, i hope to get a clear answer for step by step process to use some XMPP server and client libraries for this topic
You may not fully understand what is GCM and what GCM was designed for.
Traditionally, each desktop applications establish its own TCP connection to its own server, just like you can connect to your Openfire instance and send/receive messages when you want without any third-party services.
This approach have many issues in mobile environment:
mobile devices are resource limited: when you have many TCP connections open it will drain your battery fast
mobile devices are not have persistent network connection: you should care about cellular and/or wifi network changes (and it also have battery impact) and you should not lose any messages in these unstable environment.
To solve these problems, Apple, Google (and also their minor competitors) provide "notification services". They are consists of:
System-wide background application ("service") which keeps connection to Apple/Google "notifications" infrastructure servers.
API for developers, to "register" their applications both on server and client side: your server-side application send all events to Apple/Google, and you client app receive "pushes" from that system service, you no need to care about network outages and battery impacts - all issues are handled by OS manufacturer.
But when you are trying to "avoid GCM" you getting all things to be cared by you, plus:
Your "handmade" persistent network service will interfere with Google's one, and will at least double network and battery usage (or even more, just because your implementation will have errors/other corner cases which are already where solved by Apple/Google big engineering teams)
Your application will dramatically more complex, and you will have much more security issues (as security issues are now handled by you, too) and poor user experience (applications with "own" networking are often have bad UX design, prompting and boring end user with network error messages, for example).
So, to sum up:
Yes, technically, you can take smack library and connect to Openfire server. Basically it the same as GCM works.
No, in 99.9999% of cases you should not go this way. Unless you are a big company which develops competing mobile platform.
I am trying to use GCM service, Every thing is OK except of the long delay that GCM push notification or deliver payload... some times it take to my App 5 minutes receive notification or payload.
I need Immediate delivering...
I know about the roles of GCM, that wait until the other device got online, but in my case I hold two devices and they are online, but I got Delayed notifications!
How does WhatsApp(as example of app that uses GCM) overcome this problem.. and send Immediately?
[ i.e (message of the type: typing, online - last seen) cannot be delayed...]
the GCM Delayed Push is known problem : this issue
my question is: How other app that use GCM overcome this issue
The big players
Lets focus on WhatsApp from a scale point of view. Their scale is global and one of the largest in terms of the market share. For players like these it becomes necessary to provide a consistent and smooth user experience no matter what the circumstances are. This means that the "small fish developers" like us are left with pre-defined rules by the big fish companies. Sometimes, it is the implementation that is challenging enough that a lot of the small time developers have to do with whatever is available.
I would like to take WhatsApp's Push Notification as an example to illustrate the above.
First of all, we must stop associating Push notification with Google's services(i.e, Google Play Services) exclusively. Would a device without Google Play services won't receive Push notifications? No, of course it can -- try focusing on the core mechanism of a push notification
How do Push Notifications work - Sockets!
Contrary to a protocol like HTTP which assumes a client-server architecture and is a uni-directional protocol(server can't initiate communication by itself), a plain socket enables communication bi-directionally.
You want to implement your own File transfer protocol over socket? You can!
You want to implement your own Chatting protocol over socket? You can!
You want to implement your own Push notifications protocol over socket? You can!
A socket is the canvas of communication over a network. You can pretty much do anything. Personally we have developed a custom request-response protocol in our organization.
Multiple implementations
Don't stick with default GCM/FCM notification messages protocol or implementation. You can deploy a mechanism to maintain a persistent socket connection with the device and can listen to whatever the server wants to push.
WhatsApp uses both GCM/FCM as well as their proprietary XMPP server implementation for Push notifications
WhatsApp(and several other Apps) rely upon GCM/FCM(as option 1 - the default) as it is present as a system App on lot of devices and therefore holds a special status where it is very less likely to be killed unlike a normal App.
For devices that do not have play services, your custom socket connection is relied upon. It may be that FCM is preferred over socket when the former is available but those are upto you to manage.
From WhatsApp's latest build(2.19.203):
Notice that the relevant permission for FCM is present.
Suspected socket implementation: https://android.stackexchange.com/questions/43970/how-is-whatsapp-able-to-receive-messages-when-not-in-use
XMPP based Push Notifications
From, https://www.quora.com/Does-WhatsApp-use-GCM-to-exchange-messages
No, whatsapp doesn't use GCM[NOT entirely true]. It uses a modified version of XMPP
called FunXMPP instead. It changes the XML keywords in message frames
to save bandwidth as it's users aka mostly mobile network users,
doesn't have a good internet connection. The replacements can be found
here: mgp25/Chat-API (I am not the author though)
They have even asked for whitelisting of any port(custom) in use by them.
So, WhatsApp does it. Facebook does it. Google does it. A lot of these companies do this. You can do it as well(to an extent) using Ejjaberd, Openfire or some other technology and having a proper client side implementation for the same.
Chinese ROMs
Some chinese ROMs have taken it even further and radically changed the way the memory and processes are managed in Android. As an example, in Oppo if the Application doesn't have Auto Start turned on, it will not let you do anything once your App is killed. No hopes of any experience whatsoever except hoping that the user will open the App again. In these cases, these OEMs have whitelisted WhatsApp, Facebook, Google and other players selectively. So, who suffers?
Us. Period.
When sending your notification you could set the priority-parameter to "high".
From the docs:
By default, messages are sent with normal priority. Normal priority optimizes the client app's battery consumption, and should be used unless immediate delivery is required. For messages with normal priority, the app may receive the message with unspecified delay.
When a message is sent with high priority, it is sent immediately, and the app can wake a sleeping device and open a network connection to your server.
I know this answer comes late, nevertheless if you are still facing this issue (or anyone else) please tell me if it helps.
We have implemented rabbitmq chat in android. but java client of rabbitmq is power hungry.is rabbitmq good for android chat?. we have used direct exchange individual queue for persons and individual routing keys. what is the best design pattern for one to one chat in rabbitmq.
and also ways to reduce battery usage
I don't think that use RabbitMQ directly for developing a chat is the better solution.
There are other solution more light please read this post about MQTT.
Another standard solution is use XMPP protocol (for example whatsup uses a custom XMPP).
We made some test and we also had some problem about battery consuming.
BTW, you can mix the technologies, mixing RabbitMQ as back-end and some other server (XMPP,MQTT) as front-end.
Read this post about the MQTT.
MQTT used by Facebook Messenger
EDIT
I would add this post MQTT vs. XMPP Which Should I Choose?
EDIT2
Please read also this and this on the official rabbitmq-group
Maybe you could combine RabbitMQ with GCM to save power as GCM gets triggered by the system and doesn´t need to keep any extra connection alive.
For example:
The app gets notified via GCM when any new event comes in.
Then a new Rabbit connection gets established, retrieving the data and timeouting after a short while again, if no messages are coming in again.
So the actual "hungryness" exists only for a short moment and only when neccessary.
You can also analyze which users are tending to always write multiple messages close behind one other and vary the timeout based on that value
I think chat applications for real time delivery is sending messages over network instantly rather than reliability. Reliability means confirm receiving against delivery. But in real time chat application does not make sure it. RabbitMQ is a message broker server and it is dedicated for reliability first, but it is not responsible for real time message communication. You may use RabbitMQ for real time communication but sometimes may not be in real time.
You can use STOMP-WebSocket(For simple messaging), Firebase(easy development for instant messaging), but most professional and usable protocol is XMPP(Extensible Messaging and Presence Protocol) for real time communication.
If you have any suggestion or query against this answer, let me comment bellow.
What's the best way to send constantly updating data from a server (over a REST API or a socket) to an iOS or Android app? Should I create a socket connection and have a socket server that pumps out data, or should I have the app periodically poll a backend resource? Thanks!
Should I create a socket connection and have a socket server that
pumps out data
This is an option. I know some top apps on the play store that use web sockets for streaming data.
Have the app periodically poll a backend resource
I would recommend against this. Polling drains the battery. The android OS will keep the CPU in idle mode at times and constant polling can wake the CPU up and cause a drain in battery. Users wont like that. You are also wasting processing power when there are no results from the server.
The easiest way to send push notifications / minor updates to the android phone is via GCM. The GCM messages are delivered in near real-time (I noticed a lag of about a second for my apps). The payload is limited to 4k and the messages are stored for up to 4 weeks. This is another option you can consider based on your use case.
The typical model I follow is to hit the server on a specified interval and download the updated data.
Polling is bad, it drains out the battery
If you want to update the screen when the application is in the foreground, it is better to go with Socket Connection. You can see the changes in realtime.
For this, you need to create a socket server and open a connection between the device and the server.
https://www.raywenderlich.com/3437391-real-time-communication-with-streams-tutorial-for-ios
I would suggest to use MQTT protocol to publish and subscribe data. Libraries for iOS(Moscapsule) and Android(Paho) for integrating MQTT protocol are available and can easily be integrated in mobile apps.
Backend needs to be configured to support MQTT also. Detail information about how MQTT works can be found here.
I am going to paste my accepted answer from a similar question that was posted a few hours ago.
It can be done using sockets or polling the server but I wouldn't recommend either for a production level app. You will eventually need security features and as a frontend developer, it would be difficult to start from scratch.
I would suggest using a third party service. Take a look at Space Cloud. It is an open source alternative to Firebase where you can use your own database and has built in security features. If you want to go deeper, it uses Apache Kafka for realtime database features.
If those don't suit you then the best option would be to go with GCM.
should I have the app periodically poll a backend resource?
this must be the last option to put in consideration. as long as the client number increases you need to scale out backend/server and this is not as simple as putting an another server next to existing one.
the perfect solution will be a push oriented design and best approach will be to register clients to events and server will push clients if that specific events occur.
you need to be more specific about your business case. you had mentioned real-time in your question but what kind of real-time is that. is it a video streaming, chat application or just ordinary rest calls?
Typically, you'll want your server to push updates to the clients because polling is expensive, may not scale well with N number of clients, and will drain your phone batteries faster. Depending on your server technology:
.NET/Core:
May want to take a look at SignalR to push notifications from the backend to your client apps.
Java:
May want to take a look at Atmosphere to push notifications from the backend to your client apps.
I have used SignalR with good results publishing to phone clients. Have not used Atmosphere, but it has good reviews.
I recently learned about the ability of iPhone apps to receive nearly instantaneous notifications to apps notifications to apps.
This is provided in the form of push notifications, a bespoke protocol which keeps an always on data connection to the iPhone and messages binary packets to the app, which pops up alerts incredibly quickly, between 0.5 - 5 seconds from server app send to phone app response time. This is sent as data - rather than SMS - in very very small packets charged as part of the data plan not as incoming messages.
I would like to know if, using Android, there is either a similar facility, or whether it's possible to implement something close to this using Android APIs. To clarify, I define similar as:
Not an SMS message, but some data driven solution
As real time as is possible
Is scalable, i.e., as the server part of a mobile app, I could notify thousands of app instances in seconds
I appreciate the app could be pull based, HTTP request/response style, but ideally I don't want to be polling that heavily just to check for notification; besides which it's like drip draining the data plan.
Firebase Cloud Messaging FCM FAQ is the new version of GCM. It inherits GCM’s core infrastructure to deliver messages reliably on Android, iOS and Chrome. However they'll continue to support GCM because lot of developers are using GCM SDKs today to handle notifications, and client app upgrade takes time.
As of June 26, 2012, Google Cloud Messaging is the preferred way of sending messages to applications running on devices.
Previously (and now deprecated), the service was called Cloud To Device Messaging.
XMPP is a good solution. I have used it for a push enabled, realtime, Android application. XMPP is powerful, highly extensible and easy to integrate and use.
There are loads of free XMPP servers (though out of courtesy you shouldn't abuse them) and there are open source servers you can run on one of your own boxes. OpenFire is an excellent choice.
The library you want isn't Smack as noted above, it's aSmack. But note, this is a build environment - you will have to build the library.
This is a calculation I did on battery life impact of an XMPP solution:
The Android client must maintain a persistent TCP connection by waking up periodically
to send a heartbeat to the XMPP server.
This clearly imposes a cost in terms of power usage. An estimate of this cost is
provided below:
Using a 1400mAh battery (as supplied in the Nexus One and HTC Desire)
An idle device, connected to an 3G network, uses approximately 5mA
The wake-up, heartbeat, sleep cycle occurs every 5 minutes, takes three seconds
to complete and uses 300mA
The cost in battery usage per hour is therefore:
36 seconds 300mA = 3mAh sending heartbeat
3600 seconds 5mA = 5mAh at idle
4:95 + 3 = 7:95mAh combined
A 1400mAh battery lasts approximately 11.6 days at idle and 7.3 days when
running the application, which represents an approximate 37% reduction in
battery life.
However, a reduction in battery life of 37% represents the absolute worst case
in practice given that devices are rarely completely idle.
I recently started playing with MQTT http://mqtt.org for Android as a way of doing what you're asking for (i.e. not SMS but data driven, almost immediate message delivery, scalable, not polling, etc.)
I have a blog post with background information on this in case it's helpful http://dalelane.co.uk/blog/?p=938
(Note: MQTT is an IBM technology, and I should point out that I work for IBM.)
Have a look at the Xtify platform. Looks like this is what they are doing,
Google is depreciating C2DM, but in its place their introducing GCM (Google Cloud Messaging) I dont think theirs any quota and its free! It does require Android 2.2+ though! http://developer.android.com/guide/google/gcm/index.html
If you can depend on the Google libraries being there for you target market, then you may want to piggy back on GTalk functionality (registering a resource on the existing username - the intercepting it the messages as they come in with a BroadcastReceiver).
If not, and I expect you can't, then you're into bundling your own versions of XMPP. This is a pain, but may be made easier if XMPP is bundled separately as a standalone library.
You may also consider PubSubHubub, but I have no idea the network usage of it. I believe it is built atop of XMPP.
I have been looking into this and PubSubHubBub recommended by jamesh is not an option. PubSubHubBub is intended for server to server communications
"I'm behind a NAT. Can I subscribe to a Hub? The hub can't connect to me."
/Anonymous
No, PSHB is a server-to-server
protocol. If you're behind NAT, you're
not really a server. While we've
kicked around ideas for optional PSHB
extensions to do hanging gets ("long
polling") and/or messagebox polling
for such clients, it's not in the core
spec. The core spec is
server-to-server only.
/Brad Fitzpatrick, San Francisco, CA
Source: http://moderator.appspot.com/#15/e=43e1a&t=426ac&f=b0c2d (direct link not possible)
I've come to the conclusion that the simplest method is to use Comet HTTP push. This is both a simple and well understood solution but it can also be re-used for web applications.
There is a new open-source effort to develop a Java library for push notifications on Android, using the Meteor comet server as a backend. You can check it out at the Deacon Project Blog. We need developers, so please spread the word!
Google recently(18May2016) announced that Firebase is now it's unified platform for mobile developers including near real time push notifications.It is also multi-platform :
The company now offers all Firebase users free and unlimited
notifications with support for iOS, Android and the Web.
source
I cannot find where I read it at, but I believe gmail utilizes an open TCP connection to do the e-mail push.
As GTalk is gone from the SDK, it might be a good idea to make a 'standard' push messaging system. That way, only one service has to run, only one extra tcp connection needs to be open. Applications should talk to this service using Intents and should first request permission to send and receive notification from the service. The service should then notify the user a new application wants to send and receive messages. The user will then grant or deny permission, so he stays in control. The application will then register an action + category to the service, so the service knows how to deliver the pushed message.
Would the a good idea or not?
Why dont you go with the XMPP implementation. right now there are so many public servers available including gtalk, jabber, citadel etc. For Android there is one SDK is also available named as SMACK. This we cant say a push notification but using the XMPP you can keep a connection open between client and server which will allow a two way communication. Means Android client and server both can communicate to each other. At present this will fulfill the need of Push in android. I have implemented a sample code and it really works great
I have recently developed http://pushdroid.org its a single application that should be installed on the phone just like google has implemented it in 2.2 this works from 1.5 and is broadcasting via intent.
The problem with GCM is that there is a lot of configuration involved in the process:
You have to add a lot of boilerplate to you Android app
You need to configure an external server to comunicate with the GCM server
You will have to write tests
If you like simple things (like me) you should try UrbanAirship. It is (IMHO) the easiest way to use GCM in your app without doing a lot of configuration. It also gives you a pretty GUI to test that your GCM messages are being delivered correctly.
You can find the docs and getting started guide here
You can find a sample application here
Note: I am not afiliated with UrbanAirship in any way
https://github.com/Guti/Google-Cloud-Messaging--Titanium-/blob/master/src/com/google/android/gcm/GCMRegistrar.java
Its reaily good and working solution for push.
Please try it
They have their listeners which has to be used by you by using their library classes in your code. You need not to bother about pushing. You have to send the message to server server will push the message to the device. They use OAuth. Regarding Protocols, there are two methods using CCS and XMPP. CCS just uses XMPP as an authenticated transport layer, so you can use most XMPP libraries to manage the connection. To send notifications to device you can write code in android app to send as well as your server code. the message sending will be done only by your code. Rest will be taken care by Google Server in GCM case. You can check detail at this link
http://developer.android.com/google/gcm/server.html
Also, for security issues
google cloud messaging security https://groups.google.com/forum/#!topic/android-gcm/M-EevBitbhQ
In case your app is not running then also devices can recieve notification because you have to write code for broadcast listeners. In background it will be listening to server and whenever any message packet will be there it will recieve the message as notification. Android has service you need to not to bother about it. You have only to use those resources using the library class that makes your work easier and let them write if your app is not running then also it recieve notification. Obviously, there would be some listener whick make the app to recieve.Check "Recieve the message" section in this link
http://developer.android.com/google/gcm/client.html
It will acccept request from users also. For GCM it will do. Please check "Send a message"
http://developer.android.com/google/gcm/client.html