0

Trying to implement a simple UDP Client/Server datagram between an AndroidStudio-Java application as a client, to a Visual Studio C# Server. I am completely sure of the server side being working.

Here is a UDP Client and on a ButtonClick a UDP message should be sent to the localhost on port 15000 "for now".

my StackTrace popped the Android.os.NetworkOnMainThreadException Error. I found here that I can use an easy solution which is to import StrictMode and set a new policy to permitAll(). However still my application couldn't work and literally nothing happens on ButtonClick "No Exception to trace + No received message" and here is my code:

        ButtonOne.setOnClickListener(
                    new Button.OnClickListener() {
                        public void onClick(View v) {
                            TextView TextOne = (TextView) findViewById(R.id.TestText);
                            TextOne.setText("Hi");

                            String host = "127.0.0.1"; // localhost
                            int port = 15000;
                            String message = "Test";
                            DatagramSocket dsocket = null;

                            if (android.os.Build.VERSION.SDK_INT > 9)
                            {
                                StrictMode.ThreadPolicy policy = 
                                        new StrictMode.ThreadPolicy.Builder().permitAll().build();
                                StrictMode.setThreadPolicy(policy);
                            }

                            try {
                                // Get the Internet address of the specified host
                                InetAddress address = InetAddress.getByName(host);

                                // wrap a packet
                                DatagramPacket packet = new DatagramPacket(
                                        message.getBytes(),
                                        message.length(),
                                        address, port);

                                // Create a datagram socket, send the packet through it, close it.
                                dsocket = new DatagramSocket();
                                dsocket.send(packet);
                                dsocket.close();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
            );

Then I found here here that it's strongly not recommended to use StrictMode and that I need to use AsyncTask. However on Android Documentation it says "AsyncTask must be subclassed to be used. The subclass will override at least one method (doInBackground(Params...)), and most often will override a second one (onPostExecute(Result).)" which I don't get because each time I add Async within MainActivity class I get errors and it's frustrating..

Is't okay to use StrictMode for this simple task? If yes, why it's not working? If No, can anyone tell me please how to import AsyncTask into this piece of code? and should I use Params, Progress, Result functions??

Community
  • 1
  • 1
Khalil Khalaf
  • 9,259
  • 11
  • 62
  • 104

1 Answers1

0

Since your packet is send and forget and you do not monitor its progress or do something at its end, you do not need async task. You need to start network activity in a new thread. The code is below, may have minor compilation issues since I do not have access to one right now.

ButtonOne.setOnClickListener(
                    new Button.OnClickListener() {
                        public void onClick(View v) {
                            TextView TextOne = (TextView) findViewById(R.id.TestText);
                            TextOne.setText("Hi");


                            String message = "Test";
                            Thread networkThread = new Thread() {


                              String host = "127.0.0.1"; // localhost
                              int port = 15000;
                              DatagramSocket dsocket = null;

                              public void run() {
                                try {
                                // Get the Internet address of the specified host
                                InetAddress address = InetAddress.getByName(host);

                                // wrap a packet
                                DatagramPacket packet = new DatagramPacket(
                                        message.getBytes(),
                                        message.length(),
                                        address, port);

                                // Create a datagram socket, send the packet through it, close it.
                                dsocket = new DatagramSocket();
                                dsocket.send(packet);
                                dsocket.close();
                              } catch (Exception e) {
                                e.printStackTrace();
                            }//catch
                          }//run
                         };// Networkthread
                         networkThread.start();//networkThread.start()
                        }//onClick
                    }//onClickListener
            );//setOnClickListener
  • This code doesn't run and pops two errors: "incompatible types: void cannot be converted to Thread" on the .start() part and then "message is used from within an inner class and should be declared final". Once I declare it "final" the whole thread gets in red saying "Incompatible Types: Required Java.Lang.Thread, Found: Void". Any advice? Thanks – Khalil Khalaf Feb 06 '16 at 06:26
  • Works ! One Note: Didn't work by sending to local IP - if working on Android Studio and Visual Studio (Server-Client) on the same machine. Needed the actual IP of the server. – Khalil Khalaf Feb 06 '16 at 07:02
  • Thanks mate. Appreciate it :). Why no one mentions your simple solution? "Simply create a new thread" and could you do it using AsyncTask? – Khalil Khalaf Feb 06 '16 at 07:06
  • If you do something in response in doPostExecute(), or if you want to send a big packet and want to show its progress in a bar, for example, then async task is needed since doing that through threads is very cumbersome. – Jitendra Kulkarni Feb 06 '16 at 07:20