确保已设置
LaunchMode.SingleTop
在您的
MainActivity
:
启动模式。单顶
[Activity(~~~, LaunchMode = LaunchMode.SingleTop, ~~~]
public class MainActivity
{
~~~~
在您的
主要活动
(FormsAppCompatActivity子类)添加
OnNewIntent
覆盖:
OnNewIntent公司:
protected override void OnNewIntent(Intent intent)
{
base.OnNewIntent(intent);
NotificationClickedOn(intent);
}
现在您可以检查
intent.Action
/
intent.HasExtra
以确定发送的通知是否是您的,并对其进行处理。具有
Xamarin.Forms
最简单的方法是使用
MessagingCenter
发送在中订阅的邮件。NetStd/PCL
沙马林。表格
代码库。
通知单击打开:
void NotificationClickedOn(Intent intent)
{
if (intent.Action == "ASushiNotification" && intent.HasExtra("MessageFromSushiHangover"))
{
/// Do something now that you know the user clicked on the notification...
var notificationMessage = intent.Extras.GetString("MessageFromSushiHangover");
var winnerToast = Toast.MakeText(this, $"{notificationMessage}.\n\nð£ Please send 2 BitCoins to SushiHangover to process your winning ticket! ð£", ToastLength.Long);
winnerToast.SetGravity(Android.Views.GravityFlags.Center, 0, 0);
winnerToast.Show();
}
}
发送通知示例:
void SendNotifacation()
{
var title = "Winner, Winner, Chicken Dinner";
var message = "You just won a million StackOverflow reputation points";
var intent = new Intent(BaseContext, typeof(MainActivity));
intent.SetAction("ASushiNotification");
intent.PutExtra("MessageFromSushiHangover", message);
var pending = PendingIntent.GetActivity(BaseContext, 0, intent, PendingIntentFlags.CancelCurrent);
using (var notificationManager = NotificationManager.FromContext(BaseContext))
{
Notification notification;
if (Android.OS.Build.VERSION.SdkInt < Android.OS.BuildVersionCodes.O)
{
#pragma warning disable CS0618 // Type or member is obsolete
notification = new Notification.Builder(BaseContext)
.SetContentTitle(title)
.SetContentText(message)
.SetAutoCancel(true)
.SetSmallIcon(Resource.Drawable.icon)
.SetDefaults(NotificationDefaults.All)
.SetContentIntent(pending)
.Build();
#pragma warning restore CS0618 // Type or member is obsolete
}
else
{
var myUrgentChannel = BaseContext.PackageName;
const string channelName = "Messages from SushiHangover";
NotificationChannel channel;
channel = notificationManager.GetNotificationChannel(myUrgentChannel);
if (channel == null)
{
channel = new NotificationChannel(myUrgentChannel, channelName, NotificationImportance.High);
channel.EnableVibration(true);
channel.EnableLights(true);
channel.SetSound(
RingtoneManager.GetDefaultUri(RingtoneType.Notification),
new AudioAttributes.Builder().SetUsage(AudioUsageKind.Notification).Build()
);
channel.LockscreenVisibility = NotificationVisibility.Public;
notificationManager.CreateNotificationChannel(channel);
}
channel?.Dispose();
notification = new Notification.Builder(BaseContext)
.SetChannelId(myUrgentChannel)
.SetContentTitle(title)
.SetContentText(message)
.SetAutoCancel(true)
.SetSmallIcon(Resource.Drawable.icon)
.SetContentIntent(pending)
.Build();
}
notificationManager.Notify(1331, notification);
notification.Dispose();
}
}