【问题标题】:StopForeground doesn't stop foreground serviceStopForeground 不会停止前台服务
【发布时间】:2017-01-25 11:49:59
【问题描述】:

在我的应用程序中,我让用户下载文件。由于用户知道这是一个漫长的动作,我决定使用一项服务,并将其作为前台服务启动。我希望该服务启动,完成下载并自行终止,它不应该一直运行.

这是我为启动服务而发起的调用,来自我的主要活动。

Intent intent = new Intent(this, typeof(DownloaderService));
intent.PutExtra("id", ID);
StartService(intent);  

这是我如何将服务作为前台服务启动的,这是在 DownloaderService 类中

public override void OnCreate()
{
    //Start this service as foreground
    Intent notificationIntent = new Intent(this, typeof(VideoDownloaderService));

    PendingIntent pendingIntent = PendingIntent.GetActivity(this, 0,
                notificationIntent, 0);

    Notification notification = new Notification.Builder(this)
                       .SetSmallIcon(Resource.Drawable.Icon)
                       .SetContentTitle("Initializing")
                       .SetContentText("Starting The Download...")
                       .SetContentIntent(pendingIntent).Build();

    StartForeground(notificationID, notification);
}

这是我处理意图的方式

public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
{
    var id = intent.GetStringExtra("id");

    Task.Factory.StartNew(async () => {
        await download(id);
        StopForeground(false);
    });

    return StartCommandResult.NotSticky;
}

下载方法必须是异步的。

我的问题是服务启动正常,download(id) 方法是否正常,即使我关闭应用程序(这就是我想要的)。但是即使在调用StopForeground(false); 之后仍然可以继续工作。我不需要它在之后运行,因为它仍然会消耗资源,并且系统不会轻易杀死它,因为它是前台服务。

我可以看到我的服务在 Android 设备管理器中运行,并且我的应用程序仍在 VS2015 的调试中运行。

有什么想法吗?有没有其他方法可以杀死服务?

【问题讨论】:

    标签: c# android service xamarin.android


    【解决方案1】:

    stopForeground() 方法仅停止Service前台状态。并且使用false 作为参数,它甚至不会删除您可能希望它执行的通知,因此您可以将其切换为true

    要使Service 自行停止,您可以调用stopSelf()

    所以你的代码可能是这样的:

    Task.Factory.StartNew(async () => {
            await download(id);
            stopForeground(true);
            stopSelf();  
        });
    

    (...除非我在没有实际运行代码的情况下遗漏了一些小细节。但无论如何你都会明白基本的想法。)

    【讨论】:

    • 好像不行,我还能看到进程,vs还在调试中。我确实尝试覆盖 OnDestroy() 方法,并且我看到该方法正在被调用,但是该进程并没有死。也许它是正常的?
    • 嗯,Xamarin/C# 世界中的情况可能有所不同。写这篇文章时,我的脑子里是“常规的 Android Java”,因为那是我所熟悉的。
    • 应该表现相同,因为 xamarin.android 本质上只是 java 版本的一个端口。
    • 您遇到过这个问题吗?我看到的完全一样,如果我启动了前台服务,调用 StopForeground 然后 StopSelf 不会杀死应用程序/调试器。如果我不调用 StartForeground 那么它会正确关闭。
    猜你喜欢
    • 2019-08-06
    • 2023-03-12
    • 2018-11-11
    • 1970-01-01
    • 1970-01-01
    • 2019-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多