Click here to Skip to main content
15,914,323 members
Articles / Programming Languages / C#

Sending Push Notifications to Android with C#

Rate me:
Please Sign up or sign in to vote.
3.33/5 (6 votes)
15 Sep 2017CPOL2 min read 83.1K   10   6
How to send push notifications to Android with C#

Introduction

This tutorial shows you how to use C# to send push notifications to an Android application. You'll create a Android app with some customization that receives push notifications by using Firebase Cloud Messaging (FCM).

What is Push Notification

Push notifications let your application notify a user of new messages or events even when the user is not actively using your application.

How It Works

Image 1

Prerequisites

Below are some prerequisites required:

  1. Latest version of Android Studio
  2. Account in FCM

Completing this tutorial is a prerequisite for all other Notification Hubs tutorials for Android apps.

Creating a Project FCM

  1. Navigate to the Firebase Console, sign in with your Google account crendentials.
  2. Click Add project.

    Image 2

  3. Type in your new Project name and click Create project.

    Image 3

  4. Select newly created project, click on gear at top left and select project settings.

    Image 4

  5. In the project settings, go to cloud messaging tab and make note of the server key.

    Image 5

Create and Connect Your App to the Notification Hub

Create a New Android Project

  1. In Android Studio, start a new Android Studio project.

    Image 6

  2. Choose the Phone and Tablet form factor and the Minimum SDK that you want to support. Then click Next.

    Image 7

  3. Choose Empty Activity for the main activity, click Next, and then click Finish.

Connect App to the Notification Hub

  1. Click Tools -> Firebase on the menu. It will open Firebase Assistant as shown below. Open Set up Firebase Cloud Messaging.

    Image 8

  2. Connect your app to firebase by providing firebase credential and then select your project which was earlier created on Firebase in this demo.
  3. Ideally this is enough to get push notification……further we can discuss how to send customize notification and use it.

    Image 9

Customizing Android App

  1. In the Project View, expand app > src > main > java. Right-click your package folder under Java, click New, and then click Java Class. Add a new class named FirebaseMessagingService.

    Image 10

  2. Copy and paste the below code:
    Java
    package notification.com.test.testnewnotification;
    
    import android.app.NotificationManager;
    import android.app.PendingIntent;
    import android.content.Context;
    import android.content.Intent;
    import android.graphics.BitmapFactory;
    import android.media.RingtoneManager;
    import android.net.Uri;
    import android.support.v4.app.NotificationCompat;
    import android.util.Log;
    
    import com.google.firebase.messaging.RemoteMessage;
    
    /**
     * Created by Ashish.kapoor on 04.09.2017.
     */
    
    public class FirebaseMessagingService 
    extends  com.google.firebase.messaging.FirebaseMessagingService {
        private static final String TAG="FirebaseMessagingServic";
    
        public FirebaseMessagingService() {
        }
    
        @Override
        public void onMessageReceived(RemoteMessage remoteMessage) {
    
            String strTitle=remoteMessage.getNotification().getTitle();
            String message=remoteMessage.getNotification().getBody();
            Log.d(TAG,"onMessageReceived: 
            Message Received: \n" +
            "Title: " + strTitle + "\n" +
            "Message: "+ message);
    
            sendNotification(strTitle,message);
        }
    
        @Override
        public void onDeletedMessages() {
    
        }
    
        private  void sendNotification(String title,String messageBody) {
            Intent[] intents= new Intent[1];
              Intent intent= new      Intent(this,MainActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.putExtra("IncidentNo", title);
            intent.putExtra("ShortDesc", messageBody);
            intent.putExtra("Description",messageBody);
            intents[0]=intent;
            PendingIntent pendingIntent=PendingIntent.getActivities(this,0,
            intents,PendingIntent.FLAG_ONE_SHOT);
            Uri defaultSoundUri= RingtoneManager.getDefaultUri
            (RingtoneManager.TYPE_NOTIFICATION);
            NotificationCompat.Builder notificationbuilder= 
            new NotificationCompat.Builder(this)
                    .setSmallIcon(R.drawable.ic_stat_name)
                    .setContentTitle("Service Now")
                    .setContentText(messageBody)
                    .setAutoCancel(true)
                    .setSound(defaultSoundUri)
                    .setContentIntent(pendingIntent)
            .setLargeIcon(BitmapFactory.decodeResource
            (getResources(), R.mipmap.ic_launcher));;
    
            NotificationManager notificationManager=(NotificationManager) 
            getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.notify(0, notificationbuilder.build());
        }
    }
  3. Open MainActivity class and replace code as below:
    Java
    package notification.com.test.testnewnotification;
    import android.content.Intent;
    import android.net.Uri;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.TextView;
    import com.google.firebase.messaging.FirebaseMessaging;
    public class MainActivity extends AppCompatActivity {
      static   String strSDesc = "ShortDesc";
       static String strIncidentNo = "IncidentNo";
       static String strDesc="IncidentNo";
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            onNewIntent(getIntent());
           FirebaseMessaging.getInstance().
           subscribeToTopic("ServiceNow");
        }
    
        @Override
        public void onNewIntent(Intent intent) {
            Bundle extras = intent.getExtras();
            if (extras != null) {
                setContentView(R.layout.activity_main);
                final TextView IncidentTextView = 
                (TextView) findViewById(R.id.txtIncidentNo);
                final TextView SDescTextView = 
                (TextView) findViewById(R.id.txtShortDesc);
    
                final TextView DescTextView = 
                (TextView) findViewById(R.id.txtDesc);
                 strSDesc = extras.getString("ShortDesc",
                 "ShortDesc");
                 strIncidentNo = extras.getString("IncidentNo",
                 "IncidentNo");
                 strDesc=extras.getString("Description",
                 "IncidentNo");
    
                IncidentTextView.setText(strIncidentNo);
                        SDescTextView.setText(strSDesc);
                DescTextView.setText(strDesc);
            }
        }
    
        public void browser1(View view){
            Intent browserIntent =new Intent
            (Intent.ACTION_VIEW, Uri.parse
            ("https://somebrowser?uri=incident.do?sysparm_query=number="
            +strIncidentNo));
            startActivity(browserIntent);
        }
    }
  4. Open Activity_main.xml and add 3 textView and one command button as below:

    Image 11

    TypeIDDefault Text
    TextViewtxtIncidentNoIncident No
    TextViewtxtShortDescShort Description
    TextViewtxtDescDescription
    ButtonbtnGetDataGet Data OnClick browser1
  5. Build your app and run it.

(Optional) Sending Push Notifications from Firebase Portal

Normally, you would send notifications using a backend server. This is just to test your Notification App.

  1. Open FCM console, select your project and then open Notifications from left toolbar.

    Image 12

  2. Enter Message text, set Target as user segment and select your app. Click on advance option update Title and add Custom data as below and click on send message.

    Image 13

    Image 14

  3. Wow, you received notification message on your mobile, please find the below screenshots for the same.

    Image 15

Creating C# App

Nothing big!

Create your C# application and use the below code:

C#
     public static String SendNotificationFromFirebaseCloud()
        {
            var result = "-1";
            var webAddr = "https://fcm.googleapis.com/fcm/send";
            var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
            httpWebRequest.ContentType = "application/json";
            httpWebRequest.Headers.Add(HttpRequestHeader.Authorization,"key=your FCM senderkey");
            httpWebRequest.Method = "POST";
            using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
            {
                string strNJson = @"{
                    ""to"": ""/topics/ServiceNow"",
                    ""data"": {
                        ""ShortDesc"": ""Some short desc"",
                        ""IncidentNo"": ""any number"",
                        ""Description"": ""detail desc""
  },
  ""notification"": {
                ""title"": ""ServiceNow: Incident No. number"",
    ""text"": ""This is Notification"",
""sound"":""default""
  }
        }";
                streamWriter.Write(strNJson);
                streamWriter.Flush();
            }

            var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                result = streamReader.ReadToEnd();
            }
            return result;
        }

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect TechMahindra
Norway Norway
Technical–minded and resourceful professional with over 13 years of extensive experience credited in requirement gathering & analysis, architectural, component and interface design & development.
Possess hands-on experience in integrating enterprise applications with other and legacy systems, SOA implementation and development, proposing technical architecture, and delivering technical leadership to other solution architects.
Adeptly prepared BizTalk environment plan in terms of BizTalk/SQL Server/SAN/Network topologies, disaster recovery/failover BizTalk environments.
Highly skilled in developing business automation solutions, generating document for project, analysing systems, and finalising solution. Proven expertise and detailed knowledge in technical integration with focus on BizTalk and Azure cloud.
Adept at supporting businesses in achieving success through the implementation, integration, and transition of strategic software systems throughout enterprise.
Exceptional record of executing advanced technology to build innovative business solutions and systems that change easily, and last. An enterprising leader with strong analytical, communication and relationship management skills

Comments and Discussions

 
Questionwhat is /topics/ServiceNow Pin
Member 1381093812-Jul-20 18:57
Member 1381093812-Jul-20 18:57 
QuestionNotification without an app Pin
sanket tiger9-Dec-19 3:40
sanket tiger9-Dec-19 3:40 
QuestionWhere I have to add Device token in this above code? Pin
Member 1138376422-Jul-19 4:36
Member 1138376422-Jul-19 4:36 
QuestionRequired VB .net code to send fcm message Pin
Member 477285727-Jun-18 22:58
Member 477285727-Jun-18 22:58 
GeneralWrong title Pin
Member 1113766329-Nov-17 19:17
Member 1113766329-Nov-17 19:17 
GeneralRe: Wrong title Pin
Ashish K Kapoor3-Jan-18 3:44
professionalAshish K Kapoor3-Jan-18 3:44 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.