2010-04-25 23 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会阻塞整个程序直到它获得答案或达到超时。连接是否确定?