简体   繁体   中英

UDP socket does not receive datagrams on Android 6 (M)

My code below runs fine on Android 5.1.1, showing the datagram received on my console.

byte[] message = new byte[500];
try {
    String text;
    int server_port = 3421;
    DatagramPacket p = new DatagramPacket(message, message.length);
    DatagramSocket s = new DatagramSocket(server_port);

    s.receive(p);
    Log.d("APP", "After received");

    final String hexMsg = bytesToHex(message);
    Log.d("APP","message:" + hexMsg);

    s.close();
} catch (SocketException e) {
    e.printStackTrace();
} catch (UnknownHostException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} finally {

}

For some unknown reason when I run that same code on Android 6.0.1 I don't receive any datagram. No error is showed on console.

My UDP server is sending the datagram directly to my android device (so, it is not a broadcast).

Full class code:

 public class MainActivity extends AppCompatActivity {
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            if (Build.VERSION.SDK_INT>Build.VERSION_CODES.LOLLIPOP_MR1) {
                String pkg=getPackageName();
                PowerManager pm=getSystemService(PowerManager.class);

            if (!pm.isIgnoringBatteryOptimizations(pkg)) {
                Intent i= new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS)
                                .setData(Uri.parse("package:" + pkg));

                startActivity(i);
            }
        }

        new myAsync().execute();

    }

    final protected static char[] hexArray = "0123456789ABCDEF".toCharArray();
    public static String bytesToHex(byte[] bytes) {
        char[] hexChars = new char[bytes.length * 2];
        for ( int j = 0; j < bytes.length; j++ ) {
            int v = bytes[j] & 0xFF;
            hexChars[j * 2] = hexArray[v >>> 4];
            hexChars[j * 2 + 1] = hexArray[v & 0x0F];
        }
        return new String(hexChars);
    }

    class myAsync extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
        }

        @Override
        protected Void doInBackground(Void... params) {
            // TODO Auto-generated method stub

            byte[] message = new byte[500];
            try {
                String text;
                int server_port = 3421;
                DatagramPacket p = new DatagramPacket(message, message.length);
                DatagramSocket s = new DatagramSocket(server_port);

                s.receive(p);
                Log.d("APP", "After received");

                final String hexMsg = bytesToHex(message);
                Log.d("APP","message:" + hexMsg);


                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),  hexMsg, Toast.LENGTH_LONG).show();
                    }
                });


                s.close();
            } catch (SocketException e) {
                e.printStackTrace();
            } catch (UnknownHostException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {

            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            // Handle/Update UI Part
        }
    }
}

Any ideas on what could be the problem?

I was able to make it work by doing 2 changes:

1st) Allowing the reuse adddress by using:

DatagramSocket s = new DatagramSocket(null);
s.setReuseAddress(true);
s.bind(new InetSocketAddress(server_port));

instead of

DatagramSocket s = new DatagramSocket(server_port);

2nd) Using a Runnable Thread instead of the Async method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM