I'm trying to send a string from my phone to my Computer via UDP. In the emulator, everything works fine, I can send the string and I can receive the message on my Computer with the server-side program.
Whenever I install the apk on my phone and try to send a message, it crashes at the line:
try {udpSocket = new DatagramSocket(Integer.parseInt(String.valueOf(tPort.getText()))); } catch (Exception e) {;}
tPort has the port written in it. tIP has the IP in it.
I request this permission in the manifest:
<uses-permission android:name="android.permission.INTERNET" />
Hope somebody can spot the mistake.
I'm running the app in the emulator on a Pixel 3 XL and I have a Pixel 3a as my physical phone.
package com.example.message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.io.*;
import java.net.*;
import android.view.View;
import android.widget.TextView;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
TextView tLog,tIP,tPort, tEnter;
Button send;
DatagramSocket udpSocket;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tLog = (TextView) findViewById(R.id.tLog);
tIP = (TextView) findViewById(R.id.tIP);
tPort = (TextView) findViewById(R.id.tPort);
tEnter = (TextView) findViewById(R.id.tEnter);
send = (Button) findViewById(R.id.bSend);
send.setOnClickListener(new View.OnClickListener(){
public void onClick(View view){
tLog.setText("sending...");
try {
try {udpSocket = new DatagramSocket(Integer.parseInt(String.valueOf(tPort.getText()))); } catch (Exception e) {;}
InetAddress serverAddr = InetAddress.getByName(String.valueOf(tIP.getText()));
byte[] buf = (String.valueOf(tEnter.getText())).getBytes();
DatagramPacket packet = new DatagramPacket(buf, buf.length,serverAddr, Integer.parseInt(String.valueOf(tPort.getText()))); //9876
udpSocket.send(packet);
tLog.setText("successfully sent message!");
} catch (Exception e) {
tLog.setText("couldn't send message...");
}
}
});
}
}
The program crashes with this:
android.os.NetworkOnMainThreadException