杰瑞科技汇

SmsLib for Java如何快速上手?

Of course! Here's a comprehensive guide to using SMSLib for Java, a powerful and popular open-source library for sending and receiving SMS messages.

SmsLib for Java如何快速上手?-图1
(图片来源网络,侵删)

What is SMSLib?

SMSLib is a Java library designed to simplify the process of interacting with mobile phones, GSM modems, and SMS gateways. It abstracts away the complexities of the AT command set and provides a clean, high-level API for common SMS operations.

Key Features:

  • Multi-Protocol Support: Works with GSM modems (connected via serial/USB), HTTP gateways, and SMPP servers.
  • Core Operations: Send, receive, and delete SMS messages.
  • Message Types: Supports Text, Binary, WAP Push, and Unicode messages.
  • Advanced Features: Message scheduling, delivery reports, and multi-part (concatenated) SMS handling.
  • Extensible: Easy to add support for new gateways or protocols.

Prerequisites & Setup

Before you start, you need to have the following ready:

a) Java Development Kit (JDK)

Ensure you have JDK 8 or later installed.

SmsLib for Java如何快速上手?-图2
(图片来源网络,侵删)

b) SMSLib Library

The easiest way to add SMSLib to your project is via a build tool like Maven or Gradle.

Using Maven (pom.xml): Add the following dependency to your pom.xml file. SMSLib is hosted on Maven Central.

<dependencies>
    <dependency>
        <groupId>org.smslib</groupId>
        <artifactId>smslib</artifactId>
        <version>5.0.1</version> <!-- Check for the latest version on Maven Central -->
    </dependency>
</dependencies>

Using Gradle (build.gradle):

dependencies {
    implementation 'org.smslib:smslib:5.0.1' // Check for the latest version
}

c) Hardware: GSM Modem or Phone

You need a device that can act as a gateway. This is typically:

  • A dedicated GSM Modem (e.g., Wavecom, Siemens).
  • An old mobile phone with a data cable or Bluetooth connection.
  • A USB Dongle that supports AT commands.

You will also need the correct driver for your device so your computer can recognize it.

d) COM Port / Serial Port

You need to know the serial port (COM port on Windows, /dev/tty... on Linux/macOS) that your device is connected to.

  • Windows: Open Device Manager and look under "Ports (COM & LPT)".
  • Linux: Run ls /dev/tty* or dmesg | grep tty.

Sending an SMS (Simple Example)

This is the most common use case. We'll connect to a GSM modem and send a simple text message.

import org.smslib.*;
import org.smslib.modem.SerialModemGateway;
public class SendSmsExample {
    public static void main(String[] args) {
        // 1. Create a new Gateway instance
        // Parameters: Gateway ID, COM Port, Baud Rate, PIN (if any)
        SerialModemGateway gateway = new SerialModemGateway("modem.com1", "COM1", 115200, "");
        // 2. Configure the Gateway (optional but recommended)
        gateway.setInbound(true); // Enable inbound messages (receiving)
        gateway.setOutbound(true); // Enable outbound messages (sending)
        gateway.setSimPin("0000"); // Set your SIM PIN if required
        // 3. Create the Service and add the Gateway
        Service service = Service.getInstance();
        service.addGateway(gateway);
        try {
            // 4. Start the service and connect to the gateway
            System.out.println("Connecting to the gateway...");
            service.startService();
            System.out.println("Gateway connected.");
            // 5. Create the Outbound Message
            OutboundMessage msg = new OutboundMessage("+1234567890", "Hello from SMSLib!");
            // Replace +1234567890 with the recipient's phone number
            // 6. Send the message
            System.out.println("Sending message...");
            service.sendMessage(msg);
            System.out.println("Message sent successfully.");
            System.out.println("Message ID: " + msg.getUuid());
            System.out.println("Status: " + msg.getStatus());
        } catch (Exception e) {
            System.err.println("Error: " + e.getMessage());
            e.printStackTrace();
        } finally {
            // 7. Stop the service and disconnect
            try {
                System.out.println("Stopping the service...");
                service.stopService();
                System.out.println("Service stopped.");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

Explanation:

  1. SerialModemGateway: This class represents a GSM modem connected via a serial port. You provide its ID, the COM port, the baud rate, and the SIM PIN.
  2. Service.getInstance(): This is the central point of control for SMSLib. You add gateways to this service.
  3. service.startService(): This initializes the connection to the modem and puts it in an operational state.
  4. OutboundMessage: This object represents an SMS you want to send. It takes the recipient's number and the message text.
  5. service.sendMessage(msg): This is the core method that sends the message.
  6. service.stopService(): It's crucial to close the connection properly when you're done.

Receiving an SMS

Receiving messages requires setting up a listener to handle incoming messages as they arrive.

import org.smslib.*;
import org.smslib.modem.SerialModemGateway;
public class ReceiveSmsExample {
    public static void main(String[] args) {
        SerialModemGateway gateway = new SerialModemGateway("modem.com1", "COM1", 115200, "");
        gateway.setInbound(true);
        gateway.setOutbound(true);
        gateway.setSimPin("0000");
        Service service = Service.getInstance();
        service.addGateway(gateway);
        // 1. Create a message listener
        service.setMessageListener(new MessageListener() {
            @Override
            public void process(InterfaceGateway gateway, Message message) {
                // This method is called for every incoming message
                if (message instanceof InboundMessage) {
                    InboundMessage inboundMsg = (InboundMessage) message;
                    System.out.println("----------------------------------------------------");
                    System.out.println("Received new message from: " + inboundMsg.getOriginator());
                    System.out.println("Message text: " + inboundMsg.getText());
                    System.out.println("Received at: " + inboundMsg.getDate());
                    System.out.println("----------------------------------------------------");
                    // Optional: Delete the message from the phone's memory after reading
                    try {
                        gateway.deleteMessage(inboundMsg);
                        System.out.println("Message deleted from phone.");
                    } catch (Exception e) {
                        System.err.println("Could not delete message: " + e.getMessage());
                    }
                }
            }
        });
        try {
            System.out.println("Connecting to the gateway...");
            service.startService();
            System.out.println("Gateway connected. Waiting for messages...");
            // Keep the program running to listen for messages
            // In a real application, you would run this in a separate thread
            Thread.sleep(60000); // Listen for 1 minute
        } catch (Exception e) {
            System.err.println("Error: " + e.getMessage());
            e.printStackTrace();
        } finally {
            try {
                System.out.println("Stopping the service...");
                service.stopService();
                System.out.println("Service stopped.");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

Explanation:

  1. setMessageListener(): You register a listener with the service. This listener must implement the MessageListener interface.
  2. process() method: This method is automatically invoked whenever a new message is detected.
  3. InboundMessage: The message object passed to the listener will be an instance of InboundMessage for incoming SMS.
  4. gateway.deleteMessage(): It's good practice to delete messages from the modem's memory after you've processed them to avoid filling up the storage.

Alternative: Using an HTTP Gateway

If you don't want to deal with a physical GSM modem, you can use an SMS provider's HTTP API. SMSLib has built-in support for this.

You'll need an account with an SMS provider (like Twilio, Vonage, ClickSend, etc.) that offers an HTTP API.

import org.smslib.*;
import org.smslib.http.HttpGateway;
public class SendSmsHttpExample {
    public static void main(String[] args) {
        // 1. Create an HTTP Gateway
        // Parameters: Gateway ID, Provider's URL, Username, Password
        HttpGateway gateway = new HttpGateway(
            "http.gateway",
            "https://api.twilio.com/2010-04-01/Accounts/ACxxx/Messages.json", // Example URL
            "your_account_sid", // Your API username/ID
            "your_auth_token"  // Your API password/Token
        );
        gateway.setOutbound(true);
        Service service = Service.getInstance();
        service.addGateway(gateway);
        try {
            System.out.println("Starting HTTP gateway service...");
            service.startService();
            // 2. Create and send the message
            OutboundMessage msg = new OutboundMessage("+1234567890", "Hello from SMSLib via HTTP!");
            System.out.println("Sending message via HTTP...");
            service.sendMessage(msg);
            System.out.println("Message sent successfully.");
        } catch (Exception e) {
            System.err.println("Error: " + e.getMessage());
            e.printStackTrace();
        } finally {
            try {
                System.out.println("Stopping the service...");
                service.stopService();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

Note: The exact configuration for an HTTP gateway depends entirely on the provider's API. You may need to extend HttpGateway or use a specific implementation provided by SMSLib for your provider.


Advanced Features

a) Multi-Part (Concatenated) SMS

For messages longer than 160 characters (GSM-7) or 70 characters (Unicode), SMSLib automatically splits them into multiple parts and reassembles them on the recipient's phone.

// SMSLib handles this automatically
OutboundMessage longMsg = new OutboundMessage("+1234567890", "This is a very long message that will definitely exceed the standard 160 character limit for a single SMS. SMSLib will cleverly split this into multiple parts for you.");
service.sendMessage(longMsg);

b) Delivery Reports

To get a notification when a message is delivered, you can request a delivery report and listen for InboundDeliveryStatusReport messages.

// In your listener
service.setMessageListener(new MessageListener() {
    @Override
    public void process(InterfaceGateway gateway, Message message) {
        if (message instanceof InboundDeliveryStatusReport) {
            InboundDeliveryStatusReport report = (InboundDeliveryStatusReport) message;
            System.out.println("Delivery Report for Message ID: " + report.getMessageId());
            System.out.println("Status: " + report.getStatus());
            System.out.println("To: " + report.getRecipient());
        }
        // ... other message handling
    }
});
// When sending, request a report
OutboundMessage msg = new OutboundMessage("+1234567890", "Please send a delivery report for this.");
msg.setDeliveryReport(true); // This is the key line
service.sendMessage(msg);

Important Considerations

  • Error Handling: Always wrap your code in try...catch blocks. SMS operations can fail for many reasons (modem not found, wrong PIN, no network signal, etc.).
  • Threading: The Service should be run in its own thread if your application needs to do other things while listening for messages. The startService() and stopService() methods are not thread-safe.
  • Legal and Ethical Use: Never send unsolicited SMS (spam). Use SMSLib responsibly and only with the explicit consent of the recipients. Be aware of the laws in your country regarding SMS communications.
分享:
扫描分享到社交APP
上一篇
下一篇