我知道如何接收数据包,但我希望我的应用程序始终检查收到的数据包
public void controlListener(){
control.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(receiveData().charAt(0)){
case '1':{
Log.d("","1");
setVisibility(View.INVISIBLE);
control.setVisibility(View.VISIBLE);
break;
}
case '3':{
Log.d("","3");
setVisibility(View.VISIBLE);
control.setVisibility(View.INVISIBLE);
Thread thread = new Thread()
{
@Override
public void run() {
try {
Log.d("", "here");
runOnUiThread(new Runnable() {
public void run() {
switch(receiveData().charAt(0)){
case '1':{
Log.d("", "1");
setVisibility(View.INVISIBLE);
control.setVisibility(View.VISIBLE);
break;
}
case '3':{
Log.d("", "3");
setVisibility(View.VISIBLE);
control.setVisibility(View.INVISIBLE);
break;
}
case '4':{
Log.d("", "4");
setVisibility(View.INVISIBLE);
control.setVisibility(View.VISIBLE);
break;
}
default:{
Log.d("","not expecting this");
}
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
};
thread.start();
break;
}
case '4':{
Log.d("","4");
setVisibility(View.INVISIBLE);
control.setVisibility(View.VISIBLE);
break;
}
default:{
Log.d("","not expecting this");
}
}
}
});
}
一旦我收到3,我想要做的就是继续接收,直到我收到1或4.并允许用户使用按钮而不是3.如果1或4使所有按钮不可见直到收到3。
答案 0 :(得分:0)
所以你说你必须使用工作线程来永久执行
DatagramPacket packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
并且在该线程中还需要一个Handler,它应该在UI线程上创建,WeakReference应该在Activity上创建,以防止内存泄漏并具有更新UI的能力。因此,当您收到新包装时,您可以这样做
handler.post(new Runnable() {
public void run() {
// do something with received string and activity
}
}