我无法接收UDP广播数据包,AsyncTask卡在了receive(packet)方法上(或者设置了超时)。
设置MulticastLock之后,我正在调用UdpTransmission:
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
WifiManager wifi = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
assert wifi != null;
WifiManager.MulticastLock wifiLock = wifi.createMulticastLock("ABC");
wifiLock.acquire();
UdpTransmission udpTransmission = new UdpTransmission();
udpTransmission.execute();
(...)
这是UdpTransmission类:
package com.example.tcc.tcpconn;
import android.os.AsyncTask;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class UdpTransmission extends AsyncTask<Void, Void, Void>
{
public UdpTransmission()
{
}
@Override
protected Void doInBackground(Void ... voids)
{
byte[] packet = new byte[32];
DatagramPacket dp = new DatagramPacket(packet, packet.length);
try(DatagramSocket ds = new DatagramSocket(49153))
{
ds.setBroadcast(true);
// ds.setSoTimeout(500);
String rcvd = Arrays.toString(packet);
}
catch(Exception e)
{
e.printStackTrace();
}
return null;
}
}
manifest.xml:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
WireShark屏幕截图:
wireshark_screenshot
我想念什么吗?任何帮助,将不胜感激!
最佳答案
实际上,如果我插入电话(Xperia XA1 Plus),它就可以工作。但是不是模拟器,这很奇怪...