首先寫(xiě)一個(gè)BootstartService,顧名思義,這個(gè)service只是起引導(dǎo)作用,干完活就退出了。最精華的部分其實(shí)就是這句stopSelf(),說(shuō)白了這個(gè)service其實(shí)還沒(méi)起起來(lái)就被停掉了,這樣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());
}
}
接下來(lái)寫(xiě)我們的主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)明白了,說(shuō)白了就是兩個(gè)service共用一個(gè)notification ID,第一個(gè)service起來(lái)的時(shí)候會(huì)顯示通知欄,然后第二個(gè)service停掉的時(shí)候去除通知欄。