You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET8 MAUI Blazor中Android前台服务关闭APP后停止运行的解决方案咨询

解决方案:.NET8 MAUI Blazor Android端通过Shiny.NET实现后台持续定位服务

可以实现关闭应用后前台服务持续运行,且通过通知重启应用的需求,Shiny.NET完全支持该场景,以下是具体配置和代码实现步骤:

一、完善Android权限与清单配置

除你已配置的android:foregroundServiceType="location",还需补充:

  • 在AndroidManifest.xml中添加必要权限:
    <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
    <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
    
  • 给Shiny的定位服务添加android:stopWithTask="false"属性,避免应用被关闭时服务终止:
    <service android:name="Shiny.Locations.LocationManagerService" 
             android:foregroundServiceType="location"
             android:stopWithTask="false" />
    

二、配置Shiny.NET的前台服务与通知

1. 创建通知渠道(适配Android 8+)

在Android项目的MainApplication.cs的OnCreate方法中添加渠道创建代码:

if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
{
    var channel = new NotificationChannel("location_tracking", "位置监控", NotificationImportance.Default)
    {
        Description = "持续监控设备位置"
    };
    var notificationManager = (NotificationManager)GetSystemService(NotificationService);
    notificationManager.CreateNotificationChannel(channel);
}

2. 配置Shiny定位服务的前台通知

在MAUI项目的MauiProgram.cs中,通过自定义Shiny启动类配置定位参数与通知:

builder.Services.AddShiny<MyShinyStartup>();

public class MyShinyStartup : ShinyStartup
{
    public override void ConfigureServices(IServiceCollection services)
    {
        services.AddGps(new GpsRequest
        {
            Interval = TimeSpan.FromSeconds(30), // 按需设置定位周期
            DesiredAccuracy = GpsAccuracy.Normal,
            UseBackgroundUpdates = true,
            // 配置前台服务通知
            ForegroundNotification = new ForegroundNotification
            {
                ChannelId = "location_tracking",
                Title = "位置监控中",
                Message = "应用正在后台持续获取位置",
                // 设置点击通知唤起主应用的Intent
                Intent = new Android.Content.Intent(Android.App.Application.Context, typeof(MainActivity))
                {
                    Flags = Android.Content.ActivityFlags.ClearTop | Android.Content.ActivityFlags.SingleTop
                }
            }
        });
    }
}

三、适配Android 14后台限制

Android 14对后台位置访问有严格限制,需注意:

  • 应用启动时需先请求ACCESS_FINE_LOCATION/ACCESS_COARSE_LOCATION权限,再请求ACCESS_BACKGROUND_LOCATION权限;
  • 部分厂商定制系统(如小米、华为)的省电模式会强制终止后台服务,需引导用户将应用加入电池优化白名单。

四、验证效果

启动应用并开启定位服务后关闭应用:

  • 下拉通知栏应能看到配置的位置监控通知;
  • 进入系统“正在运行的服务”,确认LocationManagerService处于运行状态;
  • 点击通知可直接唤起应用主界面。

常见问题排查

  • 服务仍被终止:检查是否开启电池优化,需将应用加入厂商白名单;
  • 通知不显示:确认已请求POST_NOTIFICATIONS权限,且通知渠道创建成功;
  • 通知无法唤起应用:检查Intent目标Activity是否正确,Flags需设置为ClearTop | SingleTop确保回到应用实例。

内容的提问来源于stack exchange,提问作者Михаил Глухов

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 13:17:47