为什么避免 "NetworkOnMainThreadException" 的 AsyncTask 不起作用?

Why AsyncTask to avoid "NetworkOnMainThreadException" is not working?

尝试在作为客户端的 AndroidStudio-Java 应用程序与 Visual Studio C# 服务器之间实现一个简单的 UDP Client/Server 数据报。我完全确定服务器端正在工作。

Here 是一个 UDP 客户端,在 ButtonClick 上应该将 UDP 消息发送到端口 15000 "for now".

上的本地主机

我的 StackTrace 弹出 Android.os.NetworkOnMainThreadException 错误。我发现 here 我可以使用一个简单的解决方案,即导入 StrictMode 并将新策略设置为 permitAll()。但是,我的应用程序仍然无法运行,ButtonClick "No Exception to trace + No received message" 上几乎没有任何反应,这是我的代码:

        ButtonOne.setOnClickListener(
                    new Button.OnClickListener() {
                        public void onClick(View v) {
                            TextView TextOne = (TextView) findViewById(R.id.TestText);
                            TextOne.setText("Hi");

                            String host = "127.0.0.1"; // localhost
                            int port = 15000;
                            String message = "Test";
                            DatagramSocket dsocket = null;

                            if (android.os.Build.VERSION.SDK_INT > 9)
                            {
                                StrictMode.ThreadPolicy policy = 
                                        new StrictMode.ThreadPolicy.Builder().permitAll().build();
                                StrictMode.setThreadPolicy(policy);
                            }

                            try {
                                // Get the Internet address of the specified host
                                InetAddress address = InetAddress.getByName(host);

                                // wrap a packet
                                DatagramPacket packet = new DatagramPacket(
                                        message.getBytes(),
                                        message.length(),
                                        address, port);

                                // Create a datagram socket, send the packet through it, close it.
                                dsocket = new DatagramSocket();
                                dsocket.send(packet);
                                dsocket.close();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
            );

然后我发现这里 here that it's strongly not recommended to use StrictMode and that I need to use AsyncTask. However on Android Documentation 它说“AsyncTask 必须被 subclassed 才能使用。subclass 将覆盖至少一个方法( doInBackground(Params...)),并且通常会覆盖第二个(onPostExecute(Result)。)”,我没有得到,因为每次我在 MainActivity class 中添加 Async 我得到错误,这令人沮丧..

这个简单的任务可以使用 StrictMode 吗?如果是,为什么它不起作用?如果不是,谁能告诉我如何将 AsyncTask 导入这段代码?我应该使用参数、进度、结果函数吗??

由于您的数据包已发送并忘记,并且您不监视其进度或在其结束时执行某些操作,因此您不需要异步任务。您需要在新线程中启动网络 activity。代码如下,可能有一些小的编译问题,因为我现在无法访问。

ButtonOne.setOnClickListener(
                    new Button.OnClickListener() {
                        public void onClick(View v) {
                            TextView TextOne = (TextView) findViewById(R.id.TestText);
                            TextOne.setText("Hi");


                            String message = "Test";
                            Thread networkThread = new Thread() {


                              String host = "127.0.0.1"; // localhost
                              int port = 15000;
                              DatagramSocket dsocket = null;

                              public void run() {
                                try {
                                // Get the Internet address of the specified host
                                InetAddress address = InetAddress.getByName(host);

                                // wrap a packet
                                DatagramPacket packet = new DatagramPacket(
                                        message.getBytes(),
                                        message.length(),
                                        address, port);

                                // Create a datagram socket, send the packet through it, close it.
                                dsocket = new DatagramSocket();
                                dsocket.send(packet);
                                dsocket.close();
                              } catch (Exception e) {
                                e.printStackTrace();
                            }//catch
                          }//run
                         };// Networkthread
                         networkThread.start();//networkThread.start()
                        }//onClick
                    }//onClickListener
            );//setOnClickListener