не могу получить смс, помогите исправить код - PullRequest
2 голосов
/ 01 марта 2012

Я не знаю, в чем проблема, но SMS не получено с кодом ниже, и когда я вижу в памяти телефона, приложение недействительно.

Может кто-нибудь исправить этот код?
IУ меня много проблем с этим, он хорошо компилируется, но когда он работает на реальном телефоне, приложение говорит, что оно недействительно, Nokia 2630 поддерживает MIDP 2.0 , поэтому не проблема с телефоном.

package Pushtest;

import javax.microedition.midlet.*;
import com.sun.lwuit.*;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.events.ActionListener;
import com.sun.lwuit.layouts.GridLayout;
import javax.microedition.io.*;
import javax.wireless.messaging.*;
import java.util.Date;
import java.io.*;

/**
* @author test
*/
public class SendApprooval extends MIDlet implements Runnable, ActionListener, MessageListener {

  Date todaydate;

  private Dialog content, alert;
  Thread thread;
  String[] connections;
  boolean done;
  String senderAddress, mess;
  MessageConnection smsconn = null, clientConn = null;
  Message msg;

 // public SendApprooval() {
/*       
        smsPort = getAppProperty("SMS-Port");
        content = new Dialog("");
        content.addComponent(new Label("Waiting for Authentication Request"));
        content.setDialogType(Dialog.TYPE_INFO);
        content.setTimeout(2000);
     //   exitCommand = new Command("Exit", Command.EXIT, 2);
     //  content.addCommand(exitCommand)
        content.addCommand(exitCommand);
        content.addCommandListener(this);
        content.show(); 
        }  */

        public void startApp() {

         Display.init(this);

        String smsConnection = "sms://:" + 5000;
        if (smsconn == null) {
              try {
                    smsconn = (MessageConnection) Connector.open(smsConnection);
                    smsconn.setMessageListener(this);
              } catch (IOException ioe) {
                    ioe.printStackTrace();
              }
        }
        connections = PushRegistry.listConnections(true);
        if ((connections == null) || (connections.length == 0)) {
              content.addComponent(new Label("Waiting for Authentication Request"));
        }
        done = false;
        thread = new Thread(this);
        thread.start();
  //      display.setCurrent(resumeScreen);

  }

  public void run() {
        try {
              msg = smsconn.receive();
              if (msg != null) {
                    senderAddress = msg.getAddress();
                    int k, j = 0;
                    for (k = 0; k <= senderAddress.length() - 1; k++) {
                          if (senderAddress.charAt(k) == ':') {
                                j++;
                                if (j == 2) {
                                      break;
                                }
                          }
                    }
                    senderAddress = senderAddress.substring(0, k + 1);
                    content.addComponent(new Label(senderAddress));
                    senderAddress = senderAddress + 5000;
                    if (msg instanceof TextMessage) {
                          mess = ((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[i] & 0xFF;
                                if (intData < 0x10) {
                                      buf.append("0");
                                }
                                buf.append(Integer.toHexString(intData));
                                buf.append(' ');
                          }
                          mess = buf.toString();
                    }
                    if (mess.equals("Give me Rights")) {
                          try {
                                clientConn = (MessageConnection) Connector.open(senderAddress);
                          }catch (Exception e) {
                                alert = new Dialog("Alert");
                                alert.setLayout(new GridLayout(5, 1));
                                alert.addComponent(new Label("Unable to connect to Station because of network problem"));
                                alert.setTimeout(2000);
                                alert.setDialogType(Dialog.TYPE_INFO);
                                Display.init(alert);
                                alert.show();
                          }
                          try {
                                TextMessage textmessage = (TextMessage) clientConn.newMessage(MessageConnection.TEXT_MESSAGE);
                                textmessage.setAddress(senderAddress);
                                textmessage.setPayloadText("Approoved");
                                clientConn.send(textmessage);
                          } catch (Exception e) {
                                Dialog alert = new Dialog("");
                                alert.setLayout(new GridLayout(5, 1));
                                alert.setDialogType(Dialog.TYPE_INFO);
                                alert.setTimeout(2000);
                                alert.addComponent(new Label(e.toString()));
                                Display.init(alert);
                                alert.show();
                          }
                    }
              } else {
              }
        } catch (IOException e) {
              content.addComponent(new Label(e.toString()));
              Display.init(content);
        }
  }

  public void pauseApp() {
        done = true;
        thread = null;
        Display.init(this);
  }

  public void destroyApp(boolean unconditional) {
        done = true;
        thread = null;
        if (smsconn != null) {
              try {
              smsconn.close();
              } catch (IOException e) {
              }
              notifyDestroyed();
        }
  }

  public void showMessage(String message, Display displayable) {
        Dialog alert = new Dialog("");
        alert.setLayout(new GridLayout(5, 1));
        alert.setTitle("Error");
        alert.addComponent(new Label(message));
        alert.setDialogType(Dialog.TYPE_ERROR);
        alert.setTimeout(5000);
        alert.show();
  }


  public void notifyIncomingMessage(MessageConnection conn) {
        if (thread == null) {
              content.addComponent(new Label("Waiting for Authentication Request"));
              content.setLayout(new GridLayout(5, 1));
              content.setDialogType(Dialog.TYPE_INFO);
              content.show();
              done = false;
              thread = new Thread(this);
              thread.start();

        }
  }

public void actionPerformed(ActionEvent ae) {


       System.out.println("Event fired" + ae.getCommand().getCommandName());
    int id = ae.getCommand().getId();
    Command cmd = ae.getCommand();
    String cmdName1 = cmd.getCommandName();
     try {
              msg = smsconn.receive();
              if (msg != null) {
                    senderAddress = msg.getAddress();
                    int k, j = 0;
                    for (k = 0; k <= senderAddress.length() - 1; k++) {
                          if (senderAddress.charAt(k) == ':') {
                                j++;
                                if (j == 2) {
                                      break;
                                }
                          }
                    }
                    senderAddress = senderAddress.substring(0, k + 1);
                    content.addComponent(new Label(senderAddress));
                    senderAddress = senderAddress + 5000;
                    if (msg instanceof TextMessage) {
                          mess = ((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[i] & 0xFF;
                                if (intData < 0x10) {
                                      buf.append("0");
                                }
                                buf.append(Integer.toHexString(intData));
                                buf.append(' ');
                          }
                          mess = buf.toString();
                    }
                    if (mess.equals("Give me Rights")) {
                          try {
                                clientConn = (MessageConnection) Connector.open(senderAddress);
                          }catch (Exception e) {
                                alert = new Dialog("Alert");
                                alert.setLayout(new GridLayout(5, 1));
                                alert.addComponent(new Label("Unable to connect to Station because of network problem"));
                                alert.setTimeout(2000);
                                alert.setDialogType(Dialog.TYPE_INFO);
                                Display.init(alert);
                                alert.show();
                          }
                          try {
                                TextMessage textmessage = (TextMessage) clientConn.newMessage(MessageConnection.TEXT_MESSAGE);
                                textmessage.setAddress(senderAddress);
                                textmessage.setPayloadText("Approoved");
                                clientConn.send(textmessage);
                          } catch (Exception e) {
                                Dialog alert = new Dialog("");
                                alert.setLayout(new GridLayout(5, 1));
                                alert.setDialogType(Dialog.TYPE_INFO);
                                alert.setTimeout(2000);
                                alert.addComponent(new Label(e.toString()));
                                Display.init(alert);
                                alert.show();
                          }
                    }
              } else {
              }
              if (("Exit").equals(cmdName1)) {
              destroyApp(true);
              notifyDestroyed();
              }
        } catch (Exception ex) {
              ex.printStackTrace();
        }
  }
}

Ответы [ 2 ]

1 голос
/ 01 марта 2012

Это может быть вызвано тем, что отправляющее SMS-сообщение может не отправляться на порт, указанный в вашем коде,

Пожалуйста, посмотрите на этот рабочий пример .

0 голосов
/ 01 марта 2012

я нашел это, ребята, спасибо за вашу поддержку, я уверен, что вернусь с дополнительными запросами, я написал пример получения кода смс с портом 5000, это помогло бы кому-нибудь в некотором роде, Прежде чем ты начнешь, Щелкните правой кнопкой мыши ваше приложение в NetBeans и выберите свойства. Теперь выберите дескриптор приложения. выберите вкладку атрибута и нажмите кнопку Добавить. Дайте следующее в соответствующих полях. Имя: SMS-порт Значение: портно Теперь вы успешно зарегистрировали порт.

Теперь снова выберите вкладку push-реестра. укажите следующее в соответствующих полях. Имя класса: имя пакета. Имя класса IP отправителя: * Строка подключения: смс: //: портно Теперь вы успешно зарегистрировали реестр push.

КОД ЗДЕСЬ:

public class SMSReceiver extends MIDlet implements ActionListener, MessageListener {

    private Form formReceiver;
    private TextField tfPort;
        private MessageConnection msgConnection;
    private MessageListener Listener;
    private String port;



    protected void destroyApp(boolean unconditional)
            throws MIDletStateChangeException {

    }

    protected void pauseApp() {

    }

    protected void startApp() {
            Display.init(this);

        try {
            Resources r = Resources.open("/m21.res");

            UIManager.getInstance().setThemeProps(
                    r.getTheme(r.getThemeResourceNames()[0]));
        } catch (java.io.IOException e) {
            e.printStackTrace();
        }
    formReceiver = new Form();
        formReceiver.setTitle(" ");
        formReceiver.setLayout(new GridLayout(4, 2));
        formReceiver.setTransitionInAnimator(null);
        TextField.setReplaceMenuDefault(false);

        Label lblPort = new Label("Port");
        tfPort = new TextField();
        tfPort.setMaxSize(8);
        tfPort.setUseSoftkeys(false);
        tfPort.setHeight(10);
        tfPort.setConstraint(TextField.DECIMAL);
        formReceiver.addComponent(lblPort);
        formReceiver.addComponent(tfPort);
        formReceiver.addCommand(new Command("Listen"), 0);
        formReceiver.addCommand(new Command("Exit"), 0);
        formReceiver.addCommandListener(this);

        formReceiver.show();
    }



    public void notifyIncomingMessage(MessageConnection conn) {
        Message message;
        try {
            message = conn.receive();
            if (message instanceof TextMessage) {
                TextMessage tMessage = (TextMessage)message;
                formReceiver.addComponent(new Label("Message received : "+tMessage.getPayloadText()+"\n"));
            } else {
                formReceiver.addComponent(new Label("Unknown Message received\n"));
            }
        } catch (InterruptedIOException e) {
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public void actionPerformed(ActionEvent ae) {
       System.out.println("Event fired" + ae.getCommand().getCommandName());
        int idi = ae.getCommand().getId();
        Command cmd = ae.getCommand();
        String cmdNam = cmd.getCommandName();
        if ("Listen".equals(cmdNam)) {
              ListenSMS sms = new ListenSMS(tfPort.getSelectCommandText(), this);
            sms.start();
        }
        if ("Exit".equals(cmdNam)) {
              notifyDestroyed();
        }
        }
    }


class ListenSMS extends Thread {
    private MessageConnection msgConnection;
    private MessageListener Listener;
    private String port;

    public ListenSMS(String port, MessageListener listener) {
        this.port = port;
        this.Listener = listener;
    }



    public void run() {
        try {
            msgConnection = (MessageConnection)Connector.open("sms://:" + 5000);
            msgConnection.setMessageListener(Listener);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
...