检查是否单击了通知

时间:2017-12-11 14:57:07

标签: c# xamarin notifications xamarin.android

我有一个带警报的应用程序,每次警报触发,应用程序向用户发送通知,是否可以知道用户是否点击或关闭了通知?

我的通知代码如下:

public override void OnReceive(Context context, Intent intent)
{
    try
    {
       Settings.AlarmNotification = 1;

            if (System.DateTime.Now.DayOfWeek == DayOfWeek.Thursday)
            {
                Settings.AlarmCount =0;
            }

            var title = "Test";
            var message = "Something";

            Intent backIntent = new Intent(context, typeof(MainActivity));
            backIntent.SetFlags(ActivityFlags.NewTask);



            var resultIntent = new Intent(context, typeof(MainActivity));



            PendingIntent pending = PendingIntent.GetActivities(context, 0,
                new Intent[] { backIntent, resultIntent },
                PendingIntentFlags.OneShot);

            var builder =
                new Notification.Builder(context)
                    .SetContentTitle(title)
                    .SetContentText(message)
                    .SetAutoCancel(true)
                    .SetSmallIcon(Resource.Drawable.icon)
                    .SetDefaults(NotificationDefaults.All);

            builder.SetContentIntent(pending);
            var notification = builder.Build();
            var manager = NotificationManager.FromContext(context);
            manager.Notify(1331, notification);

    }
    catch (Exception)
    {

    }
}

2 个答案:

答案 0 :(得分:2)

Notification.BuilderNotificationCompat.Builder都有一个SetDeleteIntent方法,您可以使用该方法在通知关闭时触发BroadcastReceiver(即使使用" CLEAR ALL&#34 )。由于您已将通知设置为自动取消,因此在点击通知时也会触发此BroadcastReceiver

首先,设置PendingIntent以发送到BroadcastReceiver

var deleteIntent = new Intent(context, typeof(NotificationBroadcastReceiver));
deleteIntent.SetAction("Action");
deleteIntent.PutExtra("key", key);
// TODO: Set extras as needed.
var deletePendingIntent = PendingIntent.GetBroadcast(context, _notificationId, deleteIntent, PendingIntentFlags.CancelCurrent);

然后将PendingIntent与通知相关联:

var builder = new NotificationCompat.Builder(context, RouteUpdateChannelId)
            .SetDefaults(NotificationCompat.DefaultAll)
            .SetAutoCancel(true)
            // TODO: Setup Notification
            .SetDeleteIntent(deletePendingIntent);

现在您可以将BroadcastReceiver添加到Android项目中:

[BroadcastReceiver]
public class NotificationBroadcastReceiver : BroadcastReceiver
{
    public override void OnReceive(Context context, Intent intent)
    {
        if (intent.Action == "Action")
        {
            // TODO: Grab extras from the Intent as needed.
            var key = intent.GetStringExtra("key");
            // TODO: Handle notification closing here...
        }
    }
 }

答案 1 :(得分:2)

如果你想"触发"当用户点击您的通知时,您MainActivity可以设置通知PendingIntent Intent,其中包含您要传递给它的任何其他信息。

var title = "Winner, Winner, Chicken Dinner";
var message = "You just won a million StackOverflow reputation points";

var alarmIntent = new Intent(context, typeof(MainActivity));
alarmIntent.SetAction("ASushiNotification");
alarmIntent.PutExtra("MessageFromSushiHangover", message);
var pending = PendingIntent.GetActivity(context, 0, alarmIntent, PendingIntentFlags.CancelCurrent);

// set your notification as normal using ".SetContentIntent(pending)"

MainActivty上,将其LaunchMode设置为SingleTop,以便操作系统重新使用该活动,如果它已经在运行而不是开始新活动:

[Activity(Label = "A Super Duper App", MainLauncher = true, Icon = "@mipmap/icon", LaunchMode = Android.Content.PM.LaunchMode.SingleTop)]

通知意图的MainActvity有两个入口点,如果活动已在运行,则会调用OnNewIntent,意图是您在通知上设置。如果您的应用未投放,则MainActvity将正常创建,但将包含来自通知的意图。

创建一个方法(NotificationClickedOn),该方法可以对意图以及您应用的任何额外数据执行某些操作:

void NotificationClickedOn(Intent intent)
{
    if (intent.Action == "ASushiNotification" && intent.HasExtra("MessageFromSushiHangover"))
    {
        /// Do something now that you know the user clicked on the notifcation...
        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();
    }
}

MainActivty中,覆盖OnNewIntent方法并致电NotificationClickedOn

protected override void OnNewIntent(Intent intent)
{
    base.OnNewIntent(intent);
    NotificationClickedOn(intent);
}

在现有的OnCreate覆盖中添加一个电话NotificationClickedOn

protected override void OnCreate(Bundle savedInstanceState)
{
    base.OnCreate(savedInstanceState);
    SetContentView(Resource.Layout.Main);

    ~~~~~

    NotificationClickedOn(Intent);

    ~~~~~
 }

现在,当有人点击您的通知时,您就可以确定您的应用是否已在运行:

enter image description here

您的申请&如果需要,将创建活动,并显示MainActivity并显示祝酒词:

enter image description here