首先寫一個(gè)BootstartService,顧名思義帝雇,這個(gè)service只是起引導(dǎo)作用通殃,干完活就退出了。最精華的部分其實(shí)就是這句stopSelf()湾碎,說白了這個(gè)service其實(shí)還沒起起來就被停掉了宙攻,這樣onDestroy()里就會(huì)調(diào)用stopForeground(),通知欄的常駐通知就會(huì)被消掉介褥。
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會(huì)先調(diào)用一次startForeground(),然后再啟動(dòng)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);
}
}
看到這里大家應(yīng)該已經(jīng)明白了溢陪,說白了就是兩個(gè)service共用一個(gè)notification ID,第一個(gè)service起來的時(shí)候會(huì)顯示通知欄睛廊,然后第二個(gè)service停掉的時(shí)候去除通知欄形真。