DatagramSocket使设备(而不是模拟器)上的应用程序崩溃

时间:2019-07-15 16:14:46

标签: java android udp networkonmainthread

我正在尝试通过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

1 个答案:

答案 0 :(得分:0)

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