0

我正在尝试从正在运行的 Runnable 内部调用一个方法。它等待输入字符串,然后根据字符串(字符串充当命令)调用方法并运行其中的内容。

public class App extends Activity implements Runnable {

    public void run() {

         try {
             ServerSocket serverSocket = new ServerSocket(portNum);
             while (true) {          
                 Socket client = serverSocket.accept();

                 try {

                      BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
                      String str = in.readLine();
                      if(str.equals("test")) {
                          //method call here
                      }

                 } catch(Exception e) {
                        Log.d("App", e.getMessage());

                 } finally {
                            client.close();
                        Log.d("App", "Done.");
                    }
             }       
         } catch (Exception e) {
             Log.d("App", e.getMessage());
         }
    }
4

1 回答 1

1

您应该创建一个Handler对象。每个Handler实例都与一个线程相关联,并且根据您要关联/处理消息的线程,您应该Handler在其上下文中创建。然后您可以将消息推送到Message创建Handler. 当字符串进来时,你可以使用这样的东西:

public Handler handler_use = new Handler(){

    // @Override
    public void handleMessage(Message msg) {
       //Do something with the message
    }
}

在 try 块内:

try {
    BufferedReader in = new BufferedReader(new  InputStreamReader(client.getInputStream()));
    String str = in.readLine();
    if(str.equals("test")) {
        //Construct the message Msg - based on the string
        handler_use.sendMessage(Msg);
    }
}
于 2010-10-20T16:38:19.800 回答