[英]DatagramSocket crashes app on device, not on emulator
I'm trying to send a string from my phone to my Computer via UDP.我正在尝试通过 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:每当我在手机上安装 apk 并尝试发送消息时,它都会在线路上崩溃:
try {udpSocket = new DatagramSocket(Integer.parseInt(String.valueOf(tPort.getText()))); } catch (Exception e) {;}
tPort has the port written in it. tPort 中写入了端口。 tIP has the IP in it. tIP 中有 IP。
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.我正在 Pixel 3 XL 上的模拟器中运行该应用程序,并且我的实体手机是 Pixel 3a。
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 android.os.NetworkOnMainThreadException
Okay, I have found a solution.好的,我找到了解决方案。 While it seemed to work on other devices, my phone didn't want to send the message.虽然它似乎适用于其他设备,但我的手机不想发送消息。 I now moved the whole process into a new Thread and now it works fine.我现在将整个过程移到一个新的线程中,现在它工作正常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.