Android多播不适用于不同的设备

时间:2018-04-09 07:01:17

标签: java android multicast datagram multicastsocket

我正在尝试构建一个Android应用程序,它将向wifi网络中的所有可用设备发送消息。所以我决定实现多播。我正在 Nexus5 &中测试我的应用 Sumsung S4(GT-I9500)。我的代码在两个设备上单独运行良好,这意味着现在我从同一设备接收发送的消息,但不是从其他设备接收。请检查我的Service Class下面。任何人都可以帮我解决这个问题吗?

public class MulticastService {
public String message;
InetAddress group;
MulticastSocket socket;
GSLMulticastListener gslMulticastListener;
public NewMulticastService(GSLMulticastListener gslMulticastListener) throws IOException {
    this.gslMulticastListener = gslMulticastListener;
    group = InetAddress.getByName("228.5.6.7");
    socket = new MulticastSocket(6789);
    socket.joinGroup(group);
}
public  void send(){
    @SuppressLint("StaticFieldLeak") AsyncTask task = new AsyncTask() {
        @Override
        protected Object doInBackground(Object[] objects) {
            DatagramPacket hi = new DatagramPacket(message.getBytes(), message.length(),
                    group, 6789);
            try {
                socket.send(hi);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
    };
    if (Build.VERSION.SDK_INT >= 11) task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    else task.execute();
}
public void runListener(){
    @SuppressLint("StaticFieldLeak") AsyncTask asyncTask = new AsyncTask() {
        @Override
        protected Object doInBackground(Object[] objects) {
            while(true){
                byte[] buf = new byte[1000];
                DatagramPacket recv = new DatagramPacket(buf, buf.length);
                try {
                    Log.d("runListener", "doInBackground: Listening");
                    socket.receive(recv);
                    String msg = new String(recv.getData(),0,recv.getLength());
                    Log.d("runListener", "doInBackground: "+ msg);
                    gslMulticastListener.onMulticastResponse(msg);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    };
    if (Build.VERSION.SDK_INT >= 11) asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    else asyncTask.execute();
}
}

我的舱单Permissions:

 <uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
    <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" />

0 个答案:

没有答案