2010-04-25 72 views
0

我正在創建一個藍牙應用程序。命令不能在J2me的單獨線程中工作

我用退出命令創建了一個簡單的midlet,並創建了一個用於查找服務和發現設備的線程。雖然這樣做會顯示一個動畫屏幕,我在其上添加了用於退出命令的父命令監聽器。成功連接後,兩個用戶都以問候(當前屏幕調用父顯示方法setCurrent來顯示自己)表示。此屏幕也將CommandListener設置爲父級。現在我想添加更多的命令。我在這個類中實現了CommandLIstener接口,添加了一些命令但命令不起作用。我不知道什麼是錯的。我給你的代碼片段,充分說明我的問題:

package name 
Imports here 

public class MyMidlet extends MIDlet implements 
CommandListener { 

public CommandListener theListener; 

public Display theDisplay; 
public Command exitCommand; 

public MyMidlet() { 
    // Retrieve the display for this MIDlet 
    //Create the initial screen 
} 

public void startApp() throws MIDletStateChangeException { 
} 
public void pauseApp() { 
} 
public void destroyApp(boolean unconditional) { 
} 
public void commandAction(Command c, Displayable d) { 

    // Determine if the exit command was selected 
    if (c == exitCommand) { 
     //End application here 
     notifyDestroyed(); 
    } else { 
     //Start the new thread here 
    } 
} 
} 

現在,這裏是它是由一個單獨的線程上的MIDlet調用類的代碼;

package here; 
imports here 
public class MyService implements Runnable, CommandListener { 

private MyMidlet parent; 
private StreamConnection conn; 
private OutputStream output; 
private InputStream input; 

public Command sendCommand; 

private TextField messageToSend 
Form form; 

public BChatService(boolean isServer, BChatMidlet parent) { 
    //some stuff here 
this.parent = parent; 
} 

public void run() { 
    //function for showing animation here 

try { 
input = conn.openInputStream(); 
output = conn.openOutputStream(); 
} catch (IOException e) { 
displayError("IO Error", 
"An error occurred while opening " + 
"the input and output streams" + 
"(IOException: " + e.getMessage() + ")"); 
try { 
conn.close(); 
} catch (Exception ex) { 
} 
return; 
} 
// Create the Form here when service is discoverd and greets the users 


    Command sendCommand = new Command("Send", Command.ITEM, 2); 
    exitCommand = new Command("Exit", Command.EXIT, 1); 
    form.addCommand(exitCommand); 
    form.addCommand(sendCommand); 

parent.theDisplay.setCurrent(form); 

form.setCommandListener(this); 

    public void commandAction(Command c, Displayable d) { 
     if (c == exitCommand) { 
      // End the game 
      parent.destroyApp(true); 
      parent.notifyDestroyed(); 
     } 
     if(c == sendCommand) { 
      form.append("SOme text here"); 

     } 

    } 
} 

當我選擇發送命令時,字符串不會在表單中追加既不退出命令工作。

可能的原因是什麼?

我需要實現這個功能...有沒有其他的方法來實現這個功能?

+0

@RishiPatel,請改善格式。 – Kiril 2010-04-25 16:51:32

+0

它的格式正確,但是當我粘貼它時,我做了一些格式化,並且變成了這樣。 – RishiPatel 2010-05-01 14:23:50

回答

0

你確定問題出在命令上嗎?我知道的是,即使你在不同的線程上運行它們(不知道爲什麼),調用openInputStream會阻塞整個程序直到它獲得答案或達到超時。連接是否確定?