import java.io.IOException;

import javax.microedition.io.Connector;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
import javax.wireless.messaging.MessageConnection;
import javax.wireless.messaging.TextMessage;

public class SendMessage extends MIDlet implements CommandListener {

	private Form formSMS;
	private TextField tfPhoneNumber;
	private TextField tfMsg;
	private Display myDisplay;
	private Command cmdExit;
	private Command cmdSend;

	public SendMessage() {
		// TODO Auto-generated constructor stub
	}

	protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
		// TODO Auto-generated method stub

	}

	public void sendSMS(String phoneNumber, String content) {

		MessageConnection connection;
		try {
			connection = (MessageConnection) Connector.open("sms://"
					+ phoneNumber);

			TextMessage sms = (TextMessage) connection
					.newMessage(MessageConnection.TEXT_MESSAGE);
			sms.setPayloadText(content);
			connection.send(sms);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	protected void pauseApp() {
		// TODO Auto-generated method stub

	}

	protected void startApp() throws MIDletStateChangeException {
		formSMS = new Form("Envoi SMS");
		tfPhoneNumber = new TextField("Numero de telephone: ", "", 15,
				TextField.PHONENUMBER);
		tfMsg = new TextField("Message: ", "", 140, TextField.ANY);
		formSMS.append(tfPhoneNumber);
		formSMS.append(tfMsg);
		myDisplay = Display.getDisplay(this);
		cmdExit = new Command("Exit", Command.EXIT, 0);
		formSMS.addCommand(cmdExit);
		cmdSend = new Command("Envoi", Command.SCREEN, 1);
		formSMS.addCommand(cmdSend);
		formSMS.setCommandListener(this);
		myDisplay.setCurrent(formSMS);
	}

	public void commandAction(Command cmd, Displayable arg1) {
		if (cmd == cmdSend) {
			new Thread(new Runnable() {

				public void run() {
					sendSMS(tfPhoneNumber.getString(), tfMsg.getString());

				}
			}).start();
		}

	}

}
