stop前台不会停止前台服务

本文关键字:前台 服务 stop | 更新日期: 2023-09-27 18:07:32

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

下面是我从主活动启动服务的调用。

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

下面是我如何处理intent

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

下载方法必须为async。

我这里的问题是,服务火灾很好,做download(id)方法很好,即使我关闭应用程序(这是我想要的)。但是在调用StopForeground(false);之后继续工作,我不需要它之后运行,因为它仍然会消耗资源,并且系统不会轻易杀死它,因为它是一个前台服务。

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

你知道吗?还有其他方法可以终止服务吗?

stop前台不会停止前台服务

stopForeground()方法只停止Service前景状态。用false作为参数,它甚至不删除通知,你可能想要它这样做,所以你可以切换到true

要使Service停止自己,可以调用stopSelf()。

所以你的代码可以是这样的:
Task.Factory.StartNew(async () => {
        await download(id);
        stopForeground(true);
        stopSelf();  
    });

(…除非在实际运行代码的情况下遗漏了一些小细节。但是你已经了解了基本的概念。