数据gramSocket 在设备上崩溃应用程序,而不是在模拟器上



我正在尝试通过UDP将字符串从手机发送到计算机。在模拟器中,一切正常,我可以发送字符串,并且可以使用服务器端程序在我的计算机上接收消息。

每当我在手机上安装 apk 并尝试发送消息时,它都会崩溃:

try {udpSocket = new DatagramSocket(Integer.parseInt(String.valueOf(tPort.getText()))); } catch (Exception e) {;}

tPort 中写有端口。tIP 包含其中的 IP。

我在清单中请求此权限:

<uses-permission android:name="android.permission.INTERNET" />

希望有人能发现错误。

我正在模拟器中的 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...");
                }
            }
        });
    }
}

程序崩溃并显示以下内容:

android.os.NetworkOnMainThreadException

好的,我找到了解决方案。虽然它似乎可以在其他设备上工作,但我的手机不想发送消息。我现在将整个过程移动到一个新的线程中,现在它工作正常。

最新更新