MASA MAUI Plugin (七)应用通知角标(小红点)Android+iOS

MASA MAUI Plugin (七)应用通知角标(小红点)Android+iOS

背景

MAUI的出现,赋予了广大Net开发者开发多平台应用的能力,MAUI 是Xamarin.Forms演变而来,但是相比Xamarin性能更好,可扩展性更强,结构更简单。但是MAUI对于平台相关的实现并不完整。所以MASA团队开展了一个实验性项目,意在对微软MAUI的补充和扩展

项目地址https://github.com/BlazorComponent/MASA.Blazor/tree/feature/Maui/src/Masa.Blazor.Maui.Plugin

每个功能都有单独的demo演示项目,考虑到app安装文件体积(虽然MAUI已经集成裁剪功能,但是该功能对于代码本身有影响),届时每一个功能都会以单独的nuget包的形式提供,方便测试,现在项目才刚刚开始,但是相信很快就会有可以交付的内容啦。

前言

本系列文章面向移动开发小白,从零开始进行平台相关功能开发,演示如何参考平台的官方文档使用MAUI技术来开发相应功能。

介绍

上一篇文章我们集成了个推的消息通知,那么消息到达移动端之后,除了会在通知栏显示之外,在应用的角标也会显示未读消息的数量(小红点),然后用户点击查看消息之后,这些数字角标也可以自动消除,这个功能在MAUI中如何实现呢。

一、iOS部分

思路

https://developer.apple.com/documentation/uikit/uiapplication/1622918-applicationiconbadgenumber

我们参考一下官方文档,UIApplication下有一个applicationIconBadgeNumber的属性

1
var applicationIconBadgeNumber: Int { get set }

我们只需要给这个属性赋值具体的整数即可,

https://developer.apple.com/documentation/uikit/uiapplication/1622975-shared

我们可以通过shared获取当前UIApplication的实例,然后就可以给applicationIconBadgeNumber赋值了,但是如果你直接这样做,你会发现并没有效果,因为 iOS 8 以后,需要注册用户通知,以获得用户的授权。

https://developer.apple.com/documentation/usernotifications/unusernotificationcenter/1649527-requestauthorization

我们可以通过UNUserNotificationCenterRequestAuthorization方法获取请求用户本地和远程的通知权限。

在这里插入图片描述

开发步骤

我们新建一个目录Badger,并在下面新建MAUI类库项目Masa.Blazor.Maui.Plugin.Badger
Platforms下的iOS文件夹新建MasaMauiBadgerService部分类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
using UIKit;
using UserNotifications;
namespace Masa.Blazor.Maui.Plugin.Badger
{
public static partial class MasaMauiBadgerService
{
private static void PlatformSetNotificationCount(int count)
{
// Requests the user’s authorization to allow local and remote notifications for your app.
UNUserNotificationCenter.Current.RequestAuthorization(UNAuthorizationOptions.Badge, (r, e) =>{});

// The number currently set as the badge of the app icon on the Home screen
// Set to 0 (zero) to hide the badge number. The default value of this property is 0.
UIApplication.SharedApplication.ApplicationIconBadgeNumber = count;
}
}
}

RequestAuthorization方法有两个参数

1、UNAuthorizationOptions 代表应用请求的授权选项,这里我们使用Badge
2、completionHandle 这是一个Action,有两个参数,第一个参数是一个bool值,代表是否已授予授权,第二个参数是一个NSError类型,表示包含错误信息或未发生错误的对象。我们这里暂不处理出错的情况

我们通过UIApplication.SharedApplication获取当前的UIApplication实例,然后直接给
ApplicationIconBadgeNumber 赋值,这里如果我们想清除角标,就直接赋值0即可。
我们继续在项目根目录新建MasaMauiBadgerService类,通过SetNotificationCount来调用不同平台的PlatformSetNotificationCount方法。

1
2
3
4
5
6
7
8
9
10
11
namespace Masa.Blazor.Maui.Plugin.Badger
{
// All the code in this file is included in all platforms.
public static partial class MasaMauiBadgerService
{
public static void SetNotificationCount(int count)
{
PlatformSetNotificationCount(count);
}
}
}

二、安卓部分

思路

安卓部分比iOS相对复杂,我们本着不造轮子的思想,找了一个现成的aar包,ShortcutBadger

项目maven地址:https://repo1.maven.org/maven2/me/leolin/ShortcutBadger

开发步骤

1、我们下载最新的ShortcutBadger-1.1.22.aar包,并新建Android Java 库绑定项目Masa.Blazor.Maui.Plugin.BadgerBinding
在这里插入图片描述

在根目录创建Jars文件夹,并将下载的aar文件添加进去。添加进去的文件属性中,生成操作默认选择的是AndroidLibrary,如果不对请手动更正。
右键生成这个项目,这里很顺利没有任何报错。

2、我们在Masa.Blazor.Maui.Plugin.Badger项目中引用Masa.Blazor.Maui.Plugin.BadgerBinding项目,由于我们只有在安卓平台需要项目引用,所以我们手动修改一下项目文件中的引用部分,添加Android平台的判断。

1
2
3
<ItemGroup Condition="'$(TargetFramework)' == 'net7.0-android'">
<ProjectReference Include="..\Masa.Blazor.Maui.Plugin.BadgerBinding\Masa.Blazor.Maui.Plugin.BadgerBinding.csproj" />
</ItemGroup>

3、从 Android 8.0(API 级别 26)开始,所有通知都必须分配到相应的渠道,关于通知通道的信息,可以参考以下官方文档

https://developer.android.google.cn/training/notify-user/channels?hl=zh-cn

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Java 代码
private void createNotificationChannel() {
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = getString(R.string.channel_name);
String description = getString(R.string.channel_description);
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
channel.setDescription(description);
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}

我们参照以上写法,在Masa.Blazor.Maui.Plugin.Badger项目的Android平台目录下新建MasaMauiBadgerService 类,添加一个CreateNotificationChannel方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
using Android.App;
using AndroidX.Core.App;

namespace Masa.Blazor.Maui.Plugin.Badger
{
// All the code in this file is included in all platforms.
public static partial class MasaMauiBadgerService
{
private static void CreateNotificationChannel()
{
if (OperatingSystem.IsAndroidVersionAtLeast(26))
{
using var channel = new NotificationChannel($"{Android.App.Application.Context.PackageName}.channel", "Notification channel", NotificationImportance.Default)
{
Description = "Masa notification channel"
};
var notificationManager = NotificationManager.FromContext(Android.App.Application.Context);
notificationManager?.CreateNotificationChannel(channel);
}
}
}
}

1、通过OperatingSystem.IsAndroidVersionAtLeast来判断当前的Android版本。
2、NotificationChannel的创建方式与Java一致,三个参数分别为ChannelIDnameImportance
这里注意第三个参数代表重要性级别,我们这里使用了NotificationImportance.Default

用户可见的重要性级别 重要性(Android 8.0 及更高版本)
紧急:发出提示音,并以浮动通知的形式显示 IMPORTANCE_HIG
高:发出提示音 IMPORTANCE_DEFAULT
中:无提示音 IMPORTANCE_LOW
低:无提示音,且不会在状态栏中显示 IMPORTANCE_MIN

3、Description 指定用户在系统设置中看到的说明。
4、通过NotificationManager.FromContext 创建 notificationManager,然后调用CreateNotificationChannel来创建通知通道。

我们继续添加SetNotificationCount方法

1
2
3
4
5
6
7
8
9
10
11
12
13
private static void PlatformSetNotificationCount(int count)
{
ME.Leolin.Shortcutbadger.ShortcutBadger.ApplyCount(Android.App.Application.Context, count);
NotificationCompat.Builder builder = new(Android.App.Application.Context, $"{Android.App.Application.Context.PackageName}.channel");
builder.SetNumber(count);
builder.SetContentTitle(" ");
builder.SetContentText("");
builder.SetSmallIcon(Android.Resource.Drawable.SymDefAppIcon);
var notification = builder.Build();
var notificationManager = NotificationManager.FromContext(Android.App.Application.Context);
CreateNotificationChannel();
notificationManager?.Notify((int)DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), notification);
}

1、调用ShortcutBadgerApplyCount方法来添加角标
2、创建NotificationCompat.Builder示例,并以此设置角标显示数量(SetNumber),通知的标题(SetContentTitle)和内容(SetContentText),以及通知图标(SetSmallIcon)。
3、调用我们刚写好的方法创建通知通道。
4、通过NotificationManager.Notify方法在状态栏发布一条通知。
该方法有两个参数,第一个参数是一个int类型id,这个id是通知的标识符,在应用程序中应该唯一。这里需要注意:如果你发布了相同id的通知,并且前一个并没有取消,那么该id对应的通知会被更新。第二个参数是一个notification 对象,是通过NotificationCompat.Builder创建出来的。

三、创建Demo项目

1、新建一个MAUI Blazor项目:BadgerSample,添加对Masa.Blazor.Maui.Plugin.Badger项目的引用
2、添加Android权限:修改Android平台目录中的AndroidManifest.xml文件,添加必要的权限。

1
2
3
4
5
6
7
8
9
10
11
12
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application android:allowBackup="true" android:icon="@mipmap/appicon" android:roundIcon="@mipmap/appicon_round" android:supportsRtl="true"></application>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
<uses-permission android:name="android.permission.READ_APP_BADGE" />
<uses-permission android:name="com.android.launcher.permission.READ_SETTINGS"/>
<uses-permission android:name="com.android.launcher.permission.WRITE_SETTINGS"/>
<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />
<uses-permission android:name="com.android.launcher.permission.UNINSTALL_SHORTCUT" />
</manifest>

注意:国内不同手机厂家可能需要额外的权限配置,需要参考具体厂家的配置说明。

3、修改Index.razor文件

实际的使用场景应该是移动端接收消息推送,在处理消息推送的方法内修改角标,我们这里为了简化,在页面直接通过按钮触发修改角标显示的数量。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@page "/"
@using Masa.Blazor.Maui.Plugin.Badger;

<h1>Masa blazor badger sample</h1>

Masa blazor badger sample.

<button @onclick="OnIncrementClicked">Add</button>
<button @onclick="OnClearClicked">Clear</button>
@code{
int count;
private void OnIncrementClicked()
{
count++;

MasaMauiBadgerService.SetNotificationCount(count);
}
private void OnClearClicked()
{
count = 0;
MasaMauiBadgerService.SetNotificationCount(count);
}
}

Android 演示:演示机:vivo x70 pro+

在这里插入图片描述
iOS 演示:演示机:iPhone 14 iOS16 模拟器

在这里插入图片描述


如果你对我们的 MASA Framework 感兴趣,无论是代码贡献、使用、提 Issue,欢迎联系我们

WeChat:MasaStackTechOps

QQ:7424099

作者

MASA

发布于

2022-12-28

更新于

2023-05-26

许可协议