首页 > 解决方案 > 尝试使用 xamarin 显示通知

问题描述

我正在按照本指南实施使用接近信标的应用程序:

https://github.com/Estimote/Xamarin-Bindings

我从 github 下载了 ExampleApp 文件夹并安装了 Estimote.Android.Proximity。它工作正常。

但这是我的问题:

//ExampleApps/Example.Android.Proximity/MainActivity.cs

class MyEnterHandler : Java.Lang.Object, Kotlin.Jvm.Functions.IFunction1
    {
        public Java.Lang.Object Invoke(Java.Lang.Object p0)
        {
            IProximityZoneContext context = (IProximityZoneContext)p0;

            Log.Debug("app", $"MyEnterHandler, context = {context}");

            return null;
        }
    }

而不是 Log.Debug 我想创建我的通知.. 我该怎么做?

我尝试使用此脚本创建通知:

 if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
        {
            // Android 8.0 and up require a channel for the notifications
            var channel = new NotificationChannel(channelId, "Bluetooth activity", NotificationImportance.Low);
            var notificationManager = this.GetSystemService(Context.NotificationService) as NotificationManager;
            notificationManager.CreateNotificationChannel(channel);
        }
        var notification = new NotificationCompat.Builder(this, channelId)
                .SetSmallIcon(global::Android.Resource.Drawable.IcDialogInfo)
                .SetContentTitle("Proximity")
                .SetContentText("Proximity demo is scanning for beacons")
                .Build();

但是我有 this.getSystemService 的问题(我在“MyEnterHandler 类”中没有上下文)

标签: c#androidxamarinibeaconproximity

解决方案


  • 创建通知通道
void CreateNotificationChannel()
        {
            if (Build.VERSION.SdkInt < BuildVersionCodes.O)
            {
                return;
            }

        var channel = new NotificationChannel(CHANNEL_ID, Resources.GetString(Resource.String.app_name), NotificationImportance.Default)
        {
            Description = ""
        };

        var notificationManager = (NotificationManager)GetSystemService(NotificationService);
        notificationManager.CreateNotificationChannel(channel);
    }
  • 使用 notificationManager 发送通知
var pendingIntent = PendingIntent.GetActivity(this, MainActivity.NOTIFICATION_ID, intent, PendingIntentFlags.OneShot);

            var notificationBuilder = new NotificationCompat.Builder(this, MainActivity.CHANNEL_ID)
                                      .SetSmallIcon(Resource.Drawable.outline_message_24)
                                      .SetContentTitle(Resources.GetString(Resource.String.app_name))
                                      .SetContentText(messageBody)
                                      .SetAutoCancel(true)
                                      .SetContentIntent(pendingIntent);

            var notificationManager = NotificationManagerCompat.From(this);
            notificationManager.Notify(MainActivity.NOTIFICATION_ID, notificationBuilder.Build());

推荐阅读