首先寫一個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停掉的時候去除通知欄。