在我的应用程序中,我让用户下载文件。由于用户知道它是一个很长的动作,所以我决定使用一个服务,并将它作为前台服务启动,我希望该服务能够启动,完成下载并终止自身,它不应该一直运行。
这是我从我的主要活动开始服务的电话。
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);
.I之后仍然继续工作,因为它仍然会消耗资源,而且系统不会轻易地杀死它,因为它是前台服务。
我可以看到,我的服务运行在中,我的应用程序仍然运行在VS2015中的调试中。
知道吗?还有什么其他方法可以杀了这个服务吗?
发布于 2016-09-17 10:37:12
stopForeground()方法只停止Service
的前台状态。使用false
作为参数,它甚至不会删除通知,这可能是您希望它做的,所以您可以将它切换到true
。
要使Service
停止自身,您可以调用stopSelf()。
所以您的代码可以是这样的:
Task.Factory.StartNew(async () => {
await download(id);
stopForeground(true);
stopSelf();
});
(...unless,在没有实际运行代码的情况下,我忽略了一些次要的细节。但你还是有了基本的想法。)
https://stackoverflow.com/questions/39545214
复制相似问题