List<Message> messages = new ArrayList<Message>();
OfflineMessageRequest request = new OfflineMessageRequest();
request.setFetch(true);
// Filter packets looking for an answer from the server.
PacketFilter responseFilter = new PacketIDFilter(request.getPacketID());
PacketCollector response = connection.createPacketCollector(responseFilter);
// Filter offline messages that were requested by this request
PacketCollector messageCollector = connection.createPacketCollector(packetFilter);
// Send the retrieval request to the server.
connection.sendPacket(request);
// Wait up to a certain number of seconds for a reply.
IQ answer = (IQ) response.nextResult(SmackConfiguration.getPacketReplyTimeout());
// Stop queuing results
response.cancel();
if (answer == null) {
throw new XMPPException("No response from server.");
} else if (answer.getError() != null) {
throw new XMPPException(answer.getError());
}
// Collect the received offline messages
Message message = (Message) messageCollector.nextResult(
SmackConfiguration.getPacketReplyTimeout());
while (message != null) {
messages.add(message);
message =
(Message) messageCollector.nextResult(
SmackConfiguration.getPacketReplyTimeout());
}
// Stop queuing offline messages
messageCollector.cancel();
return messages.iterator();
}