.net开发安卓入门 - Notification(通知)

通知的布局

在这里插入图片描述

创建通知通道

在 Android 8.0 上运行的应用必须为其通知创建通知通道。 通知通道需要以下三条信息:

  • 标识通道的包唯一的 ID 字符串。
  • 将显示给用户的通道的名称。 名称必须介于 1 到 40 个字符之间。
  • 通道的重要性。
    应用需要检查其正在运行的 Android 版本。 运行版本低于 Android 8.0 的设备不应创建通知通道。 以下方法是如何在活动中创建通知通道的一个示例:
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);
}

创建和发布通知

若要在 Android 中生成通知,请执行以下步骤:

  1. 实例化 NotificationCompat.Builder 对象。
  2. 对对象调用各种方法 NotificationCompat.Builder 以设置通知选项。
  3. 调用对象的 Build 方法 NotificationCompat.Builder 以实例化通知对象。
  4. List item

调用通知管理器的 Notify 方法发布通知。

必须至少为每个通知提供以下信息:

  1. 大小 (为 24x24 dp 的小型图标)
  2. 简短标题
  3. 通知的文本

下面的代码示例演示如何用于 NotificationCompat.Builder 生成基本通知。 请注意, NotificationCompat.Builder 方法支持 方法链接;也就是说,每个方法返回生成器对象,以便可以使用最后一个方法调用的结果调用下一个方法调用:

// 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);

我的样例

效果图

在这里插入图片描述

代码

using Android.App;
using Android.Content;
using Android.Graphics;
using Android.Media;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using AndroidX.AppCompat.App;
using AndroidX.Core.App;
//using Android.Support.V4.App;
//using TaskStackBuilder = Android.Support.V4.App.TaskStackBuilder;
//using Android.Media;

namespace 我的第一个安卓程序
{
    [Activity(Label = "@string/app_name", Theme = "@style/AppTheme", MainLauncher = true)]
    public class MainActivity : AppCompatActivity
    {
        static readonly int NOTIFICATION_ID = 1000;
        static readonly string CHANNEL_ID = "notice"; 
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.activity_main);

            #region 创建通知通道


            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.High)
            {
                Description = description,
                
            };

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


            #endregion


            #region *****************在这里添加了用户控件处理代码start*****************
            //找到两个edittext
            var txtInput = FindViewById<EditText>(Resource.Id.txtInput);
            var txtNumInput = FindViewById<EditText>(Resource.Id.txtNumInput);
            //找到btn按钮
            var button = FindViewById<Button>(Resource.Id.btnTest);
            button.Click += (es, ee) =>
            {
                //吐司内容
                Toast.MakeText(this, $"txtInput的内容是:{txtInput.Text},txtNumInput数字是:{txtNumInput.Text}", ToastLength.Long).Show();
            };
            #endregion *****************在这里添加了用户控件处理代码end*****************
        }
        public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
        {
            Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);

            base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
        }

        [Java.Interop.Export]
        public void ShowMessage(View viwe)
        {
            Toast.MakeText(this, $" 这是通过ShowMessage进来的", ToastLength.Long).Show();
        }


        [Java.Interop.Export]
        public void ShowSecondActivity(View viwe)
        {
            StartActivity(typeof(SecondActivity));
        }

        [Java.Interop.Export]
        public void ShowIntetActivity(View viwe)
        {
            Intent intent = new Intent();
            intent.SetClass(this, typeof(SecondActivity));
            StartActivity(intent);
        }


        int count = 0;
        [Java.Interop.Export]
        public void ShowSystemNotice(View view)
        {
            // Instantiate the Image (Big Picture) style:
            NotificationCompat.BigPictureStyle  picStyle = new NotificationCompat.BigPictureStyle(); 
          // Convert the image to a bitmap before passing it into the style:
          picStyle.BigPicture(BitmapFactory.DecodeResource(Resources, Resource.Drawable.notice));

            // Set the summary text that will appear with the image:
            picStyle.SetSummaryText("就是超级大的图标能咋滴?");


            // "notice" 是通知通道,这个可以自己定义
            NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
                .SetContentTitle("这是一个通知")
                .SetContentText("我现在通知你啦, Hello World!")
                .SetDefaults((int)NotificationDefaults.All)
                .SetSound(RingtoneManager.GetDefaultUri(RingtoneType.Ringtone)) 
                .SetSmallIcon(Resource.Mipmap.notice_small)
                .SetLargeIcon(BitmapFactory.DecodeResource(Resources, Resource.Drawable.notice_normal))
                .SetStyle(picStyle);

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

            // Get the notification manager:
            var notificationManager = NotificationManagerCompat.From(this); 
           
            notificationManager.Notify(NOTIFICATION_ID, notification);
        }
    }
}

资源文件

在这里插入图片描述

常见问题

一切代码都准备就绪了,为什么就是不提示消息内容呢?

消息的权限是在APP中进行设置的,所以需要手动在模拟器中开启消息的权限,当然也可以通过资源配合代码获取开启通知的权限,我简单处理就是手动开启权限,开启方式:
设置–>应用–>找到自己的应用点击–>通知–打开就可以了如下图
在这里插入图片描述

为什么我的通知不是弹出式的

一样在系统中进行设置,设置方式自行摸索吧

同系列文章推荐

.net开发安卓入门 - 环境安装
.net开发安卓入门 - Hello world!
.net开发安卓入门 - 基本交互(Button,输入EditText,TextView,Toast)
.net开发安卓入门 - 布局与样式
.net开发安卓入门 - Activity
.net开发安卓入门 - Notification(通知)
.net开发安卓入门 - 四大基本组件
.net开发安卓入门 - Service (服务)
.net开发安卓入门 - 打包(.apk)
.net开发安卓入门 - ImageView 显示网络图片
.net开发安卓入门-文件操作与配置操作
.net开发安卓入门-Dialog
.net开发安卓入门-自动升级(配合.net6 webapi 作为服务端)
vs2022 实现无线调试安卓(Windows)
.net开发安卓从入门到放弃
.net开发安卓从入门到放弃 最后的挣扎(排查程序闪退问题记录-到目前为止仍在继续)
.net开发安卓入门 -记录两个问题处理办法

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值