1. 程式人生 > >簡訊收發封裝的一個工具類

簡訊收發封裝的一個工具類

import java.util.ArrayList;
import java.util.List;

import javax.crypto.spec.SecretKeySpec;

import org.apache.log4j.Logger;
import org.smslib.AGateway;
import org.smslib.GatewayException;
import org.smslib.ICallNotification;
import org.smslib.IGatewayStatusNotification;
import org.smslib.IInboundMessageNotification;
import org.smslib.IOrphanedMessageNotification;
import org.smslib.IOutboundMessageNotification;
import org.smslib.InboundMessage;
import org.smslib.Library;
import org.smslib.OutboundMessage;
import org.smslib.Service;
import org.smslib.AGateway.GatewayStatuses;
import org.smslib.AGateway.Protocols;
import org.smslib.InboundMessage.MessageClasses;
import org.smslib.Message.MessageEncodings;
import org.smslib.Message.MessageTypes;
import org.smslib.crypto.AESKey;
import org.smslib.modem.SerialModemGateway;

/**
 * @author kookob
 * @since 20111219
 */
public class SmsMessageUtil {
	private Logger logger = Logger.getLogger(SmsMessageUtil.class);
	public static Service srv = Service.getInstance();
	
	public static void main(String[] args) throws GatewayException {
		SmsMessageUtil sendMessage = new SmsMessageUtil();
		sendMessage.sendSMS("10086", "測試傳送");
		
		SmsMessageUtil readMessages = new SmsMessageUtil();
		try {
			readMessages.readSMS();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@SuppressWarnings("deprecation")
	public String sendSMS(String mobilePhones, String content) throws GatewayException {
		StringBuilder res = new StringBuilder();
		OutboundMessage msg;
		OutboundNotification outboundNotification = new OutboundNotification();
		SerialModemGateway gateway = new SerialModemGateway("modem.com4", Config.smsCOM, 115200, "wavecom", ""); // 設定埠與波特率
		gateway.setInbound(true);
		gateway.setOutbound(true);
		gateway.setSimPin("1234");
		srv.setOutboundMessageNotification(outboundNotification);
		srv.addGateway(gateway);
		logger.info("初始化成功,準備開啟服務");
		try {
			srv.startService();
			logger.info("服務啟動成功");
			String[] phones = mobilePhones.split(",");
			for (int i = 0; i < phones.length; i++) {
				if("0".equals(phones[i])) {
					res.append("0,"); 
					continue;
				}
				msg = new OutboundMessage(phones[i], content);
				msg.setEncoding(MessageEncodings.ENCUCS2); // 中文
				if(srv.sendMessage(msg)) {
					res.append("1,"); 
				} else {
					res.append("0,");
				}
			}
			srv.stopService();
			srv.removeGateway(gateway);
			return res.substring(0, res.length()-1).toString();
		} catch (Exception e) {
			e.printStackTrace();
			return "fail";
		}
	}
	
	public void readSMS() throws Exception {
		List<InboundMessage> msgList;
		InboundNotification inboundNotification = new InboundNotification();
		CallNotification callNotification = new CallNotification();
		GatewayStatusNotification statusNotification = new GatewayStatusNotification();
		OrphanedMessageNotification orphanedMessageNotification = new OrphanedMessageNotification();
		try {
			logger.info("Example: Read messages from a serial gsm modem.");
			logger.info(Library.getLibraryDescription());
			logger.info("Version: " + Library.getLibraryVersion());
			SerialModemGateway gateway = new SerialModemGateway("modem.com4", Config.smsCOM, 115200, null, null);
			gateway.setProtocol(Protocols.PDU);
			gateway.setInbound(true);
			gateway.setOutbound(true);
			srv.setInboundMessageNotification(inboundNotification);
			srv.setCallNotification(callNotification);
			srv.setGatewayStatusNotification(statusNotification);
			srv.setOrphanedMessageNotification(orphanedMessageNotification);
			srv.addGateway(gateway);
			srv.startService();
			logger.info("Modem Information:");
			logger.info(" Manufacturer: " + gateway.getManufacturer());
			logger.info(" Model: " + gateway.getModel());
			logger.info(" Serial No: " + gateway.getSerialNo());
			logger.info(" SIM IMSI: " + gateway.getImsi());
			logger.info(" Signal Level: " + gateway.getSignalLevel() + "%");
			logger.info(" Battery Level: " + gateway.getBatteryLevel() + "%");
			srv.getKeyManager().registerKey("+8613808080808", new AESKey(new SecretKeySpec("0011223344556677".getBytes(), "AES")));
			msgList = new ArrayList<InboundMessage>();
			srv.readMessages(msgList, MessageClasses.ALL);
			for (InboundMessage msg : msgList) {
				logger.info(msg);
//				srv.deleteMessage(msg);		//刪除簡訊
			}
			srv.stopService();
			srv.removeGateway(gateway);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 發的時候用到
	 */
	public class OutboundNotification implements IOutboundMessageNotification {
		public void process(AGateway agateway, OutboundMessage outboundmessage) {
			logger.info("Outbound handler called from Gateway: " + agateway);
			logger.info(outboundmessage);
		}
	}

	public class InboundNotification implements IInboundMessageNotification {
		public void process(AGateway gateway, MessageTypes msgType, InboundMessage msg) {
			if (msgType == MessageTypes.INBOUND) {
				logger.info(">>> New Inbound message detected from Gateway: " + gateway.getGatewayId());
			} else if (msgType == MessageTypes.STATUSREPORT) {
				logger.info(">>> New Inbound Status Report message detected from Gateway: " + gateway.getGatewayId());
			}
			logger.info(msg);
		}
	}

	public class CallNotification implements ICallNotification {
		public void process(AGateway gateway, String callerId) {
			logger.info(">>> New call detected from Gateway: " + gateway.getGatewayId() + " : " + callerId);
		}
	}

	public class GatewayStatusNotification implements IGatewayStatusNotification {
		public void process(AGateway gateway, GatewayStatuses oldStatus, GatewayStatuses newStatus) {
			logger.info(">>> Gateway Status change for " + gateway.getGatewayId() + ", OLD: " + oldStatus + " -> NEW: " + newStatus);
		}
	}

	public class OrphanedMessageNotification implements IOrphanedMessageNotification {
		public boolean process(AGateway gateway, InboundMessage msg) {
			logger.info(">>> Orphaned message part detected from " + gateway.getGatewayId());
			logger.info(msg);
			return false;
		}
	}

}