首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >StopForeground不停止前台服务

StopForeground不停止前台服务
EN

Stack Overflow用户
提问于 2016-09-17 09:34:57
回答 1查看 1.5K关注 0票数 1

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

这是我从我的主要活动开始服务的电话。

代码语言:javascript
运行
复制
Intent intent = new Intent(this, typeof(DownloaderService));
intent.PutExtra("id", ID);
StartService(intent);  

下面是作为前台服务启动服务的方式,这是DownloaderService类中的

代码语言:javascript
运行
复制
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);
}

以下是我如何处理意图

代码语言:javascript
运行
复制
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中的调试中。

知道吗?还有什么其他方法可以杀了这个服务吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-09-17 10:37:12

stopForeground()方法只停止Service的前台状态。使用false作为参数,它甚至不会删除通知,这可能是您希望它做的,所以您可以将它切换到true

要使Service停止自身,您可以调用stopSelf()

所以您的代码可以是这样的:

代码语言:javascript
运行
复制
Task.Factory.StartNew(async () => {
        await download(id);
        stopForeground(true);
        stopSelf();  
    });

(...unless,在没有实际运行代码的情况下,我忽略了一些次要的细节。但你还是有了基本的想法。)

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39545214

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档