[英]How to make DatagramSocket always to be receiving Packets for android
I know how to receive packets but I want my app to always check to packets that received 我知道如何接收数据包,但我希望我的应用始终检查收到的数据包
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");
}
}
}
});
}
What I wanted to do once I receive a 3 too keep receiving until i receive either a 1 or a 4. and allow the user to use the buttons while its a 3. If a 1 or 4 make all of the buttons invisible till a receive a 3. 收到3时我想做的事情也要一直接收,直到收到1或4为止,并允许用户在3时使用按钮。如果1或4使所有按钮不可见,直到接收到一个3。
So as you said you have to use a worker thread to permanently execute 因此,正如您所说的,您必须使用辅助线程来永久执行
DatagramPacket packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
and also in that thread you need a Handler, which should be created on the UI thread and a WeakReference to your Activity to prevent memory leaks and have ability to update UI. 并且在该线程中,您需要一个Handler(应该在UI线程上创建)以及对Activity的WeakReference,以防止内存泄漏并具有更新UI的能力。 So when you receive new package you can do like this
因此,当您收到新的包裹时,您可以这样做
handler.post(new Runnable() {
public void run() {
// do something with received string and activity
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.