1
MulticastSocket.receive 메소드가 내 스레드를 차단하고 있다고 생각합니다. 응용 프로그램이 스레드를 다시 시작하는 onResume()으로 이동하지 않으면 다시 작동하지 않습니다. 이 문제를 어떻게 해결할 수 있습니까?Android 멀티 캐스트 - 때로는 수신 스레드 차단 중입니다.
수신기 코드
private class ReceiverThread extends Thread
{
private static final String TAG = ComMessageReceiver.TAG + "Thread";
private WifiManager wifiManager;
private MulticastSocket multicastSocket;
private InetSocketAddress groupInetSocketAddress;
private boolean joinedGroup = false;
public ReceiverThread(String group, int port, int timeout) throws IOException {
super();
wifiManager = (WifiManager) App.context.getSystemService(Context.WIFI_SERVICE);
groupInetSocketAddress = new InetSocketAddress(InetAddress.getByName(group), port);
multicastSocket = new MulticastSocket(port);
multicastSocket.setSoTimeout(timeout);
}
public ReceiverThread() throws IOException {
this(Config.multicastAddress, Config.multicastPort, DEFAULT_TIMEOUT);
}
@Override
public void run() {
Log.d(TAG, "started");
while (!this.isInterrupted()) {
if (wifiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLED) {
if (!joinedGroup) {
try {
multicastSocket.joinGroup(groupInetSocketAddress,
NetworkInterface.getByInetAddress(getWifiInetAddress()));
wifiManager.createMulticastLock("ComMessageReceiverLock").acquire();
joinedGroup = true;
} catch (IOException ex) {
Log.e(TAG, "Failed to join Multicast group: " + ex.getMessage());
}
}
try {
byte[] buffer = new byte[256];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
multicastSocket.receive(packet);
Log.d(TAG, "Message received: " + message.message);
} catch (SocketTimeoutException e) {
} catch (IOException ex) {
multicastSocket = null;
Log.e(TAG, ex.getMessage());
}
} else
joinedGroup = false;
}
}
}
멀티 캐스트 코드
private class ComServerThread extends Thread {
private static final String LOG = "ComServerThread";
private final static long INTERVAL = 1000;
private boolean alert = true;
private DatagramSocket socket;
public ComServerThread() {
try {
socket = new DatagramSocket(5500);
} catch (SocketException ex) {
Log.e(LOG, "Error opening socket: " + ex.getMessage());
}
}
@Override
public void run() {
while (!this.isInterrupted()) {
try {
try {
sleep(INTERVAL);
} catch (InterruptedException ex) {
Log.e(LOG, "Interrupted the thread sleep! not cool: "
+ ex.getMessage());
}
byte[] buffer;
String msg = "Test"
buffer = msg.getBytes();
InetAddress group = InetAddress.getByName("230.0.0.1");
DatagramPacket packet = new DatagramPacket(buffer,
buffer.length, group, 5500);
socket.send(packet);
Log.d(LOG, "Packet sent.");
} catch (UnknownHostException ex) {
Log.e(LOG, "Oops. Invalid host: " + ex.getMessage());
} catch (IOException ex) {
Log.e(LOG,
"Something bad happened while sending the packet. Take a look: "
+ ex.getMessage());
}
}
}
}