就像标题所示,我有一个带有 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
}
}
}
调用 onReceive(String[] msg) 并处理不同线程上接收消息的代码的 RemoteControlServer 实现如下所示,
...
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");
}
});
}
}
}
});
...
我收到错误“只有创建 View 层次结构的原始线程才能触摸其 View 。”当 onReceive() 被调用并抛出异常并使用异常描述调用 onNotify() 时。为什么 onNotify() 可以工作,而另一个却不能?如何正确调用 TextView 的监听器并更新其文本?谢谢
最佳答案
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();
}
...
}
关于java - 从辅助线程在主线程上调用带参数的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22132797/