0
我向我的android手机中的设备发送broadcast message
,并等待他们回复。Android - 通过套接字收听设备并创建其列表
还有n
网络中的设备数量。
现在我需要创建一个设备列表发送回复。
我正在使用Runnable接口和用于接收回复的数据包。
如何准备设备列表?
由于线程不会返回任何值。我想要准备一个随机列表。类似于蓝牙搜索。
我尝试使用方法
public static synchronized void addDevice(DeviceDetails device) throws IOException
{
listIsChanged=true; //if the list changes that means if there is a device then this method will be called.
deviceList = device;
Log.v("device added with IP:",device.getDeviceIP());
}
MulticastReceiver.java
public class MulticastReceiver implements Runnable
{
DatagramSocket socket = null;
DatagramPacket inPacket = null;
byte[] inBuf;
public MulticastReceiver()
{
try
{
socket = new DatagramSocket(WifiConstants.PORT_NO_RECV);
inBuf = new byte[WifiConstants.DGRAM_LEN];
inPacket = new DatagramPacket(inBuf, inBuf.length);
socket.setSoTimeout(2*60*1000);
}
catch(Exception ioe)
{
System.out.println(ioe);
}
}
@Override
public void run()
{
//System.out.println("Listening");
try
{
for(long stop=System.nanoTime()+TimeUnit.SECONDS.toNanos(2); stop>System.nanoTime();)
{
Log.v("yoyo","yoyo honey singh");
socket.receive(inPacket);
Log.v("checking to receive","received");
String msg = new String(inBuf, 0, inPacket.getLength());
Log.v("Received: ","From :" + inPacket.getAddress() + " Msg : " + msg);
DeviceDetails device = getDeviceFromString(msg);
DeviceManagerWindow.addDevice(device);
Thread.sleep(1000);
}
}
/**try
{
socket.setSoTimeout(5000);
socket.receive(inPacket);
Log.v("checking to receive","received");
String msg = new String(inBuf, 0, inPacket.getLength());
Log.v("Received: ","From :" + inPacket.getAddress() + " Msg : " + msg);
DeviceDetails device = getDeviceFromString(msg);
DeviceManagerWindow.addDevice(device);
Thread.sleep(1000);
}**/
catch(Exception e)
{
Log.v("Receiving Error: ",e.toString()+" No Packets Received");
}
finally
{
socket.close();
}
}
public DeviceDetails getDeviceFromString(String str)
{
String type;
String IP;
type=str.substring(0,str.indexOf('`'));
str = str.substring(str.indexOf('`')+1);
IP=str;
DeviceDetails device = new DeviceDetails(type,IP);
return device;
}
}
DeviceDetails.java
package com.example.devicecontrolpanel;
public class DeviceDetails
{
private String DeviceType;
private String IPAddr;
public DeviceDetails(String type, String IP)
{
this.DeviceType=type;
this.IPAddr=IP;
}
public String getDeviceType()
{
return this.DeviceType;
}
public String getDeviceIP()
{
return this.IPAddr;
}
}
这个问题目前是关闭的候选人,因为它只能用大量的代码来回答。你能否详细说明你迄今为止所尝试过的内容,可能会分享相关的代码示例。 – 2013-05-10 10:04:57
我做了一个编辑到目前为止我已经尝试过了...... – 2013-05-10 10:08:08
请同时发布你的'Runnable'实现。 – 2013-05-10 10:23:11