J2ME短信收到没有响应

时间:2012-01-25 04:18:48

标签: java-me wma

当我尝试在j2me中接收短信时,这段代码什么也没做。当从startApp()启动应用程序时,将启动一个新线程,该线程调用run(),开始侦听消息。请看看。

import javax.microedition.io.Connector;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.Display;
import javax.microedition.midlet.*;
import javax.wireless.messaging.BinaryMessage;
import javax.wireless.messaging.Message;
import javax.wireless.messaging.MessageConnection;
import javax.wireless.messaging.MessageListener;
import javax.wireless.messaging.TextMessage;

/**
 *
 */
public class Receiver extends MIDlet implements Runnable {

    Display display;
    Alert showMessage = new Alert("Msg", "Checking inbox..", null, AlertType.INFO);

    public void startApp() {
        Thread t = new Thread();
        t.start();
    }

    public void run() {
        try {
            // Time to receive one.
//get reference to MessageConnection object
            showMessage.setTimeout(Alert.FOREVER);
            display.getDisplay(this).setCurrent(showMessage);
            MessageConnection conn = (MessageConnection) Connector.open("sms://:50001");
//set message listener
            conn.setMessageListener(new MessageListener() {

                public void notifyIncomingMessage(MessageConnection conn) {
                    try {
                        Message msg = conn.receive();
                        //do whatever you want with the message
                        if (msg instanceof TextMessage) {
                            TextMessage tmsg = (TextMessage) msg;
                            String s = tmsg.getPayloadText();
                            System.out.println(s);
                            //showMessage.setTimeout(Alert.FOREVER);
                            showMessage.setString(s);
                            showMessage.setTitle("Welcome");
                            display.setCurrent(showMessage);

                        } else if (msg instanceof BinaryMessage) {
                            System.out.println("inside else if");
                        } else {
                            System.out.println("inside else");
                        }
                    } catch (Exception e) {
                    }
                }
            });
        } catch (Exception e) {
        }
    }

    public void pauseApp() {
    }

    public void destroyApp(boolean unconditional) {
    }
}

2 个答案:

答案 0 :(得分:3)

在此博客中查看Send & Receiving SMS on specific Port with J2ME Application

它会帮助你解决这个问题。 感谢

答案 1 :(得分:2)

Thread t = new Thread();
t.start();

您需要了解Java中的线程。

目前,您正在开始一个没有的新主题。

请参阅the Javadoc for the empty Thread constructor:

  

以这种方式创建的线程必须覆盖其run()方法才能实际执行任何操作。

您的MIDlet实现了Runnable,因此您需要将其传递给线程。 试试这个:

new Thread(this).start();