2014-03-02 54 views
0

喜欢标题建议我有一个MainActivity类的一个Android项目,有一个TextView,我想在收到消息后设置文本。我也有一个类在接收我想要显示的字符串消息的单独线程上运行ServerSocket。我的MainActivity的调用方法瓦特/主线程从次线程的参数

部分看起来是这样的,

private Handler UIHandler = new Handler(); 
private RemoteControlServer remoteConnection; 
public static final int controlPort = 9090; 
public class MainActivity extends Activity implements SensorEventListener 
{ 
    ... 

    remoteConnection = new RemoteControlServer(controlPort, UIHandler); 

    ... 

    private class RemoteControlServer extends RemoteControl 
    { 
     RemoteControlServer(int port, Handler ui) 
     { 
      super(port, ui); 
     } 

     @Override 
     public void onReceive(String[] msg) 
     { 
      //updates messages textview 
     } 

     @Override 
     public void onNotify(String[] msg) 
     { 
      //updates notification textview 
     } 
    } 
} 

的代码RemoteControlServer执行调用的onReceive(字符串[MSG])还负责在不同的线程接收消息看起来是这样的,

... 

public abstract void onReceive(String[] msg); 
public abstract void onNotify(String[] msg); 

... 

controlListener = new Thread(new Runnable() 
{ 
    boolean running = true; 
    public void run() 
    { 
     String line = null; 
     while(running) 
     { 
      try 
      { 
       //Handle incoming messages 

       ... 

       onReceive(messages);  
      } 
      catch (final Exception e) 
      { 
       UIHandler.post(new Runnable() 
       { 
        public void run() 
        { 
         onNotify("Wifi Receive Failed " + e.toString() + "\n"); 
        } 
       }); 
      } 
     } 
    } 
}); 

... 

我收到错误“只有创建视图层次结构的原始线程可以触及其视图。”当onReceive()被调用并抛出异常,并调用onNotify()和异常描述。为什么onNotify()工作,但另一个不工作?我如何正确地调用监听器到TextView并更新其文本?谢谢

回答

1
private class RemoteControlServer extends RemoteControl 
{ 

    ... 

    public class BridgeThread implements Runnable 
    { 
     String[] msgArray = null; 
     public BridgeThread(String[] msg) 
     { 
      msgArray = msg; 
     } 

     public void run() 
     { 
      runOnUiThread(new Runnable() 
      { 
       @Override 
       public void run() 
       { 
        TextView zValue = (TextView) findViewById(R.id.connectionStatus); 
        zValue.setText(msgArray[0]); 
       } 
      }); 
     } 
    } 

    @Override 
    public void onReceive(String[] msg) 
    { 
     BridgeThread bridgeTest = new BridgeThread(msg); 
     bridgeTest.run(); 
    } 

    ... 
} 
+0

这会取代我目前的新线程()代码?纠正我,如果我错了,但不会在UI线程上运行我的ServerSocket(我不想这么做)? – anders

+0

当你收到一个字符串,你想在TextView中显示...只需复制该代码,并在文本视图中调用setText与该字符串(在我的代码上面是/ /设置您的文本)...事情是,你会调用UI线程(UI线程可以与用户界面一起工作,这就是你想要的)来自另一个线程,你已经实现了接收消息......为你准备好了吗? :)我不是那么好在EN:/ –

+1

好吧谢谢Matej的建议我会试几个 – anders

相关问题