首先写一个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停掉的时候去除通知栏。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐