C# 停止前景色';不要停止前台服务
在我的应用程序中,我允许用户下载文件。由于用户知道这是一个很长的操作,所以我决定使用一个服务,并将其作为前台服务启动。我希望该服务启动、完成下载并自行终止,它不应该一直运行 这是我打电话开始服务的主要活动C# 停止前景色';不要停止前台服务,c#,android,service,xamarin.android,C#,Android,Service,Xamarin.android,在我的应用程序中,我允许用户下载文件。由于用户知道这是一个很长的操作,所以我决定使用一个服务,并将其作为前台服务启动。我希望该服务启动、完成下载并自行终止,它不应该一直运行 这是我打电话开始服务的主要活动 Intent intent = new Intent(this, typeof(DownloaderService)); intent.PutExtra("id", ID); StartService(intent); 下面是我如何启动作为前台服务的服务,这是在DownloaderSer
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;
}
下载方法必须是异步的
我这里的问题是,即使我关闭了应用程序,下载(id)
方法也很好(这是我想要的)。但即使在调用StopForeground(false)后仍继续工作代码>。我不需要在以后运行它,因为它仍然会消耗资源,而且系统不会轻易终止它,因为它是一个前台服务
我可以看到我的应用程序在Android设备管理器中运行,我的应用程序仍在VS2015的调试中运行
有什么想法吗?是否有其他方法终止服务?该方法仅停止服务的前台状态。使用false
作为参数,它甚至不会删除通知,而您可能希望它这样做,因此您可以将其切换为true
要使服务
自行停止,您可以调用
因此,您的代码可能类似于:
Task.Factory.StartNew(async () => {
await download(id);
stopForeground(true);
stopSelf();
});
(…除非在没有实际运行代码的情况下,我遗漏了一些小细节。但无论如何,你都能得到基本的想法。)这似乎不起作用,我仍然可以看到流程,vs仍在调试。我确实试图重写OnDestroy()方法,我看到该方法正在被调用,但进程没有消亡。也许这很正常?好吧,在Xamarin/C#世界中情况可能会有所不同。写这篇文章时,我的想法是“常规Android Java”,因为这是我所熟悉的。应该表现相同,因为xamarin.Android本质上只是Java版本的一个端口。这个问题你有什么进展吗?我看到了完全相同的情况,如果我启动了前台服务,调用StopForeground,那么StopSelf不会杀死应用程序/调试器。如果我不呼叫StartForeground,那么它确实会正确关闭。