android startForeground去除通知栏

首先写一个BootstartService,顾名思义,这个service只是起引导作用,干完活就退出了。最精华的部分其实就是这句stopSelf(),说白了这个service其实还没起起来就被停掉了,这样onDestroy()里就会调用stopForeground(),通知栏的常驻通知就会被消掉。

public class BootstartService extends Service {  
    @Override  
    public void onCreate() {  
        super.onCreate();  
        startForeground(this);  
        // stop self to clear the notification  
        stopSelf();  
    }  
  
    @Override  
    public void onDestroy() {  
        super.onDestroy();  
        stopForeground(true);  
    }  
  
    public static void startForeground(Service context) {  
        context.startForeground(8888, new Notification());  
    }  
}  

接下来写我们的主service,主service会先调用一次startForeground(),然后再启动BootstartService。

public class MainService extends Service {  
    @Override  
    public void onCreate() {  
        super.onCreate();  
        BootstrapService.startForeground(this);  
        // start BootstartService to remove notification  
        Intent intent = new Intent(this, BootstartService.class);  
        startService(intent);  
    }  
  
    @Override  
    public void onDestroy() {  
        super.onDestroy();  
        stopForeground(true);  
    }  
}  

看到这里大家应该已经明白了,说白了就是两个service共用一个notification ID,第一个service起来的时候会显示通知栏,然后第二个service停掉的时候去除通知栏。

参考文章

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 如何能让我们的应用能够在系统后台持续地运行是一个自Android从娘胎里出来时就议论不停的话题,而且这似乎成了一个...
    骏骏的简书阅读 1,132评论 1 19
  • Service的生命周期 service的生命周期,从它被创建开始,到它被销毁为止,可以有两条不同的路径: A s...
    _执_念__阅读 1,584评论 0 19
  • 参考: 服务|Android Developers 一. 什么是服务 服务是一个可以在后台执行长时间运行操作而不提...
    NickelFox阅读 561评论 0 3
  • 转载注明出处:http://www.jianshu.com/p/a1d3d9693e91 1. 简介 与前一篇An...
    王三的猫阿德阅读 1,980评论 1 9
  • 前言:本文所写的是博主的个人见解,如有错误或者不恰当之处,欢迎私信博主,加以改正!原文链接,demo链接 Serv...
    PassersHowe阅读 1,446评论 0 5