⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 smsthread.java

📁 这是书中的一个程序
💻 JAVA
字号:
/*
 * SMSThread.java
 *
 * Created on 2005年3月15日, 下午8:13
 */

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;

import javax.microedition.io.*;
import javax.wireless.messaging.*;
import java.io.IOException;

/**
 *
 * @author  Liu Bin
 * @version
 */
public class SMSThread extends MIDlet
        implements CommandListener, MessageListener {
    
    /** 退出命令按钮 */
    private Command cmdExit;
    /** 发送消息的命令按钮 */
    private Command cmdSendMsg;
    
    //Display管理
    private Display display;
    private Form form;
    /** 消息内容 */
    private TextField tfMsgText;
    /** 用于输发送到的电话号码 */
    private TextField tfPhoneNumber;
    
    /** 用于接收消息 */
    private MessageConnection mcon;
    /** 完成标志 */
    boolean done;
    Reader reader;
    
    
    public SMSThread() {
        display = Display.getDisplay(this);
        cmdExit = new Command("退出程序", Command.EXIT, 1);
        cmdSendMsg = new Command("发送消息", Command.SCREEN, 2);
        
        tfMsgText = new TextField("请输入消息内容:", "", 255, TextField.ANY);
        tfPhoneNumber = new TextField("请输入接收号码:", "", 255,
                TextField.PHONENUMBER);
    }
    
    /**
     * 开始运行MIDlet
     */
    public void startApp() {
        try {
            mcon = (MessageConnection)Connector.open
                    ("sms://:5008");
            // Register the listener for inbound messages.
            mcon.setMessageListener(this);
            
            done = false;
            reader = new Reader();
            new Thread(reader).start();
        } catch (IOException ioe) {
            System.out.println("不能进行接收消息连接:" + ioe.toString());
        }
        
        
        form = new Form("接收/发送消息演示 - 接收端口为5008");
        form.append(tfMsgText);
        form.append(tfPhoneNumber);
        
        form.addCommand(cmdExit);
        form.addCommand(cmdSendMsg);
        form.setCommandListener(this);
        display.setCurrent(form);
        
    }
    
    
    public void pauseApp() {
        done = true;
        try {
            mcon.close();
        } catch (IOException e) {
            // Handle errors
        }
    }
    
    public void destroyApp(boolean unconditional) {
        done = true;
        try {
            mcon.setMessageListener(null);
            mcon.close();
        } catch (IOException e) {
            // Handle shutdown errors.
        }
        
        notifyDestroyed();
    }
    
    
    
    /**
     * 处理命令按钮事件
     */
    public void commandAction(Command c, Displayable s) {
        if (c == cmdExit) {
            destroyApp(false);
        } else if (c == cmdSendMsg) {
            //检查电话号码是否存在
            String pn = tfPhoneNumber.getString();
            if (pn.equals("")) { //注意如果使用pn==""会不起作用
                Alert alert = new Alert("发送消息错误",
                        "请输入接收的电话号码", null,
                        AlertType.ERROR);
                alert.setTimeout(2000);
                display.setCurrent(alert, form);
                AlertType.ERROR.playSound(display);
            } else {
                try {
                    send(tfMsgText.getString(), pn);
                } catch (Exception exc) {
                    exc.printStackTrace();
                }
            }
        }
    }
    
    
    /**
     * 给指定号码发送短信息
     * <p>
     * @param content 短信息内容
     * @param phoneNumber 手机号码
     * <p>
     * @return 发送成功返回true,否则返回false
     */
    public boolean send(String content,String phoneNumber){
        //返回值
        boolean result = true;
        try{
            //地址
            String address = "sms://+" + phoneNumber;
            //建立连接
            MessageConnection conn=(MessageConnection)Connector.open(address);   
         
            //设置短信息类型为文本
            TextMessage msg = (TextMessage)conn.newMessage(
                    MessageConnection.TEXT_MESSAGE);
            //设置消息地址
            msg.setAddress(address);
            //设置信息内容
            msg.setPayloadText(content);
            //发送消息
            conn.send(msg);
        }catch(Exception e){
            result = false;
            System.out.println("发送短消息错误:" + e.toString());
        }
        return result;
    }
    
    /**
     * 非同步调用,当有消息到达时执行该方法
     */
    public void notifyIncomingMessage(MessageConnection mc) {
        if (mc == mcon) {
            reader.handleMessage();
        }
    }
    
    /**
     * 用于读取短信的独立线程
     */
    class Reader implements Runnable {
        private int pendingMessages = 0;
        
        /**
         * 执行实际的读取短信的操作
         */
        public void run() {
            Message msg=null;
            
            while (!done) {
                synchronized(this) {
                    if (pendingMessages == 0) {
                        try {
                            wait();
                        } catch (Exception e) {
                            System.out.println("线程等待时出现异常:" +
                                    e.toString());
                        }
                    }
                    pendingMessages--;
                }
                
                try {
                    msg = mcon.receive();
                } catch (IOException ioe) {
                    //处理读取消息时发生的错误
                    System.out.println("读取消息时发生异常:" +
                            ioe.toString());
                }
                //处理读取的文本消息
                if ((msg != null) && (msg instanceof TextMessage)) {
                    TextMessage tmsg = (TextMessage)msg;
                    form.append("接收到一条消息,接收时间:" +
                            tmsg.getTimestamp().toString() + "\n");
                    form.append("消息发送方:" + tmsg.getAddress() + "\n");
                    form.append("消息内容:" + tmsg.getPayloadText());
                }
            }
        }
        
        public synchronized void handleMessage() {
            pendingMessages++;
            notify();
        }
        
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -