J2ME SMS : Receiving SMS in J2ME

/*
J2ME SMS
Source code example for receiving SMS in J2ME
*
* @(#)SMSReceive.java 1.11 04/03/22
*
* Copyright (c) 1999-2004 Sun Microsystems, Inc. All rights reserved.
* PROPRIETARY/CONFIDENTIAL
* Use is subject to license terms
*/

package example.sms;

import javax.microedition.midlet.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.wireless.messaging.*;

import java.io.IOException;

/**
* An example MIDlet displays text from an SMS MessageConnection
*/
public class SMSReceive extends MIDlet
implements CommandListener, Runnable, MessageListener {

/** user interface command for indicating Exit request. */
Command exitCommand = new Command("Exit", Command.EXIT, 2);
/** user interface command for indicating Reply request */
Command replyCommand = new Command("Reply", Command.OK, 1);
/** user interface text box for the contents of the fetched URL. */
Alert content;
/** current display. */
Display display;
/** instance of a thread for asynchronous networking and user interface. */
Thread thread;
/** Connections detected at start up. */
String[] connections;
/** Flag to signal end of processing. */
boolean done;
/** The port on which we listen for SMS messages */
String smsPort;
/** SMS message connection for inbound text messages. */
MessageConnection smsconn = null;
/** Current message read from the network. */
Message msg;
/** Address of the message's sender */
String senderAddress;
/** Alert that is displayed when replying */
Alert sendingMessageAlert;
/** Prompts for and sends the text reply */
SMSSender sender;
/** The screen to display when we return from being paused */
Displayable resumeScreen;

/**
* Initialize the MIDlet with the current display object and
* graphical components.
*/
public SMSReceive() {
smsPort = getAppProperty("SMS-Port");

display = Display.getDisplay(this);

content = new Alert("SMS Receive");
content.setTimeout(Alert.FOREVER);
content.addCommand(exitCommand);
content.setCommandListener(this);
content.setString("Receiving...");

sendingMessageAlert = new Alert("SMS", null, null, AlertType.INFO);
sendingMessageAlert.setTimeout(5000);
sendingMessageAlert.setCommandListener(this);

sender = new SMSSender(smsPort, display, content, sendingMessageAlert);

resumeScreen = content;
}

/**
* Start creates the thread to do the MessageConnection receive
* text.
* It should return immediately to keep the dispatcher
* from hanging.
*/
public void startApp() {
// SMS connection to be read.
String smsConnection = "sms://:" + smsPort;
content.setString(smsConnection);

// Open the message connection.

// if (smsconn == null) {
try {
smsconn = (MessageConnection)Connector.open(smsConnection, Connector.READ);
// smsconn.setMessageListener(this);
} catch (Throwable t) {
content.setString(t.toString());
}
// } catch (IOException ioe) {
// content.setString(ioe.toString());
// ioe.printStackTrace();
// }
// }
/*
// Initialize the text if we were started manually.
connections = PushRegistry.listConnections(true);
if (connections == null || connections.length == 0) {
content.setString("Waiting for SMS on port " + smsPort + "...");
}
done = false;
thread = new Thread(this);
thread.start();
*/
display.setCurrent(resumeScreen);
}

/**
* Notification that a message arrived.
* @param conn the connection with messages available
*/
public void notifyIncomingMessage(MessageConnection conn) {
if (thread == null) {
done = false;
thread = new Thread(this);
thread.start();
}
}

/** Message reading thread. */
public void run() {
/** Check for sms connection. */
try {
msg = smsconn.receive();
if (msg != null) {
senderAddress = msg.getAddress();
content.setTitle("From: " + senderAddress);
if (msg instanceof TextMessage) {
content.setString(((TextMessage)msg).getPayloadText());
} else {
StringBuffer buf = new StringBuffer();
byte[] data = ((BinaryMessage)msg).getPayloadData();
for (int i = 0; i < data.length; i++) {
int intData = (int)data & 0xFF;
if (intData < 0x10) {
buf.append("0");
}
buf.append(Integer.toHexString(intData));
buf.append(' ');
}
content.setString(buf.toString());
}
content.addCommand(replyCommand);
display.setCurrent(content);
}
} catch (IOException e) {
// e.printStackTrace();
}
}
/**
* Pause signals the thread to stop by clearing the thread field.
* If stopped before done with the iterations it will
* be restarted from scratch later.
*/
public void pauseApp() {
done = true;
thread = null;
resumeScreen = display.getCurrent();
}

/**
* Destroy must cleanup everything. The thread is signaled
* to stop and no result is produced.
* @param unconditional true if a forced shutdown was requested
*/
public void destroyApp(boolean unconditional) {
done = true;
thread = null;
if (smsconn != null) {
try {
smsconn.close();
} catch (IOException e) {
// Ignore any errors on shutdown
}
}
}

/**
* Respond to commands, including exit
* @param c user interface command requested
* @param s screen object initiating the request
*/
public void commandAction(Command c, Displayable s) {
try {
if (c == exitCommand || c == Alert.DISMISS_COMMAND) {
destroyApp(false);
notifyDestroyed();
} else if (c == replyCommand) {
reply();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}

/**
* Allow the user to reply to the received message
*/
private void reply() {
// remove the leading "sms://" for diplaying the destination address
String address = senderAddress.substring(6);
String statusMessage = "Sending message to " + address + "...";
sendingMessageAlert.setString(statusMessage);
sender.promptAndSend(senderAddress);
}
}

14 comments:

  1. cannot run..
    Got three error..

    C:\Documents and Settings\User\j2mewtk\2.5.2\apps\Online\src\SMSReceive.java:41: cannot find symbol
    symbol : class SMSSender
    location: class SMSReceive
    SMSSender sender;
    ^
    C:\Documents and Settings\User\j2mewtk\2.5.2\apps\Online\src\SMSReceive.java:64: cannot find symbol
    symbol : class SMSSender
    location: class SMSReceive
    sender = new SMSSender(smsPort, display, content, sendingMessageAlert);
    ^
    C:\Documents and Settings\User\j2mewtk\2.5.2\apps\Online\src\SMSReceive.java:133: inconvertible types
    found : byte[]
    required: int
    int intData = (int)data & 0xFF;
    ^
    3 errors
    com.sun.kvem.ktools.ExecutionException
    Build failed

    ReplyDelete
  2. Take the SMSSender.java from http://j2me-codes.blogspot.com/2008/02/j2me-sms-sending-sms-in-j2me.html
    and put it in same folder where SMSReceive.java is. And try compiling it.

    ReplyDelete
  3. cannot run...
    Got two errors

    C:\Documents and Settings\softland\My Documents\NetBeansProjects\MobileApplication15\src\SMSReceive.java:133: inconvertible types
    found : byte[]
    required: int
    int intData = (int)data & 0xFF;

    C:\Documents and Settings\softland\My Documents\NetBeansProjects\MobileApplication15\src\SMSReceive.java:184: cannot find symbol
    symbol : variable DISMISS_COMMAND
    location: class javax.microedition.lcdui.Alert
    if (c == exitCommand || c == Alert.DISMISS_COMMAND) {
    2 errors

    ReplyDelete
  4. Hi,

    Its very good example.But I am getting some couple of errors.If anybody know solutions for following errors,Send solutions.

    Error:1.SMSSender cannot be resolved to a type(code:SMSSender sender;)

    For this error solution already available:
    -----------------------------------
    Tabrez said...

    Take the SMSSender.java from http://j2me-codes.blogspot.com/2008/02/j2me-sms-sending-sms-in-j2me.html
    and put it in same folder where SMSReceive.java is. And try compiling it.
    ----------------------------------
    I done this one But still I am getting this error.

    Error-2:-Cannot cast from byte[] to int

    already adu posted this error.But solution not there.

    if anybody knows,please give solutions asap.

    Thanking you.

    ReplyDelete
  5. In the above code,SMSSender object is available.But that calss sourcecode not available.Due to this reason I am getting errors.Can you provide any solution for this.

    ReplyDelete
  6. instead of int intData = (int)data & 0xFF

    use

    int intData = (int)data[i] & 0xFF

    ReplyDelete
  7. Hi,


    What is the default port on which default listener listens? Is there any way by which I can monitor all SMS coming on default port, I just want to filter some special messages.

    Thanks,
    Gaurav Gupta
    1989.gaurav@gmail.com

    ReplyDelete
  8. Hi,

    Where is the SMSSender Class ?? this file contains only MIDlet file.. From the above comments i had also copied SendSMS file in to src folder but again SendSMS is another MIDlet.. it can't act as class file.

    (For ex: SendSMS has constructor with no arguments but Original SMSSender Class file need to have arguments as smsPort, display, content, sendingMessageAlert and it also need to implement promptAndSend method)

    These things are not done in SendSMS file...

    pls post the SMSSender Class file..

    Thanks for u'r efforts to post such nice articles.

    ReplyDelete
  9. WHT IS THE DEFAULT PORT

    ReplyDelete
  10. C:\Documents and Settings\Amshalekha\My Documents\JavaMESDKProjects\MobileApplication1\src\project\SMSReceive.java:69: cannot find symbol
    symbol : constructor SendSMS(java.lang.String,javax.microedition.lcdui.Display,javax.microedition.lcdui.Alert,javax.microedition.lcdui.Alert)
    location: class project.SendSMS
    sender = new SendSMS(smsPort, display, content, sendingMessageAlert);
    C:\Documents and Settings\Amshalekha\My Documents\JavaMESDKProjects\MobileApplication1\src\project\SMSReceive.java:208: cannot find symbol
    symbol : method promptAndSend(java.lang.String)
    location: class project.SendSMS
    sender.promptAndSend(senderAddress);
    2 errors

    error1:
    Constructor arguments donot macth

    error2: promptAndSend method is not defined anywher

    can anyone pl tell me the solution
    Thankyou

    ReplyDelete
  11. This is a demo available in WTK

    ReplyDelete
  12. i'm new in j2me pls i do i begin well

    ReplyDelete
  13. The worst feeling you will ever feel is sitting next to the person who means the everything to you and knowing that you mean nothing to them.
    Love sms
    Love text

    ReplyDelete

 

Design by Blogger Buster | Distributed by Blogging Tips