Xamarin Android 我需要在应用程序关闭时终止前台服务和通知 [英] Xamarin Android I need to kill a Foreground Service and a Notification when app has been closed

查看:43
本文介绍了Xamarin Android 我需要在应用程序关闭时终止前台服务和通知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Let me explain the scenario.
I have a task I need to schedule in every 10 minutes.
This task needs both network and disk resources EVEN if the app is in the background AND even if the Battery Saver has kicked in.
I tried AlarmManager, JobScheduler, and ForegroundService.
Then only one that seems to work when Battery Saver kicks in is the ForegroundService.

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

In xamarin I have started a Foreground Service in the MainActivity.cs like the following.

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

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

Inside my "foreground" service I have a Notification that is displayed in android.
I need to kill the foreground service when the application is closed by the user swiping it off the screen or hitting the "X".

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

This section DOES kill / close the notification but it does not feel right in that I am calling StartService again just to kill the service.

测试服务

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();
}

推荐答案

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

To stop a foreground service I usually use:

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

这将依次触发前台服务内部的 OnDestroy().

This will in turn trigger OnDestroy() inside of the foreground service.

OnDestroy() 中,我会这样做:

In OnDestroy() I then do:

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

StopSelf();

否则我会看到服务重新启动而没有自行停止的奇怪现象.

Otherwise I have seen odd things with the service starting again, without it stopping itself.

这篇关于Xamarin Android 我需要在应用程序关闭时终止前台服务和通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆