首页 > 解决方案 > Xamarin Android 我需要在应用程序关闭时终止前台服务和通知

问题描述

让我解释一下这个场景。
我有一个任务需要每 10 分钟安排一次。
此任务需要网络和磁盘资源,即使应用程序在后台并且即使省电模式已启动。
我尝试了 AlarmManager、JobScheduler 和 ForegroundService。
然后只有一个在省电模式启动时似乎起作用的是 ForegroundService。

在 xamarin 中,我在 MainActivity.cs 中启动了一个前台服务,如下所示。

void StartSomeService()
{
    var intent = new Intent(this, typeof(SomeService));
    StartForegroundService(intent);
}

在我的“前台”服务中,我有一个在 android 中显示的通知。
当用户将应用程序从屏幕上滑出或点击“X”关闭应用程序时,我需要终止前台服务。

这部分确实会终止/关闭通知,但感觉不对,因为我再次调用 StartService 只是为了终止服务。

测试服务

public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
{
    if ("stop_service" == intent.Action)
    {
        StopForeground(true);
        StopSelf();
    }
    else
    {
        _cts = new CancellationTokenSource();

        RegisterForegroundService();

        Task.Factory.StartNew(async () =>
        {
            while (true)
            {                        
                await Task.Delay(TimeSpan.FromSeconds(30));

                // DO SOME WORK
            }
        });
    }

    return StartCommandResult.Sticky;
}

主要活动

protected override void OnDestroy()
{
    var intent = new Intent(this, typeof(TestService));
    intent.SetAction("stop_service");
    StartService(intent);

    base.OnDestroy();
}

标签: androidxamarinxamarin.android

解决方案


要停止我通常使用的前台服务:

var intent = new Intent(this, typeof(ForegroundService));
StopService(intent);

这将反过来OnDestroy()在前台服务内部触发。

然后我OnDestroy()做:

if (Build.VERSION.SdkInt >= BuildVersionCodes.N)
{
    StopForeground(StopForegroundFlags.Remove);
}
else
{
    StopForeground(true);
}

StopSelf();

否则,我会看到服务重新启动而没有自行停止的奇怪事情。


推荐阅读