我使用以下代码来保持服务处于活动状态:
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
...
keepServiceAlive(this, 2222);
return super.onStartCommand(intent, flags, startId);
}
@SuppressWarnings("deprecation")
public void keepServiceAlive(Service service, int id) {
Notification note = new Notification(0, null, System.currentTimeMillis());
note.flags |= Notification.FLAG_NO_CLEAR;
service.startForeground(id, note);
}
但有时服务仍然被杀死。您能否帮我确认这段代码的正确性,或者您会提供更好的解决方案吗?