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??