【问题标题】:DatagramSocket crashes app on device, not on emulatorDatagramSocket 在设备上崩溃应用程序,而不是在模拟器上
【发布时间】:2019-11-24 09:16:02
【问题描述】:

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

【问题讨论】:

标签: java android udp networkonmainthread


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2012-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-16
    • 1970-01-01
    相关资源
    最近更新 更多