简体   繁体   English

从最近的任务中删除应用程序时,Android 通知被取消

[英]Android notification gets cancelled when app is removed from recent tasks

I have an app which fires notification on button click.我有一个应用程序,它会在单击按钮时触发通知。 I have created two notification channels, in one i have set SetOngoing to TRUE while in another i have set it to false.我创建了两个通知渠道,一个我将 SetOngoing 设置为 TRUE,而另一个我将其设置为 false。 Everything works fine, but once i remove my app from recent tasks, notification of secondary channel remains however those of primary channel gets removed.一切正常,但是一旦我从最近的任务中删除我的应用程序,辅助频道的通知仍然存在,但主要频道的通知被删除。 I want my notification to remain there even if my app has been closed completely.即使我的应用程序已完全关闭,我也希望我的通知保留在那里。 Here is my sample code:这是我的示例代码:

//MainActivity.cs

using Android.App;
using Android.OS;
using Android.Content;
using Android.Provider;

namespace NotificationChannels
{
    [Activity(Label = "NotificationChannels", MainLauncher = true, Icon = "@mipmap/icon", Theme = "@style/Theme.AppTheme")]
    public class MainActivity : Activity
    {
        public static string TAG = typeof(MainActivity).Name;

        public const int NOTI_PRIMARY1 = 1100;
        public const int NOTI_PRIMARY2 = 1101;
        public const int NOTI_SECONDARY1 = 1200;
        public const int NOTI_SECONDARY2 = 1201;

        MainUI ui;

        NotificationHelper notificationHelper;

        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.Main);
            notificationHelper = new NotificationHelper(this);
            ui = new MainUI(FindViewById(Resource.Id.activity_main), this);
        }

        public void SendNotification(int id, string title)
        {
            Notification.Builder nb = null;
            switch (id)
            {
                case NOTI_PRIMARY1:
                    nb = notificationHelper.GetNotification1(title, GetString(Resource.String.primary1_body));
                    break;

                case NOTI_PRIMARY2:
                    nb = notificationHelper.GetNotification1(title, GetString(Resource.String.primary2_body));
                    break;

                case NOTI_SECONDARY1:
                    nb = notificationHelper.GetNotification2(title, GetString(Resource.String.secondary1_body));
                    break;

                case NOTI_SECONDARY2:
                    nb = notificationHelper.GetNotification2(title, GetString(Resource.String.secondary2_body));
                    break;
            }
            if (nb != null)
            {
                notificationHelper.Notify(id, nb);
            }
        }

        public void GoToNotificationSettings()
        {
            var i = new Intent(Settings.ActionAppNotificationSettings);
            i.PutExtra(Settings.ExtraAppPackage, PackageName);
            StartActivity(i);
        }

        public void GoToNotificationSettings(string channel)
        {
            var i = new Intent(Settings.ActionChannelNotificationSettings);
            i.PutExtra(Settings.ExtraAppPackage, PackageName);
            i.PutExtra(Settings.ExtraChannelId, channel);
            StartActivity(i);
        }

    }
}





//MainUI.cs

using Android.Widget;
using Android.Views;
using Android.Util;

namespace NotificationChannels
{
    public class MainUI : Java.Lang.Object, View.IOnClickListener
    {
        MainActivity self;

        public MainUI(View root, MainActivity self)
        {
            this.self = self;

            titlePrimary = (TextView)root.FindViewById(Resource.Id.main_primary_title);
            ((Button)root.FindViewById(Resource.Id.main_primary_send1)).SetOnClickListener(this);
            ((Button)root.FindViewById(Resource.Id.main_primary_send2)).SetOnClickListener(this);
            ((ImageButton)root.FindViewById(Resource.Id.main_primary_config)).SetOnClickListener(this);

            titleSecondary = (TextView)root.FindViewById(Resource.Id.main_secondary_title);
            ((Button)root.FindViewById(Resource.Id.main_secondary_send1)).SetOnClickListener(this);
            ((Button)root.FindViewById(Resource.Id.main_secondary_send2)).SetOnClickListener(this);
            ((ImageButton)root.FindViewById(Resource.Id.main_secondary_config)).SetOnClickListener(this);

            ((Button)root.FindViewById(Resource.Id.btnA)).SetOnClickListener(this);
        }

        TextView titlePrimary;
        string TitlePrimaryText
        {
            get
            {
                if (titlePrimary != null)
                {
                    return titlePrimary.Text;
                }
                return string.Empty;
            }
        }

        TextView titleSecondary;
        string TitleSecondaryText
        {
            get
            {
                if (titlePrimary != null)
                {
                    return titleSecondary.Text;
                }
                return "";
            }
        }

        public void OnClick(View view)
        {
            switch (view.Id)
            {
                case Resource.Id.main_primary_send1:
                    self.SendNotification(MainActivity.NOTI_PRIMARY1, TitlePrimaryText);
                    break;
                case Resource.Id.main_primary_send2:
                    self.SendNotification(MainActivity.NOTI_PRIMARY2, TitlePrimaryText);
                    break;
                case Resource.Id.main_primary_config:
                    self.GoToNotificationSettings(NotificationHelper.PRIMARY_CHANNEL);
                    break;

                case Resource.Id.main_secondary_send1:
                    self.SendNotification(MainActivity.NOTI_SECONDARY1, TitleSecondaryText);
                    break;
                case Resource.Id.main_secondary_send2:
                    self.SendNotification(MainActivity.NOTI_SECONDARY2, TitleSecondaryText);
                    break;
                case Resource.Id.main_secondary_config:
                    self.GoToNotificationSettings(NotificationHelper.SECONDARY_CHANNEL);
                    break;
                case Resource.Id.btnA:
                    self.GoToNotificationSettings();
                    break;
                default:
                    Log.Error(MainActivity.TAG, "Unknown click event.");
                    break;
            }
        }
    }
}





//NotificationHelper.cs


using System;
using Android.App;
using Android.Content;
using Android.Graphics;

namespace NotificationChannels
{
    public class NotificationHelper : ContextWrapper
    {
        public const string PRIMARY_CHANNEL = "default";
        public const string SECONDARY_CHANNEL = "second";

        NotificationManager manager;
        NotificationManager Manager
        {
            get
            {
                if (manager == null)
                {
                    manager = (NotificationManager)GetSystemService(NotificationService);
                }
                return manager;
            }
        }

        int SmallIcon => Android.Resource.Drawable.StatNotifyChat;

        public NotificationHelper(Context context) : base(context)
        {
            var chan1 = new NotificationChannel(PRIMARY_CHANNEL,
                    GetString(Resource.String.noti_channel_default), NotificationImportance.Default);
            chan1.LightColor = Color.Green;
            chan1.LockscreenVisibility = NotificationVisibility.Private;
            Manager.CreateNotificationChannel(chan1);

            var chan2 = new NotificationChannel(SECONDARY_CHANNEL,
                    GetString(Resource.String.noti_channel_second), NotificationImportance.High);
            chan2.LightColor = Color.Blue;
            chan2.LockscreenVisibility = NotificationVisibility.Public;
            Manager.CreateNotificationChannel(chan2);
        }

        public Notification.Builder GetNotification1(String title, String body)
        {
            return new Notification.Builder(ApplicationContext, PRIMARY_CHANNEL)
                     .SetContentTitle(title)
                     .SetContentText(body)
                     .SetSmallIcon(SmallIcon)
                     .SetAutoCancel(false)
                     .SetOngoing(true);
        }

        public Notification.Builder GetNotification2(String title, String body)
        {
            return new Notification.Builder(ApplicationContext, SECONDARY_CHANNEL)
                     .SetContentTitle(title)
                     .SetContentText(body)
                     .SetSmallIcon(SmallIcon)
                     .SetAutoCancel(false);
        }

        public void Notify(int id, Notification.Builder notification)
        {
            Manager.Notify(id, notification.Build());
        }

    }
}

That would be the expected behavior.那将是预期的行为。 An ongoing notification serves the purpose of letting the user know the application is currently performing some important task.持续通知的目的是让用户知道应用程序当前正在执行某些重要任务。

An ongoing notification cannot be dismissed by the user and needs to be handled by the application.正在进行的通知不能被用户关闭,需要由应用程序处理。 If the application is closed then the ongoing notification would also be dismissed.如果申请被关闭,那么正在进行的通知也将被驳回。

So if you need the notification to remain:因此,如果您需要保留通知:

  1. Start a foreground service - Then similar to a music application the notification will not be dismissed even if the application is swiped away from the recents screen启动前台服务- 然后类似于音乐应用程序,即使应用程序从最近屏幕上滑动,通知也不会被关闭
  2. When the application is closing you could send another notification which is not an ongoing notification.当应用程序关闭时,您可以发送另一个通知,这不是正在进行的通知。 You would have to do this in the OnDestroy() method of either an Activity or the Application object您必须在 Activity 或 Application 对象的OnDestroy()方法中执行此操作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Xamarin.Android HttpClient PostAsync在发布时被取消 - Xamarin.Android HttpClient PostAsync gets cancelled when in Release 尝试创建appx时,已从package.appxmanifest中删除了远程应用程序服务声明 - Remote app service declaration gets removed from package.appxmanifest when trying to create appx 当一些任务可能被取消时等待多个任务 - Waiting for multiple tasks when some might be cancelled 当数组中的一个或多个任务被取消或失败时继续吗? - Continuation when one or more tasks in an array is cancelled or fails? 如何从 Task.WhenAll 执行返回未取消的任务 - How to return the not-cancelled tasks from Task.WhenAll execution C#任务未取消 - C# tasks are not cancelled 使用Xamarin Crossplatform在应用程序不在设备的最新历史记录中时如何显示本地通知 - How to display local notification when the app is not in the recent history of the device using Xamarin Crossplatform 从最近删除应用程序时,使MessageCenter保持活动状态 - keep MessageCenter alive when app remove from recent 运行 BroadcastReceiver 即使应用程序从最近的列表中刷出 - Run BroadcastReceiver even when app is swiped out from recent list 如何在UWP应用中检测何时将项目添加到ListView或从ListView中删除? - How to detect when a item is added to or removed from a ListView in UWP app?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM