我已经实现了此代码以通过udp包获取数据,但我只能读取第一个包(Thread run()方法运行一次)。我正在实现线程和处理程序。
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textViewState = (TextView)findViewById(R.id.state);
new Thread() {
@Override
public void run() {
byte[] buffer = new byte[100];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
DatagramSocket datagramSocket = null;
try {
datagramSocket = new DatagramSocket(3333);
} catch (SocketException e) {
e.printStackTrace();
}
try {
datagramSocket.receive(packet);
mHandler.obtainMessage(2, 10, -1, buffer)
.sendToTarget(); // Send the obtained bytes to the UI activity
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
mHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
if (msg.what == 2) {
byte[] readRpmBuf = (byte[]) msg.obj;
String val="";
for (int i=0;i<100;i++){
val+=String.valueOf(readRpmBuf[i])+"-";
}
textViewState.setText(val);
}
}
};
}