Xamarin Android: Create Remote Notifications Using Google GCM

Let’s start.

Step 1
 
Open Visual Studio->New Project->Templates->Visual C#->Android->Blank app. 

Select blank app. Give Project Name and Project Location. 

Step 2

Go to Solution Explorer-> Project Name-> Components, right click to get more components. The new dialog box will open. This dialog box will be used to search the GCM. Add the Google Play Services-GCM Packages.
 

Step 3

Open Solution Explorer-> Project Name->MainActivity.cs. Click Open CS code Page view and add the namespaces. Next, write the code given, below. First, we will check if the current mobile Google Play Store supports it or not. If it does not, the GCM will not work.

Add Namespace, 

  1. using Android.Gms.Common;   

MainActivity.cs

  1. protected override void OnCreate(Bundle bundle)  
  2. {  
  3.     base.OnCreate(bundle);  
  4.     // Set our view from the "main" layout resource  
  5.     SetContentView(Resource.Layout.Main);  
  6.     IsPlayServicesAvailable()  
  7. }  
  8. public bool IsPlayServicesAvailable()  
  9. {  
  10.     int resultCode = GooglePlayServicesUtil.IsGooglePlayServicesAvailable(this);  
  11.     if (resultCode != ConnectionResult.Success)  
  12.     {  
  13.         if (GooglePlayServicesUtil.IsUserRecoverableError(resultCode))  
  14.             txtmsg.Text = GooglePlayServicesUtil.GetErrorString(resultCode);  
  15.         else  
  16.         {  
  17.             Toast.MakeText(this"Sorry, this device is not supported", ToastLength.Short)  
  18.                 .Show();  
  19.             Finish();  
  20.         }  
  21.         return false;  
  22.     }  
  23.     else  
  24.     {  
  25.         Toast.MakeText(this"Google Play Services is available.", ToastLength.Short)  
  26.             .Show();  
  27.         return true;  
  28.     }  
  29. }  

Step 4

Register with GCM in Android Developer Console,

Go to https://console.developers.google.comcreate New Project and give project Name. Refer to the screenshots, given below:

 

Next, enable API for Google Cloud Messaging.
 

 
After enabling API to Create New credentials for Server Key, give the key a name 
 
 
 
 
 
 
Step 5

Register with GCM in the application. Here, we need InstanceID. Hence, go to the developer console to get InstanceID. Find Project information and get the project number.
 
 
 

 

Step 6

Next is Implementation Registration Intent Service in Android Application. Create a new class Registrationintentservice.cs and give the  code, shown below:
 
 

C# Code

  1. [Service(Exported = false)]  
  2. class RegistrationIntentService: IntentService  
  3. {  
  4.     static readonly string[] Topics = {  
  5.         "global"  
  6.     };  
  7.     public RegistrationIntentService(): base("RegistrationIntentService")  
  8.     {}  
  9.     protected override void OnHandleIntent(Intent intent)  
  10.     {  
  11.         try  
  12.         {  
  13.             Log.Info("RegistrationIntentService""Calling InstanceID.GetToken");  
  14.             lock(this)  
  15.             {  
  16.                 var instanceID = InstanceID.GetInstance(this);  
  17.                 var token = instanceID.GetToken(  
  18.                     "YOUR_INSTANCE_ID", GoogleCloudMessaging.InstanceIdScope, null);  
  19.                 Log.Info("RegistrationIntentService""GCM Registration Token: " + token);  
  20.                 SendRegistrationToAppServer(token);  
  21.                 SubscribeToTopics(token, Topics);  
  22.             }  
  23.         }  
  24.         catch (Exception e)  
  25.         {  
  26.             Log.Debug("RegistrationIntentService""Failed to get a registration token");  
  27.             return;  
  28.         }  
  29.     }  
  30.     void SendRegistrationToAppServer(string token)  
  31.     {  
  32.         // Add custom implementation here as needed.  
  33.     }  
  34.     void SubscribeToTopics(string token, string[] topics)  
  35.     {  
  36.         foreach(var topic in topics)  
  37.         {  
  38.             var pubSub = GcmPubSub.GetInstance(this);  
  39.             pubSub.Subscribe(token, "/topics/" + topic, null);  
  40.         }  
  41.     }  
  42. }  

Step 7

Next, run Registrationintentservice.cs. Hence, again modify MainActivity.cs;  open Solution Explorer-> Project Name-> MainActivity.cs.

Follow the code given below:
  1. protected override void OnCreate(Bundle bundle)  
  2. {  
  3.     base.OnCreate(bundle);  
  4.     // Set our view from the "main" layout resource  
  5.     SetContentView(Resource.Layout.Main);  
  6.     txtmsg = FindViewById < TextView > (Resource.Id.txtmsg);  
  7.     btnsend = FindViewById < Button > (Resource.Id.btnsend);  
  8.     if (IsPlayServicesAvailable())  
  9.     {  
  10.         var intent = new Intent(thistypeof(RegistrationIntentService));  
  11.         StartService(intent);  
  12.     }  
  13. }  

Step 8

Next is Implementation InstanceId Listener Service in Android Application. Create new class InstanceIdListenerService.cs and give the following code: 

 

C# Code

  1. [Service(Exported = false), IntentFilter(new []  
  2. {  
  3.     "com.google.android.gms.iid.InstanceID"  
  4. })]  
  5. class MyInstanceIDListenerService: InstanceIDListenerService  
  6. {  
  7.     // When a token refresh happens, start my RegistrationIntentService:  
  8.     public override void OnTokenRefresh()  
  9.     {  
  10.         var intent = new Intent(thistypeof(RegistrationIntentService));  
  11.         StartService(intent);  
  12.     }  
  13. }  

Step 9

Next is Implementation GCM Listener Service in Android Application. Create new class GcmListenerService.cs and give the following code. This code receives the Notifications Title, Icon, and Message.

  1. [Service(Exported = false), IntentFilter(new []  
  2. {  
  3.     "com.google.android.c2dm.intent.RECEIVE"  
  4. })]  
  5. public class MyGcmListenerService: GcmListenerService  
  6. {  
  7.     public override void OnMessageReceived(string from, Bundle data)  
  8.     {  
  9.         // Extract the message received from GCM:  
  10.         var message = data.GetString("message");  
  11.         Log.Debug("MyGcmListenerService""From: " + from);  
  12.         Log.Debug("MyGcmListenerService""Message: " + message);  
  13.         // Forward the received message in a local notification:  
  14.         SendNotification(message);  
  15.     }  
  16.     // Use Notification Builder to create and launch the notification:  
  17.     void SendNotification(string message)  
  18.     {  
  19.         var intent = new Intent(thistypeof(MainActivity));  
  20.         intent.AddFlags(ActivityFlags.ClearTop);  
  21.         var pendingIntent = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.OneShot);  
  22.         var notificationBuilder = new Notification.Builder(this)  
  23.         .SetSmallIcon(Resource.Drawable.Icon) //Icon  
  24.         .SetContentTitle("C#Corner"//Title  
  25.         .SetContentText(message) //Message  
  26.         .SetAutoCancel(true)  
  27.         .SetContentIntent(pendingIntent);  
  28.         var notificationManager = (NotificationManager) GetSystemService(Context.NotificationService);  
  29.         notificationManager.Notify(0, notificationBuilder.Build());  
  30.     }  
  31. }  

Step 10

Go to Solution Explorer-> Project Name-> References and right click to Manage NuGet Packages, the new dialog box will open. This dialog box is used to search Json and install the Newtonsoft.Json Packages.

 

Step 11

Finally, create Button Send Event, which is next to open MainActivity.cs and give the following code for Button click, before adding a namespace:

  1. using Newtonsoft.Json.Linq;  
  2. using System.Net.Http;  
  3. using System.Net.Http.Headers;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6. protected override void OnCreate(Bundle bundle)  
  7. {  
  8.     base.OnCreate(bundle);  
  9.     // Set our view from the "main" layout resource  
  10.     SetContentView(Resource.Layout.Main);  
  11.     btnsend.Click += (object sender, EventArgs e) =>  
  12.         {  
  13.             OnButtonClicked(sender, e);  
  14.         };  
  15. }  
  16. public async void OnButtonClicked(object sender, EventArgs args)  
  17. {  
  18.     var MESSAGE = txtmsg.Text;  
  19.     var jGcmData = new JObject();  
  20.     var jData = new JObject();  
  21.     jData.Add("message", MESSAGE);  
  22.     jGcmData.Add("to""/topics/global");  
  23.     jGcmData.Add("data", jData);  
  24.     string a;  
  25.     var url = new Uri("https://gcm-http.googleapis.com/gcm/send");  
  26.     try  
  27.     {  
  28.         using(var client = new HttpClient())  
  29.         {  
  30.             client.DefaultRequestHeaders.Accept.Add(  
  31.                 new MediaTypeWithQualityHeaderValue("application/json"));  
  32.             client.DefaultRequestHeaders.TryAddWithoutValidation(  
  33.                 "Authorization""key=" + API_KEY);  
  34.             Task.WaitAll(client.PostAsync(url, new StringContent(jGcmData.ToString(), Encoding.Default, "application/json"))  
  35.                 .ContinueWith(response =>  
  36.                     {  
  37.                         Console.WriteLine(response);  
  38.                         Console.WriteLine("Message sent: check the client device notification tray.");  
  39.                     }));  
  40.         }  
  41.     }  
  42.     catch (Exception e)  
  43.     {  
  44.         Console.WriteLine("Unable to send GCM message:");  
  45.         Console.Error.WriteLine(e.StackTrace);  
  46.     }  
  47. }  

Step 12

Next, the final step is required to give the permission for Notifications; open AndroidManifest.xml.

  1. <receiver android:name="com.google.android.gms.gcm.GcmReceiver" android:exported="true" android:permission="com.google.android.c2dm.permission.SEND">  
  2.   
  3.     <intent-filter>  
  4.   
  5.         <action android:name="com.google.android.c2dm.intent.RECEIVE" />  
  6.   
  7.         <action android:name="com.google.android.c2dm.intent.REGISTRATION" />  
  8.   
  9.         <category android:name="GCM.GCM" />  
  10.   
  11.     </intent-filter>  
  12.   
  13. </receiver>  
  14.   
  15. </application>  
  16.   
  17. <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />  
  18.   
  19. <uses-permission android:name="android.permission.WAKE_LOCK" />  
  20.   
  21. <uses-permission android:name="android.permission.INTERNET" />  
  22.   
  23. <uses-permission android:name="GCM_ANDROID.GCM_ANDROID.permission.C2D_MESSAGE" />  

Step 13

Press F5 or build and run the Application. First image depicts sending the notification message and the next image is used to depict the received notification.

 
 
 

Finally, we successfully created remote notifications, using Google GCM.


Similar Articles