• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to handle SMS in J2ME

 
Prasanth Duggirala
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Friends,

I have to know how to read a new SMS in my mobile using a small app using midlets.

How we can do? Can any one help me by giving any example.

thanks
 
Prasanth Duggirala
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

What i found in site.

please make use of it.

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package com.sms.java;

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

// A WMA test application that opens a server
// connection on the specified port and waits
// for text messages to arrive. It then sends
// the reversed text message back to the client.

public class TestWMA extends MIDlet implements CommandListener,MessageReceiver,Runnable {

// The application data
private Display display;
private String port = "5000";
private Form setupForm;
private TextField portTF;
private Form statusForm;
private MessageConnection currentConn;
private MessageReceiverListener messageListener;

// Our commands
public static final Command exitCommand =
new Command( "Exit",
Command.EXIT, 1 );

public static final Command okCommand =
new Command( "OK",
Command.OK, 1 );

public static final Command resetCommand =
new Command( "Reset",
Command.SCREEN, 1 );
private String msgReceived;

public TestWMA(){
}

// Adds a message to the status form.
public void addStatus( String msg ){
statusForm.append( msg );
}

// Handles the screen events.
public void commandAction( Command c,
Displayable d ){
if( c == exitCommand ){
exitMIDlet();
} else if( c == okCommand ){
port = portTF.getString();
new Thread( this ).start();
} else if( c == resetCommand ){
closeConnection();
getDisplay().setCurrent( setupForm );
}
}

// Clears the status form.
private void clearStatus(){
int s;

while( ( s = statusForm.size() ) > 0 ){
statusForm.delete( s-1 );
}

addStatus( "Waiting..."+port );
}

// Closes the current server connection, if any.
private void closeConnection(){
if( currentConn != null ){
try {
currentConn.close();
}
catch( IOException e ){
}

currentConn = null;
}
}

// Called by system to destroy the MIDlet.
protected void destroyApp( boolean unconditional )
throws MIDletStateChangeException {
exitMIDlet();
}

// General cleanup.
public void exitMIDlet(){
if( messageListener != null ){
messageListener.stop();
messageListener = null;
}

closeConnection();
notifyDestroyed();
}

// Returns the MIDlet's display object.
public Display getDisplay(){ return display; }

// Handles errors simply using an alert to
// display the exception.
private void handleError( Throwable e, Displayable next ){
Alert a = new Alert( "Exception",
e.toString(),
null,
AlertType.ERROR );
a.setTimeout( Alert.FOREVER );
getDisplay().setCurrent( a, next );
}

// Initializes the MIDlet by creating the two forms
// as well as the message listener.
protected void initMIDlet(){
messageListener = new MessageReceiverListener( this );

setupForm = new Form( "Receiver Setup" );
setupForm.addCommand( exitCommand );
setupForm.addCommand( okCommand );
setupForm.setCommandListener( this );

portTF = new TextField( "Port number:", port,5, TextField.NUMERIC );

setupForm.append( portTF );

statusForm = new Form( "Status" );
statusForm.addCommand( resetCommand );
statusForm.addCommand( exitCommand );
statusForm.setCommandListener( this );

getDisplay().setCurrent( setupForm );
}

// Implements the MessageReceiver interface. Called
// when an error occurs while receiving a message.
public void messageError(MessageConnection conn, Throwable excep){
handleError( excep, statusForm );
}

// Implements the MessageReceiver interface. Called
// when a message has been successfully received.
public void messageReceived(MessageConnection conn,Message msg){
//statusForm.append("messageReceived Entered");
byte[] data= new byte[1000];
MessagePart[] part;
if( messageListener == null ) return;

if( conn != currentConn ) return;

if(msg instanceof MultipartMessage){
MultipartMessage mmsg = (MultipartMessage)msg;
part = mmsg.getMessageParts();
//Handle the getMessageParts message...
msgReceived = part.toString();
addStatus("Multipart : "+ msgReceived);
return;
}
else if( msg instanceof BinaryMessage ){
BinaryMessage bmsg = (BinaryMessage)msg;
data = bmsg.getPayloadData();
addStatus(" Len : "+ data.length);
//Handle the binary message...
msgReceived = data.toString();
addStatus("Binary : "+ msgReceived);

return;
}
String text1 = new String();
TextMessage tmsg = (TextMessage) msg;
text1 = tmsg.getPayloadText();
String addr = tmsg.getAddress();
addStatus( "Text : " + text1);
addStatus(" Length : "+ text1.length());
//Convert to Hex
String g = "";
for(int i=0;i<text1.length();i++){
int keyInt = text1.charAt(i);
g = g+Integer.toString(keyInt,16);
}
//System.out.println(g.toUpperCase());
addStatus(" Con : "+ g.toUpperCase());

if( addr == null ){
addStatus( "No return address, ignoring" );
return;
}
}

// Called by the system to pause the MIDlet.
protected void pauseApp(){
}

// Creates the server connection. This needs to run in
// a separate thread to avoid blocking the user interface,
// since the device may prompt the user to confirm
// that the application has permission to use wireless
// connectivity.
public void run(){
closeConnection();

String url = "sms://:" + port;

try {
// Create the connection and register it with
// the message listener.
currentConn = (MessageConnection)
Connector.open( url );
currentConn.setMessageListener( messageListener );

// Move to the status form.
getDisplay().setCurrent( statusForm );
clearStatus();
}
catch( IOException e ){
handleError( e, setupForm );
}
}

// Called by the system to activate the MIDlet.
protected void startApp()
throws MIDletStateChangeException {
if( display == null ){
display = Display.getDisplay( this );
initMIDlet();
}
}
}

-------------

package com.sms.java;


import javax.wireless.messaging.*;

// MIDlets or other classes interested in receiving messages
// should implement this interface.

public interface MessageReceiver {
void messageReceived( MessageConnection conn, Message msg );
void messageError( MessageConnection conn, Throwable excep );
}

------------------

package com.sms.java;


import javax.wireless.messaging.*;
// A message listener that spawns a new thread every
// time a message arrives, receives the message on
// that thread, and then forwards the message (or any
// exception) to a waiting message receiver.

public class MessageReceiverListener implements MessageListener {

private boolean stop;
private Class factory;
private MessageReceiver singleton;

// When created with this constructor, the listener
// forwards all messages to the single instance of
// the given receiver.
public MessageReceiverListener( MessageReceiver singleton ){
this.singleton = singleton;
}

// When created with this constructor, the listener
// first creates a new instance of the given class,
// which must implement MessageReceiver. The message
// is then forwarded to that new instance.
public MessageReceiverListener( Class factory ){
this.factory = factory;
}

// Called whenever a message arrives for the given
// connection. Starts a thread to receive and forward
// the message.
public void notifyIncomingMessage( MessageConnection conn ){
if( !stop ){
new Runner( conn ).start();
}
}

// Stops the processing of messages.
public void stop(){
stop = true;
}

// Helper class: when started, receives a message
// and forwards it to the ultimate message receiver.
private class Runner extends Thread {
private MessageConnection connection;

Runner( MessageConnection connection ){
this.connection = connection;
}

public void run(){
Message message = null;
Throwable exception = null;

try {
message = connection.receive();
}
catch( Throwable e ){
exception = e;
}

MessageReceiver recv = singleton;
if( recv == null ){
try {
recv = (MessageReceiver) factory.newInstance();
}
catch( Exception e ){
}
}

if( message != null ){
recv.messageReceived( connection, message );
} else {
recv.messageError( connection, exception );
}
}
}
}
------------------------------------
 
shoaib khan
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
[quote=Prasanth Duggirala]Hi All,

What i found in site.

please make use of it.

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package com.sms.java;

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

// A WMA test application that opens a server
// connection on the specified port and waits
// for text messages to arrive. It then sends
// the reversed text message back to the client.

public class TestWMA extends MIDlet implements CommandListener,MessageReceiver,Runnable {

// The application data
private Display display;
private String port = "5000";
private Form setupForm;
private TextField portTF;
private Form statusForm;
private MessageConnection currentConn;
private MessageReceiverListener messageListener;

// Our commands
public static final Command exitCommand =
new Command( "Exit",
Command.EXIT, 1 );

public static final Command okCommand =
new Command( "OK",
Command.OK, 1 );

public static final Command resetCommand =
new Command( "Reset",
Command.SCREEN, 1 );
private String msgReceived;

public TestWMA(){
}

// Adds a message to the status form.
public void addStatus( String msg ){
statusForm.append( msg );
}

// Handles the screen events.
public void commandAction( Command c,
Displayable d ){
if( c == exitCommand ){
exitMIDlet();
} else if( c == okCommand ){
port = portTF.getString();
new Thread( this ).start();
} else if( c == resetCommand ){
closeConnection();
getDisplay().setCurrent( setupForm );
}
}

// Clears the status form.
private void clearStatus(){
int s;

while( ( s = statusForm.size() ) > 0 ){
statusForm.delete( s-1 );
}

addStatus( "Waiting..."+port );
}

// Closes the current server connection, if any.
private void closeConnection(){
if( currentConn != null ){
try {
currentConn.close();
}
catch( IOException e ){
}

currentConn = null;
}
}

// Called by system to destroy the MIDlet.
protected void destroyApp( boolean unconditional )
throws MIDletStateChangeException {
exitMIDlet();
}

// General cleanup.
public void exitMIDlet(){
if( messageListener != null ){
messageListener.stop();
messageListener = null;
}

closeConnection();
notifyDestroyed();
}

// Returns the MIDlet's display object.
public Display getDisplay(){ return display; }

// Handles errors simply using an alert to
// display the exception.
private void handleError( Throwable e, Displayable next ){
Alert a = new Alert( "Exception",
e.toString(),
null,
AlertType.ERROR );
a.setTimeout( Alert.FOREVER );
getDisplay().setCurrent( a, next );
}

// Initializes the MIDlet by creating the two forms
// as well as the message listener.
protected void initMIDlet(){
messageListener = new MessageReceiverListener( this );

setupForm = new Form( "Receiver Setup" );
setupForm.addCommand( exitCommand );
setupForm.addCommand( okCommand );
setupForm.setCommandListener( this );

portTF = new TextField( "Port number:", port,5, TextField.NUMERIC );

setupForm.append( portTF );

statusForm = new Form( "Status" );
statusForm.addCommand( resetCommand );
statusForm.addCommand( exitCommand );
statusForm.setCommandListener( this );

getDisplay().setCurrent( setupForm );
}

// Implements the MessageReceiver interface. Called
// when an error occurs while receiving a message.
public void messageError(MessageConnection conn, Throwable excep){
handleError( excep, statusForm );
}

// Implements the MessageReceiver interface. Called
// when a message has been successfully received.
public void messageReceived(MessageConnection conn,Message msg){
//statusForm.append("messageReceived Entered");
byte[] data= new byte[1000];
MessagePart[] part;
if( messageListener == null ) return;

if( conn != currentConn ) return;

if(msg instanceof MultipartMessage){
MultipartMessage mmsg = (MultipartMessage)msg;
part = mmsg.getMessageParts();
//Handle the getMessageParts message...
msgReceived = part.toString();
addStatus("Multipart : "+ msgReceived);
return;
}
else if( msg instanceof BinaryMessage ){
BinaryMessage bmsg = (BinaryMessage)msg;
data = bmsg.getPayloadData();
addStatus(" Len : "+ data.length);
//Handle the binary message...
msgReceived = data.toString();
addStatus("Binary : "+ msgReceived);

return;
}
String text1 = new String();
TextMessage tmsg = (TextMessage) msg;
text1 = tmsg.getPayloadText();
String addr = tmsg.getAddress();
addStatus( "Text : " + text1);
addStatus(" Length : "+ text1.length());
//Convert to Hex
String g = "";
for(int i=0;i<text1.length();i++){
int keyInt = text1.charAt(i);
g = g+Integer.toString(keyInt,16);
}
//System.out.println(g.toUpperCase());
addStatus(" Con : "+ g.toUpperCase());

if( addr == null ){
addStatus( "No return address, ignoring" );
return;
}
}

// Called by the system to pause the MIDlet.
protected void pauseApp(){
}

// Creates the server connection. This needs to run in
// a separate thread to avoid blocking the user interface,
// since the device may prompt the user to confirm
// that the application has permission to use wireless
// connectivity.
public void run(){
closeConnection();

String url = "sms://:" + port;

try {
// Create the connection and register it with
// the message listener.
currentConn = (MessageConnection)
Connector.open( url );
currentConn.setMessageListener( messageListener );

// Move to the status form.
getDisplay().setCurrent( statusForm );
clearStatus();
}
catch( IOException e ){
handleError( e, setupForm );
}
}

// Called by the system to activate the MIDlet.
protected void startApp()
throws MIDletStateChangeException {
if( display == null ){
display = Display.getDisplay( this );
initMIDlet();
}
}
}

-------------

package com.sms.java;


import javax.wireless.messaging.*;

// MIDlets or other classes interested in receiving messages
// should implement this interface.

public interface MessageReceiver {
void messageReceived( MessageConnection conn, Message msg );
void messageError( MessageConnection conn, Throwable excep );
}

------------------

package com.sms.java;


import javax.wireless.messaging.*;
// A message listener that spawns a new thread every
// time a message arrives, receives the message on
// that thread, and then forwards the message (or any
// exception) to a waiting message receiver.

public class MessageReceiverListener implements MessageListener {

private boolean stop;
private Class factory;
private MessageReceiver singleton;

// When created with this constructor, the listener
// forwards all messages to the single instance of
// the given receiver.
public MessageReceiverListener( MessageReceiver singleton ){
this.singleton = singleton;
}

// When created with this constructor, the listener
// first creates a new instance of the given class,
// which must implement MessageReceiver. The message
// is then forwarded to that new instance.
public MessageReceiverListener( Class factory ){
this.factory = factory;
}

// Called whenever a message arrives for the given
// connection. Starts a thread to receive and forward
// the message.
public void notifyIncomingMessage( MessageConnection conn ){
if( !stop ){
new Runner( conn ).start();
}
}

// Stops the processing of messages.
public void stop(){
stop = true;
}

// Helper class: when started, receives a message
// and forwards it to the ultimate message receiver.
private class Runner extends Thread {
private MessageConnection connection;

Runner( MessageConnection connection ){
this.connection = connection;
}

public void run(){
Message message = null;
Throwable exception = null;

try {
message = connection.receive();
}
catch( Throwable e ){
exception = e;
}

MessageReceiver recv = singleton;
if( recv == null ){
try {
recv = (MessageReceiver) factory.newInstance();
}
catch( Exception e ){
}
}

if( message != null ){
recv.messageReceived( connection, message );
} else {
recv.messageError( connection, exception );
}
}
}
}
------------------------------------
HEY I WANT TO KNOW HOW TO RUN THIS CODE......... please its urgent,,,,,,,,,........
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic