Chat with notifications in the app

Asked

Viewed 1,997 times

6

I have an Android application that inside it, the user can send message to the administrator(eu). I wanted to do something more cool in this communication, I would like when I answered the message, appeared in the application that it has a new unread message, IE, receives as a notification.

I was thinking about some possible solutions, but I don’t think it should be ideal, I would do something like this:
Inside my app would make a Thread that stayed every second by consulting a database and checking if you have any columns of a table that is unread status, in case I would change my app. I believe it is not the best thing to do and I think it would not be so easy to implement.

Someone knows a way to do it?

  • I don’t see any other way to do it, I think you really need to have a threar running.

  • 4

    I don’t know if that’s what you want, but take a look at http://developer.android.com/google/gcm/index.html

  • That’s right Paul, thank you

2 answers

5

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

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

It works as follows:

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

your app must deliver this Key to your server that you want 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 phone

Your mobile notification service delivers the notification to your code.

That is, the servers communicate with GCM and GCM with your phone, this makes the phone only need a connection to be open: the GCM. This allows me to scale and avoids connection problems. This is how facebook and Whatsapp apps work. Your app doesn’t need to stay open, and doesn’t need background threads listening to 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 about this HERE, with explanations on how to implement the client part and the server part and more.

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

I hope I’ve helped!!!

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

  • 1

    Just playing the boring heheh, I know you meant "listening to connection" in the sense of "data being trafficked through the connection", but strictly speaking what GCM does is keep an open connection to the GCM server (with right to heartbeats between device and server to keep it open) and the useful data only travel as necessary, without doing Polling. Question of use of words.

  • I’m doing a read on GCM and it seems to me to be the solution, I haven’t started to implement it yet, but for example, with it is possible for an application I send message that goes to the web and is saved in some bank and then I reply and the reply message arrives in the client? The tutorials and materials I found only speak in exchange for sending a message from the Web and nothing like an exchange.

  • I see that my answer to Guilherme’s question spread. hauahauhauahau. The Whatsapp app uses exactly this to be able to exchange messages. If you implement an XMPP server there is yes possibility of message exchange and not only receiving in the app --> GCM XMPP SERVER

  • haha sharing his knowledge Ighor Augusto

4

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 turned off, you can notify him that there is a new message.

Be aware that as your application performs the query in an external database, maybe the check interval should be equal to or more than one 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 shuts down 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 on Androidmanifest.xml:

Permission:

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

Declaration of service and receiver within the tag application:

    <!-- 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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.