import java.util.LinkedList;
import org.jsmsengine.CIncomingMessage;
import org.jsmsengine.CMessage;
import org.jsmsengine.COutgoingMessage;
import org.jsmsengine.CService;
@SuppressWarnings("unchecked")
/****
* 收发短信的服务类
*/
public class MsgService
{
private static CService cs = null;
public static void init(String port, Integer fm)
{
// 指定端口号和频率
cs = new CService(port, fm);
}
/**
* 发送短信
*
* @param phone
* 手机号
* @param info
* 短信内容
*/
public static void sendmsg(String phone, String info)
{
try
{
System.out.println("正在发送短信");
// 初始化连接
cs.initialize();
// 设置jSMSEngine服务的缓存
cs.setCacheDir(".\\");
// 连接
int status = cs.connect();
// 连接成功(可以是GSM Modem、带有红外线、蓝牙、数据线的手机)
if (status == CService.ERR_OK)
{
cs.setOperationMode(CService.MODE_PDU);
cs.setSmscNumber("");
COutgoingMessage msg = new COutgoingMessage(phone, info);
msg.setMessageEncoding(CMessage.MESSAGE_ENCODING_UNICODE);
if (cs.sendMessage(msg) == CService.ERR_OK)
{
System.out.println("给" + phone + "发送短信成功!");
} else
{
System.out.println("给" + phone + "发送短信失败!");
}
// 断开连接
cs.disconnect();
} else
{
System.out.println("连接设备失败, 异常: " + status);
}
} catch (Exception e)
{
e.printStackTrace();
}
}
/***
* 读取短信内容
*/
public static void readmsg()
{
//存入短信集合
LinkedList msgList = new LinkedList();
try
{
System.out.println("读取短信中。。。。");
cs.initialize();
cs.setCacheDir(".\\");
// 连接设备
int status = cs.connect();
if (status == CService.ERR_OK)
{
cs.setOperationMode(CService.MODE_PDU);
if (cs.readMessages(msgList, CIncomingMessage.CLASS_ALL) == CService.ERR_OK)
for (int i = 0; i < msgList.size(); i++)
{
CIncomingMessage msg = (CIncomingMessage) msgList.get(i);
System.out.println(msg);
//输出短信文本
System.out.println(msg.getText());
//删除短信
cs.deleteMessage(i);
}
// 断开连接
cs.disconnect();
} else
System.out.println("设备连接失败:" + status);
} catch (Exception e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
init("com4", 9600);
sendmsg("15800000000", "这是一个测试程序");
readmsg();
}
}