背景

MAUI的呈现,赋予了宽广Net开发者开发多平台利用的能力,MAUI 是Xamarin.Forms演变而来,然而相比Xamarin性能更好,可扩展性更强,构造更简略。然而MAUI对于平台相干的实现并不残缺。所以MASA团队发展了一个实验性我的项目,意在对微软MAUI的补充和扩大,我的项目地址https://github.com/BlazorComp...,每个性能都有独自的demo演示我的项目,思考到app安装文件体积(尽管MAUI曾经集成裁剪性能,然而该性能对于代码自身有影响),届时每一个性能都会以独自的nuget包的模式提供,不便测试,当初我的项目才刚刚开始,然而置信很快就会有能够交付的内容啦。

前言

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

介绍

上一篇文章咱们集成了个推的音讯告诉,那么音讯达到挪动端之后,除了会在告诉栏显示之外,在利用的角标也会显示未读音讯的数量(小红点),而后用户点击查看音讯之后,这些数字角标也能够主动打消,这个性能在MAUI中如何实现呢。

一、iOS局部

思路

https://developer.apple.com/d...

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

var applicationIconBadgeNumber: Int { get set }

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

https://developer.apple.com/d...

咱们能够通过shared获取以后UIApplication的实例,而后就能够给applicationIconBadgeNumber赋值了,然而如果你间接这样做,你会发现并没有成果,因为 iOS 8 当前,须要注册用户告诉,以取得用户的受权。

https://developer.apple.com/d...

咱们能够通过UNUserNotificationCenterRequestAuthorization办法获取申请用户本地和近程的告诉权限。

开发步骤

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

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办法。

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/maven...

开发步骤

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平台的判断。

    <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.goo...
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办法

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办法

        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文件,增加必要的权限。

<?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文件

理论的应用场景应该是挪动端接管音讯推送,在解决音讯推送的办法内批改角标,咱们这里为了简化,在页面间接通过按钮触发批改角标显示的数量。
@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