我在更新TextView
时遇到问题,我使用Handler方法将消息传递给UI。我的应用程序接收数据(类型整数)true io stream并显示在TextView
中。
我的Activity类看起来像这样:
public class DeviceView extends Activity {
TextView dataX;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.device_view);
dataX = (TextView) findViewById(R.id.datax);
handler = new Handler() {
@Override
public void handleMessage(Message msg) {
dataX.setText(String.valueOf(msg.arg1));
}
};
}
}
我还有一个单独的类,它扩展了Thread:
public class IOThread extends Thread {
public void run() {
byte[] buffer = new byte[1024];
int data;
while (true) {
try {
data = in.read(buffer);
Message message= Message.obtain();
message.arg1= data;
DeviceView.handler.sendMessage(message);
} catch (IOException ex) {
break;
}
}
}
}
我是否必须创建单独的变量类型String
并将其指向可变数据并最后调用计数?这是否足以更新TextView
?
答案 0 :(得分:0)
您可以尝试使用界面吗?让Activity实现它,将它传递给IOThread类。获得结果后,将结果传递给Activity。
名为InterfaceData的接口
public class DeviceView extends Activity implements InterfaceData{
TextView dataX;
Handler handler;
IOThread ioThread;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.device_view);
handler = new Handler();
ioThread = new IOThread(this);
dataX = (TextView) findViewById(R.id.datax);
}
@Override
public void getData(int data){
handler.postDelayed(new Runnable(){
public void run(){
dataX.setText(data);
};
},100);
}
}
> Thread class
public class IOThread extends Thread {
InterfaceData interfaceData;
public IOThread(InterfaceData interfaceData){
this.interfaceData = interfaceData;
}
public void run() {
byte[] buffer = new byte[1024];
int data;
while (true) {
try {
data = in.read(buffer);
interfaceData.getData(data);
} catch (IOException ex) {
break;
}
}
}
}
答案 1 :(得分:0)
我发现我的问题不是处理程序问题。我在开头发布的代码是coorect。问题是我从InputStream读取接收到的bytes []数组的方式。我已通过发送整数int numbers = (int) 2
进行测试,当在Android应用中在终端中打印此接收数据时,它仅接收1,即使我发送int 3或4,我仍然会收到1。
所以我在你的示例代码@ dcanh121之前,但我的问题是如何正确读取服务器发送的整数?
public void run() {
byte[] buffer = new byte[1024];
int data;
while (true) {
try {
data = in.read(buffer);
Log.d(TAG + data, "test");
Message message = Message.obtain();
message.arg1 = data;
Log.d(TAG + message.arg1, "test");
DeviceView.handler.sendMessageDelayed(message, 100);
} catch (IOException ex) {
Log.e(TAG_IOThread, "disconnected", ex);
break;
}
}
}