Chat with app notifications

Posted on

Question :

I have an Android application that through it, the user can send a message to the administrator (me). I wanted to do something cooler in this communication, I would like it when I respond to the message, it appears in the application that it has a new unread message, ie it receives as a notification.

I was thinking of some possible solutions, but I think it should not be ideal, it would do something like this:
Inside my app would make a Thread that would be every second querying a database and checking if it has any column of a table that is with unread status, if yes it changed my app. I think it’s not the best thing to do and I think it would not be so easy to implement.

Does anyone know a way to do this?


Answer :

Actually leaving apps and threads running in the background with open connections is not recommended. Imagine if every app had an open port and an established connection waiting for a response from the server? In a mobile environment where the 3G connection is often very slow, it would clog the network, and the user would not be able to navigate efficiently. So from there, Google has created a server bus that makes this communication to us, thus avoiding congestion in case the internet connection is too bad.

This bar is called GCM (Google Cloud Messaging), quoted in the comments by our friend Wakim.

It works as follows:

The app registers to your GCM account and a Key is generated

Your app should deliver this key to your server that wants to communicate with the app

The server sends a notification to the GCM servers with the key of your application

GCM queues notifications and delivers them to your mobile

Your phone’s notification service delivers the notification to your code.

That is, the servers communicate with GCM and GCM with your cellphone, this means that the cell phone only needs an open connection: that of GCM. This allows me to scale and avoids connection problems. This is how facebook apps and whatsapp works. Your app does not need to stay open, and you do not need background threads listening for connections, you just need to set up a service in your app and the operating system does the rest.

Obviously my explanation is very brief, and very superficial. You can find more details on this HERE , with explanations of how to implement the customer part and the part of the server and more.

You can also find a very well-explained video tutorial HERE .

I hope I have helped !!!

I had this answer in a question I hope to have helped.
source: HERE !


Well, if your application queries an external database, you can, instead of doing a thread, do a service that does just what you said.

The difference is that even with the application closed and the user doing other things or even with the screen off, you can notify them that a new message exists.

Be aware that as your application performs the query in an external database, the check range may be one or more times.

Example service:

public class MessageVerifyService extends Service
    private Handler serviceHandler;
    private Task myTask;
    NotificationManager notify;

    public IBinder onBind(Intent arg0) 
        return null;

    public int onStartCommand(Intent intent, int flags, int startId) 
        notify = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);

        myTask = new Task();
        serviceHandler = new Handler();

        return START_STICKY;


    public void onDestroy() 

            serviceHandler = null;

        catch(Exception e)


    public void showNotificationAlert(int numMensagens)
        Intent intent= new Intent(getBaseContext(), MainActivity.class); // coloque sua activity para ver as mensagens não lidas
        Notification note = new Notification(R.drawable.ic_launcher,"Mensagens não Lidas",System.currentTimeMillis());
        PendingIntent i =PendingIntent.getActivity(getBaseContext(), 0,intent,0);

        note.setLatestEventInfo(getBaseContext(),"Mensagens não lidas","Existem " + numMensagens + " mensagens não lidas",null);
        // Hide the notification after its selected
        note.flags |= Notification.FLAG_AUTO_CANCEL;
        note.defaults |= Notification.DEFAULT_SOUND ;
        notify.cancel(0x1);//retira se houver
        notify.notify(0x1, note);

    class Task implements Runnable
        public void run() 

             int numMens = verificarMensagensNaoLidas();
             if(numMens > 0)


            //executa de uma em uma hora
            serviceHandler.postDelayed(this,3600000);// 1 hora


Consider also that if the user hangs up the phone, you should return your verification service, then also implement a Receiver class:

public class MessageVerifyServiceReceiver extends BroadcastReceiver {

    private final String BOOT_COMPLETED_ACTION = "android.intent.action.BOOT_COMPLETED";

    public void onReceive(Context arg0, Intent arg1) {

            Intent myIntent = new Intent(arg0, MessageVerifyService.class);
            Toast.makeText(arg0, "Serviço verificador de mensagens iniciado novamente!",Toast.LENGTH_LONG).show();



You need to put this code in AndroidManifest.xml:


<uses-permission android_name="android.permission.RECEIVE_BOOT_COMPLETED" />

Service declaration and receiver within Tag application:

    <!-- SERVICES -->
            android_process=":verifymessage" />

                android_process=":receiver" >
                <action android_name="android.intent.action.BOOT_COMPLETED" />
                <category android_name="android.intent.category.LAUNCHER" />


Leave a Reply

Your email address will not be published. Required fields are marked *