在我的应用程序中,我让用户下载文件。由于用户知道它是一个很长的动作,所以我决定使用一个服务,并将它作为前台服务启动,我希望该服务能够启动,完成下载并终止自身,它不应该一直运行。
这是我从我的主要活动开始服务的电话。
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);