J2ME Game Optimization Secrets (part 5)

Other Techniques One technique I was unable to include in my example code was the optimal use of a switch() statement. Switches are very commonly used to implement Finite State Machines, which are used in game Artificial Intelligence code to control the behavior of non-player actors. When you use a switch, it is good programming […]

Developing Applications with the Java APIs for Bluetooth (JSR-82)

Developing Applications with the Java APIs for Bluetooth (JSR-82) This paper covers the Java API for Bluetooth (JSR-82) with respect to Sony Ericsson devices. It starts by introducing the Bluetooth technology, followed by the Java APIs for Bluetooth, and how to use them. Currently, these APIs are currently available in the Sony Ericsson P900/P908 handsets. […]

Multi-Player MIDP Game Programming

Multi-Player MIDP Game Programming This tutorial explains how to write multi-player games for MIDP phones. It describes the technologies that are available to support multi-player games, and shows what kinds of games are possible with these technologies. Click here to view “Multi-Player MIDP Game Programming”

j2me:Socket connection

/*J2ME: The Complete ReferenceJames KeoghPublisher: McGraw-HillISBN 0072227109*/// jad file (Please verify the jar size first)/*MIDlet-Name: socketconnectionMIDlet-Version: 1.0MIDlet-Vendor: MyCompanyMIDlet-Jar-URL: socketconnection.jarMIDlet-1: socketconnection, , socketconnectionMicroEdition-Configuration: CLDC-1.0MicroEdition-Profile: MIDP-1.0MIDlet-JAR-SIZE: 100*/import javax.microedition.midlet.*;import javax.microedition.lcdui.*;import java.io.*;import javax.microedition.io.*;public class socketconnection extends MIDlet implements CommandListener {  private Command exit, start;  private Display display;  private Form form;  public socketconnection ()   {    display = Display.getDisplay(this);    exit = new Command(“Exit”, Command.EXIT, 1);    start = new Command(“Start”, Command.EXIT, 1);    form = new Form(“Read Write Socket”);    form.addCommand(exit);    form.addCommand(start);    form.setCommandListener(this);  }  public void startApp() throws MIDletStateChangeException   {    display.setCurrent(form);  }  public void pauseApp()   {  }  public void destroyApp(boolean unconditional)   {  }  public void commandAction(Command command, Displayable displayable)   {    if (command == exit)     {      destroyApp(false);      notifyDestroyed();    }    else if (command == start)     {      try       {       StreamConnection connection = (StreamConnection) Connector.open(“socket://www.myserver.com:80”);       PrintStream output =          new PrintStream(connection.openOutputStream() );       output.println( “GET /my.html HTTP/0.9\n\n” );       output.flush();       InputStream in = connection.openInputStream();       int ch;       while( ( ch = in.read() ) != –1 )      {         System.out.print( (char) ch );       }       in.close();       output.close();       connection.close();     }      catch( ConnectionNotFoundException error )       {         Alert alert = new Alert(            “Error”, “Cannot access socket.”, null, null);         alert.setTimeout(Alert.FOREVER);         alert.setType(AlertType.ERROR);         display.setCurrent(alert);              }        catch( IOException error )        {         Alert alert = new Alert(“Error”, error.toString(), null, null);         alert.setTimeout(Alert.FOREVER);         alert.setType(AlertType.ERROR);         display.setCurrent(alert);        }    }  }}

Demonstrates the functionality of DatagramConnection framework.

/*** Chapter 5 Sample Code for Datagram functionality ***/import javax.microedition.midlet.*;import javax.microedition.lcdui.*;import javax.microedition.io.*;import java.util.*;public class DatagramTest extends MIDlet {  // Port 9001 is used for datagram communication    static final int receiveport  = 9001;  Receive receiveThread = new Receive();    public DatagramTest() {  }    public void startApp() {        // Start the listening thread        receiveThread.start();        // Send message Hello World!        sendMessage(“Hello World!”);    }    public void pauseApp() {    }    public void destroyApp(boolean unconditional)  {    }  // This function sends a datagram message on port 9001.    void sendMessage(String msg)  {    String destAddr = “datagram://localhost:” + receiveport;        DatagramConnection dc = null;    Datagram dgram;    byte[] bMsg = msg.getBytes();    try {           dc = (DatagramConnection)Connector.open(destAddr);      // Create a datagram socket and send            dgram= dc.newDatagram(bMsg,bMsg.length,destAddr);            dc.send(dgram);      System.out.println(“Sending Packet:” +  msg);            dc.close();        }        catch (Exception e)  {            System.out.println(“Exception Connecting: ” + e.getMessage());    }    finally {            if (dc != null) {                try {                    dc.close();                }                catch (Exception e) {                   System.out.println(“Exception Closing: ” + e.getMessage());                }            }        }    }  // This function is a listener. It waits to receive datagram packets on 9001 port    class Receive extends Thread  {        public void run() {        doReceive();        }        void doReceive() {            DatagramConnection dc = null;            Datagram dgram;      try {        // Open Server side datagram connection                dc = (DatagramConnection)Connector.open(“datagram://:”+receiveport);          String receivedMsg;          while (true) {                    dgram = dc.newDatagram(dc.getMaximumLength());                try {             dc.receive(dgram);          } catch (Exception e) {            System.out.println(“Exception in receiving message:” + e.getMessage());          }                    receivedMsg = new String(dgram.getData(), 0,dgram.getLength());                    System.out.println(“Received Message: ” + receivedMsg);                    try {                       Thread.sleep(500);                    }                    catch (Exception e) {                      System.out.println(“Exception doReceive(): ” + e.getMessage());                    }                }            }          catch (Exception e) {          System.out.println(“Exception doReceive(): ” + e.getMessage());       }       finally {          if (dc != null) {          try {                       dc.close();                   }                   catch (Exception e) {                      System.out.println(“Exception Closing: ” + e.getMessage());                   }               }          }        }     } }

Derby JDBC Connection

import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import java.util.Properties;public class MainClass {   public static void main(String[] args)   {      try {         String driver = “org.apache.derby.jdbc.EmbeddedDriver”;         Class.forName(driver).newInstance();         Connection conn = null;         conn = DriverManager.getConnection(“jdbc:derby:DerbyTestDB”);         Statement s = conn.createStatement();         ResultSet rs = s.executeQuery(“SELECT city, state, zipcode FROM zipcodes”);         while(rs.next()) {            System.out.println(“City   : “+ rs.getString(1));            System.out.println(“State  : “+ rs.getString(2));            System.out.println(“Zipcode: “+ rs.getString(3));            System.out.println();         }         rs.close();         s.close();         conn.close();      } catch(Exception e) {         System.out.println(“Exception: “+ e);         e.printStackTrace();      }   }}

Connect to Java DB (Derby) with org.apache.derby.jdbc.EmbeddedDriver

import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.Statement;public class JavaDBDemo {  static Connection conn;  public static void main(String[] args) {    String driver = “org.apache.derby.jdbc.EmbeddedDriver”;    String connectionURL = “jdbc:derby:myDatabase;create=true”;    String createString = “CREATE TABLE Employee (NAME VARCHAR(32) NOT NULL, ADDRESS VARCHAR(50) NOT NULL)”;    try {      Class.forName(driver);    } catch (java.lang.ClassNotFoundException e) {      e.printStackTrace();    }    try {      conn = DriverManager.getConnection(connectionURL);      Statement stmt = conn.createStatement();      stmt.executeUpdate(createString);      PreparedStatement psInsert = conn.prepareStatement(“insert into Employee values (?,?)”);      psInsert.setString(1, args[0]);      psInsert.setString(2, args[1]);      psInsert.executeUpdate();      Statement stmt2 = conn.createStatement();      ResultSet rs = stmt2.executeQuery(“select * from Employee”);      int num = 0;      while (rs.next()) {        System.out.println(++num + “: Name: ” + rs.getString(1) + “\n Address” + rs.getString(2));      }      rs.close();    } catch (Exception e) {      e.printStackTrace();    }  }}

分享一下我的Eclipse啓動參數

eclipse.exe -nl en_US -clean -vmargs -Xverify:none -XX:+UseParallelGC -XX:PermSize=20M -XX:MaxNewSize=32M -XX:NewSize=32M -Xmx256m -Xms128m -nl 後面跟的是語言 -clean 是當啓動Eclipse IDE時清空緩衝,一般來説在没有更新插件的情况下,去掉這個參數啓動速度更快。 -vmargs 使用JRE的參數,後面就是JRE的參數了: -Xverify:none 去掉JAR包數據驗證,一般來説只有在網絡環境下才需要驗證JAR包數據的有效性。本地的話可以不用驗證。 -XX:+UseParallelGC 使用并行垃圾收集機制,據説這個GC算法比較快。具體不清楚。 -XX:PermSize=20M -XX:MaxNewSize=32M -XX:NewSize=32M 這三個就是設置詳細的緩衝數據了。詳情看Java官方網站的介紹吧。 -Xmx256m Java虚擬機最大使用内存容量,根據你所使用機器的内容大小設置,只要不超過最大内存容量就好。 -Xms128m Java虚擬機初始化内存容量。 在偶Athlon64 3000+,1GB DDR400的機器第一次啓動速度不到20秒,第二次啓動速度10秒左右。希望對大家有用。