Chat with in-app notifications

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

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

Does anyone know a way to do this?

Author: brasofilo, 2014-07-02

2 answers

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 often the 3G connection is very slow, this would congestion the network, and the user would not be able to navigate efficiently. So from there, Google created a bus of servers that do this communication for us, thus avoiding congestion in case the internet connection is too bad.

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

Works as follows:

The app registers in your GCM account and a key

Your app must deliver this Key to your server that you want to communicate with the app

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

GCM queues the notifications and deliver them to your Mobile

Your mobile notification service delivers the notification to your code.

That is, the servers communicate with the GCM and the GCM with your mobile, this makes the mobile only need a connection to be open: that of the GCM. This allows me scalability and avoids connection problems. This is how Facebook and whatsapp apps work. Your app doesn't need to stay open, and you don't need background threads listening to connections, you you only need to set up one 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 about this here , with explanations of how to implement the client part and the server part and more.

You can also find a very well explanatory tutorial video here .

Hope I helped!!!

I had this answers in a question of mine I hope to have help. source: here !

 5
Author: Guilherme, 2017-04-13 12:59:39

Well, if your application queries an external database , you can, instead of making a thread, make 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 him that there is a new message.

Be aware that because your application performs the query in an external database, perhaps the check interval should be equal or more than an hour.

Service example:

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

    @Override
    public IBinder onBind(Intent arg0) 
    {
        return null;
    }

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

        myTask = new Task();
        serviceHandler = new Handler();
        serviceHandler.postDelayed(myTask,1000);

        return START_STICKY;

    }


    @Override
    public void onDestroy() 
    {
        super.onDestroy();

        try
        {
            serviceHandler.removeCallbacks(myTask);
            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
        intent.setAction("android.intent.action.MAIN");
        intent.addCategory("android.intent.category.LAUNCHER");
        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
    {
        @Override
        public void run() 
        {
            //VERIFICAR AQUI SE HÁ UMA NOVA MENSAGEM
            /*

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


            */

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


    }
}

Also think that if the user turns off 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";

    @Override
    public void onReceive(Context arg0, Intent arg1) {

         if(arg1.getAction().equals(BOOT_COMPLETED_ACTION))
         {
            Intent myIntent = new Intent(arg0, MessageVerifyService.class);
            arg0.startService(myIntent);
            Toast.makeText(arg0, "Serviço verificador de mensagens iniciado novamente!",Toast.LENGTH_LONG).show();
         }

    }

}

You need to put this code in AndroidManifest.xml:

Permission:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

Statement of Service and receiver within the application Tag:

    <!-- SERVICES -->
    <service
            android:name=".MessageVerifyService"
            android:exported="false"
            android:process=":verifymessage" />

        <!-- RECEIVER QUE INICIA JUNTO COM O DISPOSITIVO -->
        <receiver
                android:name=".MessageVerifyServiceReceiver"
                android:exported="false"
                android:label="@string/app_name"
                android:process=":receiver" >
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </receiver>
 4
Author: Cícero Moura, 2014-07-02 12:46:39