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

.NET MAUI流媒体音频App后台定时关闭播放器实现方案咨询

.NET MAUI 流媒体音频定时关闭实现方案

一、适配的NuGet包方案

可以使用CommunityToolkit.Maui,这是微软官方维护的MAUI工具集,内置跨平台的DispatcherTimer,能快速实现定时任务。

实现步骤:

  1. 安装NuGet包:CommunityToolkit.Maui
  2. 在MauiProgram.cs中注册工具集:
builder.UseMauiApp<App>().UseMauiCommunityToolkit();
  1. 在ViewModel或页面中编写定时逻辑:
private IDispatcherTimer _shutdownTimer;
// 定义15分钟至2小时的可选定时时长
public List<TimeSpan> ShutdownTimeOptions { get; } = new()
{
    TimeSpan.FromMinutes(15),
    TimeSpan.FromMinutes(30),
    TimeSpan.FromMinutes(60),
    TimeSpan.FromMinutes(90),
    TimeSpan.FromMinutes(120)
};

public TimeSpan SelectedShutdownTime { get; set; }

// 启动定时命令
public ICommand StartTimerCommand => new Command(() =>
{
    _shutdownTimer?.Stop();
    _shutdownTimer = Dispatcher.CreateTimer();
    _shutdownTimer.Interval = SelectedShutdownTime;
    _shutdownTimer.Tick += (_, _) =>
    {
        _shutdownTimer.Stop();
        // 执行关闭播放器的逻辑
        YourAudioPlayerInstance.Stop();
    };
    _shutdownTimer.Start();
});

// 取消定时命令
public ICommand CancelTimerCommand => new Command(() => _shutdownTimer?.Stop());

二、手动实现方案(无需额外NuGet包)

直接使用.NET MAUI内置的DispatcherTimer,适合轻量场景,无需依赖第三方包。

核心代码示例:

private DispatcherTimer _timer;

// 初始化定时组件
public void InitTimer()
{
    _timer = new DispatcherTimer();
}

// 启动定时(传入用户选择的时长)
public void StartShutdownTimer(TimeSpan duration)
{
    _timer.Stop();
    _timer.Interval = duration;
    _timer.Tick += TimerTickHandler;
    _timer.Start();
}

// 定时触发的回调
private void TimerTickHandler(object sender, EventArgs e)
{
    _timer.Stop();
    _timer.Tick -= TimerTickHandler;
    // 停止音频播放
    YourAudioPlayer.Stop();
}

// 取消定时
public void CancelShutdownTimer()
{
    _timer?.Stop();
    _timer?.Tick -= TimerTickHandler;
}

额外注意点

  • 若APP退到后台,DispatcherTimer可能会暂停执行。如果需要后台仍保持定时生效:
    • Android:结合WorkManager实现后台定时任务
    • iOS:使用BackgroundTasks框架注册后台任务(需注意苹果的后台权限限制)

内容的提问来源于stack exchange,提问作者copang

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 10:55:14