How to implement a chat in an Android application with WebApi backend

6

I'm developing an Android application that consumes services from a WebApi project. In one part of this application will be necessary the development of chat between two or more people.

Given this scenario, what is the best approach to developing a chat without using a third party framework? Should messages go through the WebAPI backend and be notified as an event, or should the communication be direct between Android devices?

    
asked by anonymous 05.03.2015 / 18:47

2 answers

4

An alternative to using GCM answered by @GustavoBitencourt is to use SignalR for communication between WebApi and Android.

On the SignalR SignalR tutorials page you can use the same chat example to use on android, implementing Javascript logic on Android using the SignalR Client for Java / Android

You can follow these steps to take a chat test:

Deploy a Hub in your web solution

using System;
using System.Web;
using Microsoft.AspNet.SignalR;
namespace SignalRChat
{
    //Nome que será utilizado para criação do hub no cliente
    [HubName("chatHub")]
    public class ChatHub : Hub
    {
        //Método utilizado para enviar a mensagem para o cliente
        [HubMethodName("send")]
        public void Send(string name, string message)
        {
            // Método que será chamado no cliente.
            // Esse método precisa ser implementado no Android.
            Clients.All.broadcastMessage(name, message);
        }
    }
}

Deploy the Android client to receive the messages

(in this example, the client was deployed on an Android Service)

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Logger logger = new Logger() {
            @Override
            public void log(String message, LogLevel level) {
                Log.d("SignalR-Test", level.toString() + ":" + message);
            }
        };

    HubConnection connection = new HubConnection(server,queryStringQualquer,true, logger);

    HubProxy proxy = connection.createHubProxy("chatHub");

    //Foi utilizado o tipo de transporte LongPolling, mas pode ser modificado
    //pra o transport de sua preferência.
     SignalRFuture<Void> awaitConnection = connection.start(new LongPollingTransport(logger));

     try {
        awaitConnection.get();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }

    proxy.on( "broadcastMessage", new SubscriptionHandler2<String, String>() {
        @Override
        public void run(String nome, String msg) {
            //Aqui a mensagem é recebida e você exibe ela da forma que preferir                
        }
    }, String.class, String.class);
}

Example of how to send message to Hub

proxy.invoke("send","Malloni","Olá, tudo bem?");

Notes

It is simple enough to implement and avoids relying on GCM for delivering messages, as it does not guarantee that your message arrives on time.

You will have control of everything!

    
10.04.2015 / 16:00
4

I recommend these articles to answer an issue:

link link link

A chat apparently does not seem to me to be complex, because by understanding it consists of a two-way messaging service. On the use of WebApi, I believe it will be quiet, since it is only REST services, to which Android can work very well. In this function of communication with server, I recommend to see this API: link

On your issue of the messages being notified as an event, I would like to add that, in my opinion, the correct thing would be for you to use Google Cloud Messaging, for some questions, help with the lowest battery consumption among others. GCM is very easy to work with. I recommend you take a look at it to do the messaging / notification service, when the user is not with the application open (in the background).

Answering your other question ..

GCM has some functions / details regarding your idea like: - receive a notification without having to request data from the server, that is, the server when it receives a new message from a user, it will notify the other user of the chat using GCM, not forcing users to keep the app open. - you will need to register the users in GCM, since GCM generates a key for each user to which it will need to send the message. That is, the communication here will not be client-server, but rather, the inverse that is server-client. - messages sent by servers can not exceed 4kb. This for you will have two features that are: 1) Since chat usually consists of text, maybe 4kb is enough for you; 2) But if it is not, you should implement the stream that the staff generally uses from the GCM function, which is to receive the notification, which will have a broadcastreceiver waiting for the notification, and when received, will on your server fetch all text that the user typed.

You commented as follows: "The user submits a post to the WebApi that stores the message information and creates an event using GCM, which in turn notifies the second user who receives the message." Yes, that's basically it, but with one more detail. You agree that if both chat users have the app open, you will not need to use GCM because the chat will be in real time. To do this, you must implement a status mechanism for conversations such as WhatsApp, which changes the icons by placing an OK symbol when it was viewed. That is, you can do the following mechanism: User 1 sends message, goes to the server and consequently will appear for user 2 if he has the app open, as he will be sent the message to him in the chat. Make a mechanism to which you will know if the user will be with the active / open application. If it does not have the app open, let the server know about it, and the message that the other user sends, the server processes and sends via GCM.

Maybe it was a bit embarrassing to explain what I tried to explain, but try to take a look at the links to see if it helps clarify:

09.04.2015 / 14:55