import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.wireless.messaging.*;
import javax.microedition.io.*;
import java.io.*;
public class KirimSMS extends MIDlet
implements CommandListener, Runnable {
private Display display;
private Command cmdKeluar, cmdLanjut, cmdKembali, cmdKirim;
private Displayable prevScreen;
private TextBox tfNum, tfText;
private String port;
private Thread thread;
private Alert alert;
private final String INVALID_PHONE =
"Nomor yang dimasukkan tidak absah";
public KirimSMS() {
display = Display.getDisplay(this);
port = getAppProperty("Port-SMS");
cmdKeluar = new Command("Keluar", Command.EXIT, 1);
cmdLanjut = new Command("Lanjut", Command.SCREEN, 1);
cmdKembali = new Command("Kembali", Command.BACK, 1);
cmdKirim = new Command("Kirim", Command.SCREEN, 1);
alert = new Alert(null);
alert.setTimeout(3000);
}
public void startApp() {
tfNum = generatePhoneInput();
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public void commandAction(Command c, Displayable s) {
if (c == cmdKeluar) {
destroyApp(false);
notifyDestroyed();
} else if (c == cmdKembali) {
display.setCurrent(tfNum);
} else if (c == cmdLanjut) {
if (!isValidPhoneNumber(tfNum.getString())) {
alert.setType(AlertType.ERROR);
alert.setString(INVALID_PHONE);
display.setCurrent(alert,tfNum);
} else {
tfText = generateMessageInput();
}
} else {
thread = new Thread(this);
thread.start();
}
}
public void run() {
MessageConnection conn = null;
String alamat = "sms://" + tfNum.getString() + ":" + port;
try {
conn = (MessageConnection) Connector.open(alamat);
TextMessage pesan = (TextMessage)
conn.newMessage(MessageConnection.TEXT_MESSAGE);
pesan.setAddress(alamat);
pesan.setPayloadText(tfText.getString());
conn.send(pesan);
alert.setString("Sedang mengirim ke nomor " +
alamat.substring(6));
alert.setType(AlertType.INFO);
display.setCurrent(alert);
} catch (IOException ioe) {
ioe.printStackTrace();
}
if (conn != null) {
try {
conn.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
public TextBox generatePhoneInput() {
TextBox tfPhone = new TextBox("Nomor Tujuan?", null,
15, TextField.PHONENUMBER);
tfPhone.addCommand(cmdKeluar);
tfPhone.addCommand(cmdLanjut);
tfPhone.setCommandListener(this);
display.setCurrent(tfPhone);
return tfPhone;
}
public TextBox generateMessageInput() {
TextBox tfMessage = new TextBox("Teks Pesan", null,
500, TextField.ANY);
tfMessage.addCommand(cmdKembali);
tfMessage.addCommand(cmdKirim);
tfMessage.setCommandListener(this);
display.setCurrent(tfMessage);
return tfMessage;
}
private static boolean isValidPhoneNumber(String number) {
char[] chars = number.toCharArray();
if (chars.length == 0) {
return false;
}
int startPos = 0;
// jika diawali dengan tanda +
if (chars[0] == '+') {
startPos = 1;
}
for (int i = startPos; i < chars.length; ++i) {
if (!Character.isDigit(chars[i])) {
return false;
}
}
return true;
}
}
No comments:
Post a Comment