posts - 609,  comments - 13,  views - 64万
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
参考:https://blog.csdn.net/qq_40912347/article/details/129801231
退出app:Android.OS.Process.KillProcess(Android.OS.Process.MyPid());
INavigateService
复制代码
using Microsoft.AspNetCore.Components;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace schmpos.Data
{
    public interface INavigateService
    {
        /// <summary>
        /// 存储想要返回时触发的方法
        /// </summary>
        event Action Action;
        NavigationManager Navigation { get; protected set; }
        /// <summary>
        /// 存储URL历史记录
        /// </summary>
        List<string> HistoryUrl { get; protected set; }
        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="navigation"></param>
        void Initialize(NavigationManager navigation);
        /// <summary>
        /// 导航
        /// </summary>
        /// <param name="url"></param>
        void NavigateTo(string url);
        /// <summary>
        /// 返回上一页
        /// </summary>
        void NavigateToBack();
        /// <summary>
        /// 返回键处理
        /// </summary>
        /// <returns>true已处理事件,false为无事件可处理(便于做进一步处理,例如退出应用)</returns>
        bool OnBackButtonPressed();
    }
}
复制代码

NavigateService

复制代码
using Microsoft.AspNetCore.Components;
using schmpos.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace schmpos.Data
{
    public class NavigateService : INavigateService
    {
        public NavigationManager Navigation { get; set; } = default!;

        public event Action? Action;

        public void Initialize(NavigationManager navigation)
        {
            Navigation = navigation;
        }

        public List<string> HistoryUrl { get; set; } = new List<string>();

        public void NavigateTo(string url)
        {
            var href = Navigation.ToBaseRelativePath(Navigation.Uri);
            HistoryUrl.Add(href);
            Navigation.NavigateTo(url);
        }
        public void NavigateToBack()
        {
            string href = string.Empty;
            if (HistoryUrl.Count > 0)
            {
                href = HistoryUrl.Last();
            }
            Navigation.NavigateTo(href);
            if (HistoryUrl.Count > 0)
            {
                HistoryUrl.RemoveAt(HistoryUrl.Count - 1);
            }
        }

        public bool OnBackButtonPressed()
        {
            if (Action != null && Action?.GetInvocationList().Length > 0)
            {
                var delegates = Action!.GetInvocationList();
                (delegates.Last() as Action)!.Invoke();
                return true;
            }

            if (HistoryUrl.Count > 0)
            {
                NavigateToBack();
                return true;
            }
        }
    }
}
复制代码

添加安卓返回键处理类,放在Platforms/Android下

复制代码
using Android.OS;
using Android.Views;
using Android.Widget;
using SwashbucklerDiary.IServices;
using Application = Android.App.Application;

namespace XXX.Platforms.Android
{
    public static class BackButtonPressed
    {
        private static byte BackPressCounter;

        public static bool OnBackButtonPressed(KeyEvent e)
        {
            if (e.KeyCode == Keycode.Back)
            {
                if (e.Action == KeyEventActions.Down)
                {
                    var service = MauiApplication.Current.Services.GetRequiredService<INavigateService>();
                    bool flag = service!.OnBackButtonPressed();
                    if (!flag)
                    {
                        QuitApp();
                    }
                }
                return true;
            }
            return false;
        }

        public static void QuitApp()
        {
            if (BackPressCounter == 1)
            {
                Process.KillProcess(Process.MyPid());
            }
            else if (BackPressCounter == 0)
            {
                BackPressCounter++;
                Toast.MakeText(Application.Context, "再按一次退出", ToastLength.Long)!.Show();
                Task.Run(async () =>
                {
                    await Task.Delay(2000);
                    BackPressCounter = 0;
                });
            }
        }
    }
}
复制代码

修改Platforms/Android/MainActivity.cs,添加以下代码

复制代码
public override bool DispatchKeyEvent(KeyEvent e)
{
    var flag = BackButtonPressed.OnBackButtonPressed(e);
    if (flag)
    {
        return true;
    }

    return base.DispatchKeyEvent(e);
}
复制代码

Shared下添加MainLayout.razor.cs

复制代码
public partial class MainLayout 
{
    [Inject]
    NavigationManager Navigation { get; set; } = default!;
    [Inject]
    INavigateService NavigateService { get; set; } = default!;

    protected override void OnInitialized()
    {
        NavigateService.Initialize(Navigation);
        base.OnInitialized();
    }
}
复制代码

修改MauiProgram.cs,添加以下代码 builder.Services.AddSingleton<INavigateService, NavigateService>();
使用,注入INavigateService,
[Inject]
protected INavigateService NavigateService { get; set; } = default!;
如果想要将跳转后的上一页保存到返回服务中,跳转页面时使用NavigateService.NavigateTo(url),当你主动调用NavigateService.NavigateToBack()或者按下安卓返回键时,会跳转回之前保存的上一页。如果想要让返回键执行什么方法,就加入到委托中NavigateService.Action += 你的方法;别忘了在执行后和组件Dispose中把你的方法移出委托NavigateService.Action -= 你的方法;

posted on   邢帅杰  阅读(410)  评论(2编辑  收藏  举报
相关博文:
阅读排行:
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探
历史上的今天:
2022-06-14 Mysql查询优化
2016-06-14 MVC过滤器实现用户登录验证
2016-06-14 MVC过滤器
点击右上角即可分享
微信分享提示