Question

I'm trying to do an instant messaging app for Android, I have made the interface to send the messages to my database and it works fine. The problem is I dont have idea about how I can make a listener to receive the in coming messages from the database.

I was thinking to use a Timer to ask every 5 or 10 seconds and in case there are new messages for the client, download it. I tried it and if I'm using the app it works but when I'm use the same code to notify the client about new messages the timer doesn't work and the client never is notified.

Hope you can help me with some ideas. Thanks.

Was it helpful?

Solution

using a timer would abcolutly kill the phones battery at that interval. You need to look into using Google Cloud Messaging or XMPP to notify the device that a new message arrived

OTHER TIPS

As the previous answers suggested using timer is a really bad idea cause of battery life . google cloud messaging / XMPP sounds good and you can use broadcast receiver to handle the incoming messages.

check out this tutorial from approx : Create an Instant Messaging app using Google Cloud Messaging (GCM)

shows a clear implementation of the above mentioned techniques . it also has a basic server backend written in java, running on google app engine . helped me a lot building my instant messenger project in android.

In addition I would suggest you can also use MQTT to implement instant messaging in your android application. Use Eclipse Paho Android library to implement MQTT. It has it own onMessageArrived() method which is called whenever a new message is received.

Checking for new messages in every 5 to 10 seconds is a bad practise as it drains battery. MQTT establishes a low level TCP connection with the MQTTserver which is ideal for instant messaging.

Messages are automatically backed by the API when they are received, which deletes them from the server.

And polling 10 times means reading, processing and flushing the buffer 10 times, so it's not like you will still find data from the first poll during the 7th poll.

Use the Broadcast Receiver to handle the incoming messages Don't use pull the connection after every 5 min or 10 min it would battery consuming use GCM(Google Cloud Messaging)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top