如何用Smack实现延迟交付(XEP-203)?求DelayInformationManager使用示例
Using Smack's DelayInformationManager for XEP-203 Delayed Delivery
Got it, let's break down a straightforward, working example of using DelayInformationManager to send delayed messages with Smack. I'll assume you already have an initialized XMPPTCPConnection (let's call it connection) set up and connected to your XMPP server.
Step 1: Get the DelayInformationManager instance
Smack's managers are tied to a connection, so grab the instance like this:
DelayInformationManager delayManager = DelayInformationManager.getInstanceFor(connection);
Step 2: Create your message and add delay rules
You have two common ways to define the delay: relative time (e.g., send in 10 minutes) or absolute time (e.g., send at 3 PM tomorrow).
Option A: Delay by a relative time
// Define your target recipient's JID Jid targetJid = JidCreate.from("jane@your-xmpp-domain.com"); // Build a basic message Message delayedMessage = MessageBuilder.buildMessage() .to(targetJid) .setBody("Hey, this message was scheduled to send later!") .build(); // Add a 10-minute delay (convert to milliseconds) long delayInMillis = 10 * 60 * 1000; delayManager.addDelayInformation(delayedMessage, delayInMillis);
Option B: Delay until a specific future time
// Set a specific future time (e.g., 2 hours from now) Calendar futureDeliveryTime = Calendar.getInstance(); futureDeliveryTime.add(Calendar.HOUR_OF_DAY, 2); Date delayUntil = futureDeliveryTime.getTime(); // Add the absolute delay to your message delayManager.addDelayInformation(delayedMessage, delayUntil);
Step 3: Send the delayed message
Once the delay is attached, send the message like any other Smack stanza:
connection.sendStanza(delayedMessage);
Quick Notes
- Server Support: Make sure your XMPP server implements XEP-203—if it doesn't, the delay will be ignored and the message sends immediately.
- Check Delay Info: You can verify if a message has delay metadata with
delayManager.hasDelayInformation(message). - Retrieve Delay Info: To get the scheduled delivery time from a message, use
delayManager.getDelayInformation(message).
内容的提问来源于stack exchange,提问作者JohnCalms
相关产品推荐
相关产品推荐

