《Message.java的消息处理》一文深入探讨了Java编程中消息对象的管理和操作技巧,涵盖了消息接收、解析及响应的最佳实践。适合中级开发者阅读和学习。
```java
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.wireless.messaging.*;
import java.io.IOException;
import javax.microedition.io.*;
public class Message extends MIDlet implements CommandListener {
private Form form; // The form UI object
private TextBox tb; // The SMS Text Entry UI object
private TextField tf; // The text field for phone number
private Command exitCmd; // The exit command object
private Command composeCmd; // The compose SMS command object
private Command sendCmd; // The send SMS command object
private Display display; // 显示对象
private String txPort = 10000; //定义发送端口号
public Message() {
/*初始化对象*/
form = new Form(SMS Transmit);
tf = new TextField(Enter Phone Number, , 25, TextField.PHONENUMBER);
tb = new TextBox(Compose SMS, , 100, TextField.ANY);
composeCmd = new Command(Compose, Command.SCREEN, 2);
sendCmd = new Command(Send, Command.SCREEN, 2);
exitCmd = new Command(Exit, Command.EXIT, 3);
display = Display.getDisplay(this);
// Build Form UI
form.addCommand(exitCmd);
form.addCommand(composeCmd);
form.append(tf);
form.setCommandListener(this);
// Build TextBox UI
tb.addCommand(exitCmd);
tb.addCommand(sendCmd);
// Associate使联合 display with form
display.setCurrent(form);
}
public void startApp() throws MIDletStateChangeException {
}
public void pauseApp() {
}
public void destroyApp( boolean unconditional ) {
}
public void commandAction(Command c, Displayable s)
{
if (c == exitCmd)
{
destroyApp(false);
notifyDestroyed();
}
if (c == composeCmd)
{
if (tf.getString().length() > 5)
{
// Switch UI to TextBox
display.setCurrent(tb);
tb.setCommandListener(this);
}
else
{
out(Phone Number Invalid Length);
dbg(Message.commandAction(): Phone Number Invalid Length);
}
}
if (c == sendCmd)
{
sendSMS(tb.getString());
}
}
// 能实际发送手机短信的到的WMA服务器的方法
private void sendSMS(String s)
{
try
{
String addr = sms:// + tf.getString() + : + txPort;
MessageConnection conn = (MessageConnection) Connector.open(addr);
TextMessage msg = (TextMessage)conn.newMessage(MessageConnection.TEXT_MESSAGE);
msg.setPayloadText(tb.getString());
conn.send(msg);
dbg(Message.sendSMS(): + tb.getString());
}
catch (IOException ioe)
{
dbg(Message.sendSMS(): + ioe.toString()); //生成
}
}
private void out(String s)
{ form.append(s + \n);
}
private void dbg(String s)
{ System.out.println(s);
}
}
```