发送短信的关键代码如下:
MessageConnection mconn = null; try { mconn = (MessageConnection) Connector.open("sms://+8618688880000"); TextMessage m = (TextMessage) mconn .newMessage(MessageConnection.TEXT_MESSAGE); m.setAddress("sms://+8618688880000"); m.setPayloadText("短信内容"); mconn.send(m); } catch (Exception e) { e.printStackTrace(); } finally { try { mconn.close(); } catch (IOException e) { e.printStackTrace(); } }
import java.io.IOException; import javax.microedition.io.Connector; import javax.wireless.messaging.MessageConnection; import javax.wireless.messaging.TextMessage; /** * 发短信助手 * * @author Denger * */ public class SMSHelper { private static final String TAG = "SMSHelper"; /** * 发送SMS * * @param lsn * 短信发送监听器 * @param number * 手机号码,不需要加“+86” * @param msg * 短信内容 */ public static void sendSMS(final ISMSSenderListener lsn, final String number, final String msg) { new Thread() { public void run() { send(lsn, number, msg); }; }.start(); } /** * 发送SMS * * @param lsn * 短信发送监听器 * @param numbers * 手机号码数组 * @param msg * 短信内容 */ public static void sendSMS(final ISMSSenderListener lsn, final String[] numbers, final String msg) { new Thread() { public void run() { for (int i = 0; i < numbers.length; i++) { send(lsn, numbers[i], msg); try { sleep(500); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }.start(); } /** * 格式化手机号码:如果传入的手机号码前面加了“+86”,则去掉 * * @param number * @return */ public static String formatNumber(String number) { if (number.startsWith("+86")) { return number.substring(3); } return number; } private static void send(ISMSSenderListener lsn, String number, String msg) { MessageConnection mconn = null; String addr = "sms://+86"; try { number = formatNumber(number); addr += number; lsn.onSendStateChange(addr, ISMSSenderListener.SENDING); Log.d(TAG, "发送短信,地址:" + addr); mconn = (MessageConnection) Connector.open(addr); TextMessage m = (TextMessage) mconn .newMessage(MessageConnection.TEXT_MESSAGE); m.setAddress(addr); m.setPayloadText(msg); mconn.send(m); lsn.onSendStateChange(addr, ISMSSenderListener.SENDOVER); Log.d(TAG, "发送短信,结束"); } catch (Exception e) { e.printStackTrace(); lsn.onSendStateChange(addr, ISMSSenderListener.SENDERROR); Log.e(TAG, "发送出错:" + e.getMessage()); } finally { try { mconn.close(); } catch (IOException e) { e.printStackTrace(); } } } }
/** * SMS发送的监听器 * * @author Denger * */ public interface ISMSSenderListener { /** * 正在发送 */ public static final int SENDING = 0; /** * 发送结束 */ public static final int SENDOVER = 1; /** * 发送出错 */ public static final int SENDERROR = -1; /** * SMS发送时的回调 * * @param state * 返回发送的状态,详见本接口的常量 */ void onSendStateChange(String num, int state); }