How to implement a chat in an Android app with backend Webapi

Asked

Viewed 772 times

6

I’m developing an Android application that consumes services from a Webapi project. In one part of this application it will be necessary to develop chat between two or more people.

Against this background, what is the best approach to developing a chat without using a third-party framework? Messages must go through the Webapi backend and be notified as an event, or communication must be direct between Android devices?

  • 1

    See if this helps: http://stackoverflow.com/questions/24359453/how-do-asp-net-backend-and-web-api-web-service-hosted-on-azure-send-push-notific?answertab=active#tab-top

2 answers

4

I recommend these articles to answer a question:

http://quickblox.com/developers/Android_XMPP_Chat_Sample http://www.appsrox.com/android/tutorials/instachat/ https://github.com/Pirngruber/AndroidIM

A chat apparently does not seem to me to be complex, because by understanding it consists of a two-way messaging service. About the use of Webapi, I believe it will be quiet, because it is only REST services, to which Android can work very well. In this server communication function, I recommend seeing this API: http://developer.android.com/training/volley/index.html

On your issue of the messages being notified as an event, I would add, that in my view, the correct thing would be to use Google Cloud Messaging, for some questions, aid in lower battery consumption among others. GCM’s pretty quiet 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 background).

Answering your other question..

The GCM has some functions/details regarding its idea such as: - receive a notification without having to request data from the server, that is, when the server receives a new message from a user, it will notify the other chat user using GCM, not obliging users to keep the app open. - you will need to register users in GCM, because GCM generates a key for each user that they will need to send the message to. In other words, the communication here will not be client-server, but rather the opposite of server-client. - messages sent by the servers cannot exceed 4kb. This for you will have two functionalities which are: 1) Since chat usually consists of text, maybe 4kb is enough for you; 2) But if it is not, you must implement the flow that the staff usually uses of the function of GCM, which is to receive the notification, which will have a broadcastreceiver waiting for the notification, and when received, will in your server search all the text that the user typed.

You commented the following: "The user sends 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, as the conversation will be in real time. To do this, you must implement a chat status mechanism such as Whatsapp, which changes the icons by placing an OK symbol when viewed. That is, you can make the following mechanism: User 1 sends a message, goes to the server and consequently appears to user 2 in case he has the app open, as the message will be sent 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 is not open, make sure the server knows that, and the message that the other user sends, the server processes and sends by GCM.

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

  • Gustavo. Can you suggest a flow for development of this mechanism? That is, the user sends 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. That’s really what?

4


An alternative to the use of GCM answered by @Gustavobitencourt, is to use Signaler for communication between Webapi and Android.

In the tutorials page of Signaler you can use the same chat example to use on android, implementing the logic of Javascript 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);
        }
    }
}

Implement client on Android to receive messages

(in this example, the client was implemented in 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 a message to the Hub

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

Notes

It is quite simple to implement and avoids relying on GCM for the delivery of messages, since it does not guarantee that your message will arrive on time.

You’ll have control of everything!

Browser other questions tagged

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