【发布时间】: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