美文网首页
android startForeground去除通知栏

android startForeground去除通知栏

作者: 关阝 | 来源:发表于2016-12-09 15:36 被阅读0次

首先写一个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 startForeground去除通知栏

      本文链接:https://www.haomeiwen.com/subject/sdnemttx.html