此 Android 代码未接收数据包。该代码基于一些可以正常工作的java代码。有人可以提供意见,可能是什么问题。我们没有在模拟器上运行,所以它不是人们遇到的模拟器问题。发件人应用程序正在使用 android 平板电脑 wi-fi 平板电脑地址以及发送者和接收者中的 udp 端口匹配。
可能是应用程序正在丢弃数据包。
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
public class NetworkServer extends Thread
{
DatagramSocket mSocket = null;
boolean isFinish = false;
private SimplestPossibleActivity activity;
public NetworkServer(SimplestPossibleActivity activity)
{
this.activity = activity;
}
public void run()
{
try
{
Log.d("UDP", "Listening");
mSocket = new DatagramSocket( 2010); //4444
mSocket.setBroadcast(true);
while (!isFinish)
{
Log.d("UDP", "C: socket create success");
byte[] recvbuffer = new byte[12];
DatagramPacket packet = new DatagramPacket(recvbuffer,recvbuffer.length);
Log.d("UDP", "receiving...");
mSocket.receive(packet);
Log.d("UDP", "received packet");
ByteBuffer bb = ByteBuffer.allocate(recvbuffer.length).
order(ByteOrder.LITTLE_ENDIAN);
bb.put(recvbuffer);
bb.rewind();
//System.out.println(bb.getFloat());
//System.out.println(bb.getFloat());
//System.out.println(bb.getFloat());
// byte[] buffer = packet.getData();
// String msg = new String(buffer);
// bundle data to send to message handler
Bundle data = new Bundle();
data.putFloat("latitude", bb.getFloat());
data.putFloat("longitude", bb.getFloat());
data.putFloat("altitude", bb.getFloat());
Message msgHandle = new Message();
msgHandle.setData(data);
mhandler.sendMessage(msgHandle);
} //end while
} catch (Exception e) {
Log.e("UDP", "C: Error", e);
}
}
private Handler mhandler = new Handler()
{
@Override
public void handleMessage(Message msg)
{
float lat;
float lon;
float alt;
Bundle data = msg.getData();
Log.d("NetworkServer","adding position" + "lat = " + data.getFloat("latitude") +
"lon = " + data.getFloat("longitude") +
"alt = " + data.getFloat("altitude"));
activity.addPosition(data.getFloat("latitude"),
data.getFloat("longitude"),
data.getFloat("altitude"));
}
};
}