简体   繁体   中英

Construct Notification for Xamarin Android Application

Am trying to create a notification that will notify user when alarm matures, am calling the Notification code in my OnCreate method, so i expect to see it when i launch my Activity but my code here seems to have a problem, any help to get the App to notify will greatly be appreciated... Here is what i got so far

 class SecondActivity : AppCompatActivity
    {
    static readonly int mid = 1000;
        static readonly string CHANNEL_ID = "location_notification";
          protected override void OnCreate(Bundle onSavedInstanceState){
      //Notification code
              NotificationChannel channel = null;
            Intent intent=new Intent(this, typeof(SecondActivity));
            //Construct TaskStack builder for pending intent
            Android.App.TaskStackBuilder taskStackBuilder = Android.App.TaskStackBuilder.Create(this);
            //Add intent to backstack
            taskStackBuilder.AddNextIntentWithParentStack(intent);
            //Construct pending intent to open desired activity 
            PendingIntent pendingIntent = taskStackBuilder.GetPendingIntent(0, PendingIntentFlags.UpdateCurrent);
           //Enque notification to inform the user that the alarm has matured
            NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
            .SetSmallIcon(Resource.Drawable.abc_tab_indicator_mtrl_alpha)
            .SetContentTitle("Alarm")
              .SetContentIntent(pendingIntent);
               .SetContentText("Alarm Time has matured");
              NotificationManager notificationManager = 
              (NotificationManager)GetSystemService(Context.NotificationService);
            notificationManager.Notify(mid, mBuilder.Build());
            channel = notificationManager.GetNotificationChannel(channelName);
            notificationManager.CreateNotificationChannel(channel);         
      }
}

What Am i doing wrong?, Thanks

You need to do a lot of things before your notification can work, Microsoft documentation provides a very easy way of doing that...

 class SecondActivity : AppCompatActivity
    {
     //Declare notification ID and Channel ID In your class so you can use them from any method
         static readonly int NOTIFICATION_ID = 1000;
        static readonly string CHANNEL_ID = "location_notification";
        protected override void OnCreate(Bundle savedInstanceState){

        
          }
       //Define the method you will use to call notification 
   }
      void createNotificationChannel()
        {
            if (Build.VERSION.SdkInt < BuildVersionCodes.O)
            {
                // Notification channels are new in API 26 (and not a part of the
                // support library). There is no need to create a notification
                // channel on older versions of Android.
                return;
            }
            var name = Resources.GetString(Resource.String.channel_name);
            var description = GetString(Resource.String.channel_description);
            var channel = new NotificationChannel(CHANNEL_ID, name, NotificationImportance.Default)
            {
                Description = description
            };
            var notificationManager = (NotificationManager)GetSystemService(NotificationService);
            notificationManager.CreateNotificationChannel(channel);
        }
   //Use a button to send the notification to the operating system
private void notifier(object sender, EventArgs e){

            Intent intent=new Intent(this, typeof(SecondActivity));
            //Construct TaskStack builder for pending intent
            Android.App.TaskStackBuilder taskStackBuilder = Android.App.TaskStackBuilder.Create(this);
            //Add intent to backstack
            taskStackBuilder.AddNextIntentWithParentStack(intent);
            //Construct pending intent to open desired activity 
            PendingIntent pendingIntent = taskStackBuilder.GetPendingIntent(0, PendingIntentFlags.UpdateCurrent);
            //Enque notification to inform the user that the alarm has matured
            NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, CHANNEL_ID)
           .SetSmallIcon(Resource.Drawable.abc_tab_indicator_mtrl_alpha)
            .SetContentTitle("Alarm")
            .SetContentText("Alarm Time has matured")
   
            .SetShowWhen(false).SetContentIntent(pendingIntent);
            NotificationManagerCompat notificationManager = NotificationManagerCompat.From(this);
            notificationManager.Notify(NOTIFICATION_ID, mBuilder.Build());
}
}
}

If you follow the instructions on this page then your notification should show without so much hassle https://docs.microsoft.com/en-us/xamarin/android/app-fundamentals/notifications/local-notifications-walkthrough

am calling the Notification code in my OnCreate method

You could not call notification on OnCreate method directly. Generaly We will use button click event or another separated task event to call Notification.

Second, as SushiHangover's said, you need to CreateNotificationChannel before publish local notification.

You can refer to Notification channels to add notification channel:

void CreateNotificationChannel()
{
    if (Build.VERSION.SdkInt < BuildVersionCodes.O)
    {
        // Notification channels are new in API 26 (and not a part of the
        // support library). There is no need to create a notification
        // channel on older versions of Android.
        return;
    }

    var channelName = Resources.GetString(Resource.String.channel_name);
    var channelDescription = GetString(Resource.String.channel_description);
    var channel = new NotificationChannel(CHANNEL_ID, channelName, NotificationImportance.Default)
                  {
                      Description = channelDescription
                  };

    var notificationManager = (NotificationManager) GetSystemService(NotificationService);
    notificationManager.CreateNotificationChannel(channel);
}

And pulish notification:

// Instantiate the builder and set notification elements:
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
    .SetContentTitle ("Sample Notification")
    .SetContentText ("Hello World! This is my first notification!")
    .SetSmallIcon (Resource.Drawable.ic_notification);

// Build the notification:
Notification notification = builder.Build();

// Get the notification manager:
NotificationManager notificationManager =
    GetSystemService (Context.NotificationService) as NotificationManager;

// Publish the notification:
const int notificationId = 0;
notificationManager.Notify (notificationId, notification);

Note: The CHANNEL_ID should be the same both on creating channel and publishing notification. Generally, we will use the package name as the channel id.

The full sample code as follows:

private void Button_Click(object sender, EventArgs e)
{
    // create notification channel
    if (Build.VERSION.SdkInt < BuildVersionCodes.O)
    {
        // Notification channels are new in API 26 (and not a part of the
        // support library). There is no need to create a notification
        // channel on older versions of Android.
        return;
    }

    var channelName = "Notify user";
    var channelDescription = "first local notification";
    var channel = new NotificationChannel("com.companyname.appandroidlistview", channelName, NotificationImportance.Default)
    {
        Description = channelDescription
    };

    var notificationManager = (NotificationManager)GetSystemService(NotificationService);
    notificationManager.CreateNotificationChannel(channel);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "com.companyname.appandroidlistview")
            .SetContentTitle("Sample Notification")
            .SetContentText("Hello World! This is my first notification!")
            .SetSmallIcon(Resource.Drawable.icon);

    // Build the notification:
    Notification notification = builder.Build();

    // Get the notification manager:
    NotificationManager notificationManager =
        GetSystemService(Context.NotificationService) as NotificationManager;

    // Publish the notification:
    const int notificationId = 0;
    notificationManager.Notify(notificationId, notification);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM