This tutorial help you to create a real time chat applications using SignalR library.
SignalR Lib is an open-source lib introduced by .Net Framwork. Its very easy to use for building applications that require live user interaction or real time data updates.
SignalR Library enables to building real time applications. It use an ASP.NET server library and JavaScript client lib.
Follow some below steps to use SignalR library in android.
Step 1- Download the jar files from below Url.
https://www.dropbox.com/sh/xjwl4jfc5rjaasi/AABFzzeJaH_ymea1j9lmtJFya?dl=0
Create a libs folder inside your package and simply paste these jar files here.
Step 2- Now add "compile files" inside dependencies of build.gradle
compile 'com.google.code.gson:gson:2.3.1'
compile files('libs/signalrclientsdk.jar')
compile files('libs/signalrclientsdkandroidrelease.aar')
Now after this press "Sync Project with Gradle file"
Step 3- Create a class SignalRHubConnection to make connection with SignalR Hub. This class start SignalR and generate a ConnectionId. Each time when user will connect to signalR Hub, ConnectionId will unique.
/* Class to create a SignalR Connection */
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.concurrent.ExecutionException;
import microsoft.aspnet.signalr.client.Credentials;
import microsoft.aspnet.signalr.client.Platform;
import microsoft.aspnet.signalr.client.SignalRFuture;
import microsoft.aspnet.signalr.client.http.Request;
import microsoft.aspnet.signalr.client.http.android.AndroidPlatformComponent;
import microsoft.aspnet.signalr.client.hubs.HubConnection;
import microsoft.aspnet.signalr.client.hubs.HubProxy;
import microsoft.aspnet.signalr.client.hubs.SubscriptionHandler1;
import microsoft.aspnet.signalr.client.hubs.SubscriptionHandler2;
import microsoft.aspnet.signalr.client.transport.ClientTransport;
import microsoft.aspnet.signalr.client.transport.ServerSentEventsTransport;
public class SignalRHubConnection {
// HubConnection
public static HubConnection mHubConnection;
public static HubProxy mHubProxy;
private static Context context;
public static String mConnectionID;
public SignalRHubConnection(Context context) {
this.context = context;
}
//
/*
This function try to connect with chat hub and return connection ID.
*/
public static void startSignalR() {
if (AppUtility.isInternetAvailable(context) == false) {
AppUtility.showAlertDialog(context, context.getString(R.string.app_name), context.getString(R.string.connection_error));
} else {
try {
Platform.loadPlatformComponent(new AndroidPlatformComponent());
Credentials credentials = new Credentials() {
@Override
public void prepareRequest(Request request) {
AppPreferences appPrefs = AppPreferences.getInstance(context);
request.addHeader("UserName", appPrefs.getString(PrefConstants.USER_NAME));
}
};
mHubConnection = new HubConnection("SignalR Hub Url");
mHubConnection.setCredentials(credentials);
mHubProxy = mHubConnection.createHubProxy("SignalR Hub");
ClientTransport clientTransport = new ServerSentEventsTransport(mHubConnection.getLogger());
SignalRFuture<Void> signalRFuture = mHubConnection.start(clientTransport);
signalRFuture.get();
//set connection id
mConnectionID = mHubConnection.getConnectionId();
// To get onLine user list
mHubProxy.on("onGetOnlineContacts",
new SubscriptionHandler1<Object>() {
@Override
public void run(final Object msg) {
try {
Gson gson = new Gson();
String json = gson.toJson(msg);
JSONObject responseObject = new JSONObject(json.toString());
JSONArray jsonArray = responseObject.getJSONArray("messageRecipients");
int sizeOfList = jsonArray.length();
for (int i = 0; i < sizeOfList; i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
JSONArray onLineUserList = jsonObject.getJSONArray("TwingleChatGroupIds");
int onLineUserCount = onLineUserList.length();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
, Object.class);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
}
}
You can use this connection id throughout the app .
Step 4- Now you need to start SignalR and get connection Id(You can defined mConnectionId variable static or can save any where in app) . This task can perform in any activity where you need.
private SignalRHubConnection mSignalRHubConnection;
// crete connection with signalR hub
mSignalRHubConnection = new SignalRHubConnection(WelcomeActivity.this);
SignalRHubConnection.startSignalR();
Step-5 This line of code is use to send chat message
public bool SendChatMessage(ChatMessage chatMessage)
{
try
{
ChatRoom chatRoom;
if (_chatRooms.TryGetValue(chatMessage.TwingleChatGroupId, out chatRoom))
{
chatMessage.TwingleChatGroupId = Guid.NewGuid().ToString();
chatMessage.Timestamp = DateTime.Now;
Clients.Group(chatMessage.TwingleChatGroupId).receiveChatMessage(chatMessage, chatRoom);
return true;
}
else
{
throw new InvalidOperationException("Problem in sending message!");
}
}
catch
{
throw new InvalidOperationException("Problem in sending message!");
}
}
Step 6- This step tell us that how can received chat message
/ This method setup to get received chat message
// This will call from signalR side
private void signalRChatMessageReceived() {
try {
// receiveChatMessage method calling from server side because this same method defined on server side
SignalRHubConnection.mHubProxy.on("receiveChatMessage", new SubscriptionHandler2<Object, Object>() {
@Override
public void run(final Object object1, final Object object2) {
try {
try {
Gson gson = new Gson();
String json = gson.toJson(object1);
JSONObject responseObject = new JSONObject(json.toString());
// responseObject contains your chat message
} catch (Exception e) {
}
}
}, Object.class, Object.class);
} catch (Exception e) {
}
}
6 Comment(s)