Xamarin.Android - Realtime App with SignalR ASP.Net Core

Introduction

 
This article is all about developing real-life mobile applications in Xamarin.Android with SignalR ASP.Net Core.
 
 
 
What is SignalR?
 
SignalR is a library for asp.net developers that revamps the path toward adding progressing web value to applications. Consistent web convenience is the ability to have server code push substance to related clients immediately as it twists up recognizably available, rather than having the server site for a client to request new data.
 
Prerequisites
 
You are required to have basic knowledge of ASP.NET Core Web Application and intermediate level of knowledge Xamarin. Android and a basic idea of Microsoft Azure web app publishing.
  1. SignalR browser Library
  2. Microsoft Azure Account
  3. Microsoft.AspNetCore.SignalR.Client
  4. ASP.Net Core 2.2 or Above
Server Side Application
 
Step 1: - Create a Xamarin Android Project
 
Open Visual Studio-> New Project-> Templates-> Visual C#-> Web -> ASP.NET Core Web Application. Give the project name SignalRCoreServer and select Web Application.
 
(ProjectName: SignalRCoreServer)
 
Step 2: - Add Client-Side Library
 
Next, go to Solution Explorer-> Project Name-> then Right Click to Add and Select Client-Side Library.
 
 
Step 3: - Create Hubs Class
 
Next, go to Solution Explorer-> Project Name-> then Right Click to Add New Folder with name Hubs and inside this folder add a new class with name ViewHub.
 
(Folder Name: Hubs, File: ViewHub)
  1. public class ViewHub : Hub  
  2.     {  
  3.         public async Task MoveFromServer(float x, float y)  
  4.         {  
  5.             Console.WriteLine("Receive position from Server: " + x + "/"+ y);  
  6.             await Clients.Others.SendAsync("ReceiveNewPosition", x, y);  
  7.         }  
  8.     }  
Step 4 : - Configure Startup Class
 
Go to Startup.cs and Add the SignalR service to ConfigureServices Method and also add the following code to the configure method.
  1. //Add to ConfigureServices Method  
  2.   
  3. services.AddSignalR();  
  4.   
  5. //Add to Configure Method  
  6.   
  7. app.UseSignalR(routes =>  
  8. {  
  9.    routes.MapHub<ViewHub>("/movehub");  
  10. });  
Step 5 : - Publish To Azure
 
For the sake of accessing this web app from anywhere, we will deploy to Microsoft Azure cloud by right-clicking on the project and hitting Publish.
 
 
 
This service successfully publishes on Microsoft Azure. Now everyone can use and access this service from the given URL.
 
http://signalrcoreserver.azurewebsites.net/
 
Client-Side
 
Step 1: - Create a Xamarin Android Project
 
Open Visual Studio-> New Project-> Templates-> Visual C#-> Android-> Blank app and give the project name XamarinSignalR.
 
(ProjectName: XamarinSignalR)
 
Step 2: - Add NuGet Package
 
After creating a blank project, first, add Microsoft.AspNetCore.SignalR.Client NuGet packages to this project by right-clicking on References and select manage NuGet packages.
 
Step 3: - Create a Layout
 
Next, open Solution Explorer-> Project Name-> Resources-> Layout-> Main.axml. Open activity_main.axml file and add following code.
 
(FileName: activity_main.axml)
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     xmlns:app="http://schemas.android.com/apk/res-auto"  
  4.     xmlns:tools="http://schemas.android.com/tools"  
  5.     android:background="@color/colorPrimary"  
  6.     android:layout_width="match_parent"  
  7.     android:layout_height="match_parent">  
  8.   
  9. <Button  
  10.        android:id="@+id/btn_start"  
  11.        android:text="START"  
  12.        android:layout_alignParentBottom="true"  
  13.        android:layout_width="match_parent"  
  14.        android:layout_height="wrap_content"/>  
  15.     <View  
  16.         android:id="@+id/view_move"  
  17.         android:background="@color/colorAccent"  
  18.         android:layout_width="100dp"  
  19.         android:layout_height="100dp"/>  
  20. </RelativeLayout>  
Step 4 : - Main Activity
 
Now, go to solution Explorer-> Project Name-> MainActivity file and add the following code and use appropriate namespaces.
 
(FileName: MainActivity.cs)
  1. public class MainActivity : AppCompatActivity, IOnTouchListener  
  2.     {  
  3.         Button btn_start;  
  4.         View view_move;  
  5.   
  6.         HubConnection hubConnection;  
  7.         protected override void OnCreate(Bundle savedInstanceState)  
  8.         {  
  9.             base.OnCreate(savedInstanceState);  
  10.             Xamarin.Essentials.Platform.Init(this, savedInstanceState);  
  11.             SetContentView(Resource.Layout.activity_main);  
  12.   
  13.             btn_start = FindViewById<Button>(Resource.Id.btn_start);  
  14.             view_move = FindViewById<View>(Resource.Id.view_move);  
  15.   
  16.             hubConnection = new HubConnectionBuilder().WithUrl("https://signalrcoreserver.azurewebsites.net/movehub").Build();  
  17.   
  18.             hubConnection.On<floatfloat>("ReceiveNewPosition", (x, y) =>  
  19.              {  
  20.                  view_move.SetX(x);  
  21.                  view_move.SetY(y);  
  22.              });  
  23.   
  24.             btn_start.Click += async delegate   
  25.             {  
  26.                 if (btn_start.Text.ToLower().Equals("start"))  
  27.                 {  
  28.                     if(hubConnection.State == HubConnectionState.Disconnected)  
  29.                     {  
  30.                         try  
  31.                         {  
  32.                             await hubConnection.StartAsync();  
  33.                             btn_start.Text = "stop";  
  34.                         }  
  35.                         catch (System.Exception){}  
  36.                     }                     
  37.                 }  
  38.                 else if (btn_start.Text.ToLower().Equals("stop"))  
  39.                 {  
  40.                     if (hubConnection.State == HubConnectionState.Connected)  
  41.                     {  
  42.                         try  
  43.                         {  
  44.                             await hubConnection.StopAsync();  
  45.                             btn_start.Text = "start";  
  46.                         }  
  47.                         catch (System.Exception) { }  
  48.                     }  
  49.                 }  
  50.             };  
  51.   
  52.             view_move.SetOnTouchListener(this);  
  53.         }  
  54.   
  55.         public bool OnTouch(View v, MotionEvent e)  
  56.         {  
  57.             view_move.SetX(e.RawX);  
  58.             view_move.SetY(e.RawY);  
  59.   
  60.             if(hubConnection.State == HubConnectionState.Connected)  
  61.             {  
  62.                 hubConnection.SendAsync("MoveFromServer", e.RawX, e.RawY);  
  63.             }  
  64.             return true;  
  65.         }  
  66.     }  
Step 5 : - Permissions From Device
 
We need permission from the device because we can use the device’s INTERNET. Please add internet permission to your AndroidManifest.xml.Let's open Solution Explorer-> Properties-> AndroidManifest and let's add the code inside application tags.
  1. <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />  
  2. <uses-permission android:name="android.permission.INTERNET" />  
OUTPUT 
 
 
 

Summary

 
This was the process of creating a Realtime app with SignalR ASP.Net Core in Xamarin.Android, using Visual Studio. Please share your comments and feedback.


Similar Articles