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

📄 chatbypushmidlet.java

📁 包括及时通讯,音效,菜单显示等等java程序
💻 JAVA
字号:
/*
 * @(#)ChatMIDlet.java
 *
 * Copyright (c) 2003 Qualcomm, Inc. All rights reserved.
 * PROPRIETARY/CONFIDENTIAL
 * Use is subject to license terms
 */

package com.qualcomm.demo.chatbypush;

import java.util.*;
import java.io.*;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.*;

/**
 *  PushMIDlet - a Push sample MIDlet
 */
public class ChatByPushMIDlet
    extends MIDlet implements CommandListener {

//  Default values to use.
String midletClassName  = this.getClass().getName();

//  User Interface related
private Command sendCommand = new Command("Send", Command.ITEM, 1);
private Command exitCmd  = new Command("Exit",Command.EXIT, 4 );
protected Display display;
private Ticker ticker;
private Form form;
private StringItem siStatus = new StringItem("Status:" , " ");
private TextField  tf = new TextField("Send:", "", 30, TextField.ANY);
OutputStream os;
SocketSender scSender = null;
DatagramSender dgSender = null;
private String address;

/** Constructor */
public ChatByPushMIDlet() {
}

/**
 *  Initial state.
 *  @throw MIDletStateChangeException to indicate
 *  a transient error has occured.
 */
public void startApp() throws MIDletStateChangeException {
    try {
        if (display == null) {
            System.out.println("Setting up...");
            display = Display.getDisplay(this);
            //  Create a Ticker and a Form, add commands
            //  to the form to test PushRegistry alarms and
            //  inbound connections, set the Form'scommand
            //  listener, and the Ticker to the Form.
            ticker = new Ticker("");
            form = new Form("ChatByPush");
            //form.addCommand(sendCommand);
            form.addCommand(exitCmd);
            form.append(siStatus);
            form.append(tf);
            form.setCommandListener(this);
            form.setTicker(ticker);
            display.setCurrent(form);

            //  Discover if activation is due to an inbound
            //  connection.
            //if (isPushActivated() == true) {
            if (handlePushActivation() == true) {
                //ticker.setString("Push Activated");
            }
        }
    }
    catch(Exception e) {
        System.out.println("Exception during startApp()");
        e.printStackTrace();
        //  If some kind of transient error ocurrs, throw a
        //  MIDledStateChangeException.
        throw new MIDletStateChangeException("Error Starting...");
    }
}

/** Paused state. Release resources (connection, threads, etc). */
public void pauseApp() {
    display = null;
}

/**
 *  Destroyed state. Release resources (connection,
 *  threads, etc). Also, schedule the future launch
 *  of the MIDlet. @param uc If true when this method
 *  is called, the MIDlet must cleanup and release all
 *  resources. If false the MIDlet may throw @throw
 *  MIDletStateChangeException  to indicate it does not
 *  want to be destroyed at this time.
 */
public void destroyApp(boolean uc) throws
    MIDletStateChangeException {
    display = null;
}

/**
 *  Command/button listener.
 *  @param c the LCDUI Command to process.
 *  @param d the Displayable source of the Command.
 */
public void commandAction(Command c, Displayable d) {
  if (c == sendCommand) {
    if (scSender != null) // socket
      scSender.send(tf.getString());
    else if (dgSender != null) // datagram
    {
      System.out.println("datagram send: address="+address+" msg=" + tf.getString());
      dgSender.send(address, tf.getString());
    }
    else
      System.out.println("Error: Sender not initialized!");
  }
  else  if (c == exitCmd) {
      try
      {
        destroyApp(true);
        notifyDestroyed();
      }
      catch (Exception e)
      {
        e.printStackTrace();
      }
    }
} // commandAction()

/**
 *  Determine if activated due to inbound connection
 *  and if so dispatch a PushProcessor to handle incoming
 *  connection(s). @return true if MIDlet was activated
 *  due to inbound connection, false otherwise
 */
private boolean handlePushActivation() {
    //  Discover if there are pending push
    //  inbound connections and if so, dispatch
    //  a PushProcessor for each one.
    String[] connections =
        PushRegistry.listConnections(true);
    if (connections != null && connections.length > 0) {
        System.out.println("is PushActivated");
        for (int i=0; i < connections.length; i++) {
            PushProcessor pp = new PushProcessor(connections[i]);
            //System.out.println("Connection:" + connections[i]);
            if (connections[i].startsWith("socket://"))
            {
              ticker.setString("Push Activated by Socket");
            }
            else
            {
              ticker.setString("Push Activated by Datagram");
            }

            // TO DO, ADD TO LIST TO REMEMBER TO SHUTDOWN PROCESSOR UPON EXIT
        }
        return(true);
    }
    return(false);
}



/**
 *  PushProcessor - Thread of execution responsible of
 *  receiving and processing push events.
 */
class PushProcessor implements Runnable {

    Thread th = new Thread(this);
    String url;
    boolean done = false;
    String midletClassName;

    /** Constructor */
    public PushProcessor(String url) {
    System.out.println("PushProcessor(" + url + ")");
        this.url = url;
        th.start();
    }

    public void notifyDone() {
        done = true;
    }

    /**
         *  Thread's run method to wait for and process
         *  received messages.
         */
    public void run() {
        ServerSocketConnection ssc = null;
        SocketConnection sc = null;
        DatagramConnection dc = null;
        Datagram dg = null;
        InputStream is = null;
        form.addCommand(sendCommand);
        try {
            while(!done)
            {
                if (url.startsWith("socket://"))
                {
                    //  "Open" connection.
                    //ticker.setString("Push activated by socket");
                    ssc = (ServerSocketConnection)Connector.open(url);
                    //  Wait for (and accept) inbound connection.
                    sc = (SocketConnection) ssc.acceptAndOpen();
                    is  = sc.openDataInputStream();
                    os = sc.openOutputStream();
                    scSender = new SocketSender(os);
                    while (true)
                    {
                      StringBuffer sb = new StringBuffer();
                      int c = 0;
                      while (((c = is.read()) != '\n') && (c != -1))
                      {
                        sb.append((char) c);
                      }
                      siStatus.setText("Received - " + sb.toString());
                      //ticker.setString("Received - " + sb.toString());
                    }
                }
                else if (url.startsWith("datagram://"))
                {
                  // Open the connection.
                  //ticker.setString("Push activated by datagram");
                  dc = (DatagramConnection)Connector.open(url);
                  dgSender = new DatagramSender(dc);
                  while (true)
                  {
                    dg = dc.newDatagram(100);
                    dc.receive(dg);
                    //address = dg.getAddress();
                    if (dg.getLength() > 0)
                    {
                      String msg = new String(dg.getData(), 0, dg.getLength());
                      siStatus.setText("Received - " + msg);
                      //ticker.setString("Received - " + msg);
                    }
                  }
                }
            }
        }
        catch (IOException e) {
            System.out.println("PushProcessor.runException" + e);
            e.printStackTrace();
        }
        finally {
            try {
                if (is != null) is.close();
                if (sc != null) sc.close();
                if (ssc != null) ssc.close();
                if (dc != null) dc.close();
            }
            catch(Exception e) {
            }
        }
    }

} //  PushProcessor

} //  ChatByPushMIDlet

⌨️ 快捷键说明

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