Wednesday, July 30, 2008

J2ME Mobile Code



How to send SMS using J2ME

package sms;

import javax.microedition.io.Connector;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.MIDlet;
import javax.wireless.messaging.MessageConnection;
import javax.wireless.messaging.TextMessage;


/**
* The text field demo displays all of the text field types on the screen
* allowing the user to edit them at will.
*
* @version 2.0
*/
public class SMSDemo extends MIDlet implements CommandListener {
private Command exitCommand = new Command("Exit", Command.EXIT, 1);
private Command sendCommand = new Command("Send", Command.SCREEN, 1);

private boolean firstTime;
private Form mainForm;
private TextField txtPhone = null;
private TextField txtMsg = null;

public SMSDemo() {
firstTime = true;
mainForm = new Form("SMS Demo");
}

protected void startApp() {
if (firstTime) {

mainForm.append(txtPhone = new TextField("Phone", "", 15, TextField.PHONENUMBER));
mainForm.append(txtMsg = new TextField("Message","",260, TextField.ANY));
mainForm.addCommand(sendCommand);
mainForm.addCommand(exitCommand);
mainForm.setCommandListener(this);
firstTime = false;
}

Display.getDisplay(this).setCurrent(mainForm);
}

public void commandAction(Command c, Displayable s) {
if (c == exitCommand) {
destroyApp(false);
notifyDestroyed();
}
if (c == sendCommand) {
try
{
String addr = "sms://+91"+ txtPhone.getString() +":50000";
MessageConnection conn = (MessageConnection)Connector.open(addr);
TextMessage msg = (TextMessage)conn.newMessage(MessageConnection.TEXT_MESSAGE);
msg.setPayloadText(txtMsg.getString());
conn.send(msg);

Alert a = new Alert("Success", "Message Sent", null, AlertType.INFO);
Display.getDisplay(this).setCurrent(a);
}
catch(Exception ex)
{
Alert a = new Alert("Message not Sent", ex.getMessage(), null, AlertType.ERROR);
Display.getDisplay(this).setCurrent(a);
}
}
}

protected void destroyApp(boolean unconditional) {
}

protected void pauseApp() {
}
}


Output

No comments: