【问题标题】:Why I'm Getting NetworkOnMainThread Exception Error onProgressUpdate为什么我在 ProgressUpdate 上收到 NetworkOnMainThread 异常错误
【发布时间】:2019-04-19 17:57:15
【问题描述】:

我正在使用 AsyncTask 在填充后读取“/proc/net/arp”文件。问题是,在我阅读每一行之后,我想为每个 IP 地址进行名称解析。那就是我遇到异常错误的时候。我没有在主线程上执行这个,因为我在这个过程中使用了 AsyncTask。这是我的 onProgressUpdate 方法

protected void onProgressUpdate(Void... params) {
            //update progress bar
            /*scanProgress.setProgress(values[0].progressBar);*/
            try {

                BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(ARP_TABLE), "UTF-8"));
                reader.readLine(); // Skip header.
                String line;
                while ((line = reader.readLine()) != null) {
                    Log.v("ARPFILE", line);
                    String[] arpLine = line.split("\\s+");
                    //if arp line contains flag 0x2 we parse host
                    if(arpLine[2].equals(ARP_FLAG)) {
                        final String ip = arpLine[0];
                        final String flag = arpLine[2];
                        final String mac = arpLine[3];
                        Node node = new Node(ip, mac);
                        hostList.add(node);
                        networkAdapter.notifyDataSetInvalidated();
//                        scanProgress.setProgress(node.progressBar);
                    }
                }
                reader.close();
            }
            catch (Exception ex) {

            }

            for(Node node: hostList) {
                InetAddress inetAddress;
                android.os.Debug.waitForDebugger();
                try {
                    inetAddress = InetAddress.getByName(node.ip);
                    String hostname = inetAddress.getCanonicalHostName();
                    node.setHostName(hostname);
                    Log.v("HOSTNAME", hostname);
                } catch (UnknownHostException e) {
                    // It's common that many discovered hosts won't have a NetBIOS entry.
                }
            }
        }

【问题讨论】:

    标签: android exception android-asynctask


    【解决方案1】:

    我没有在主线程上执行这个,因为我正在为此使用 AsyncTask 过程。这是我的 onProgressUpdate 方法

    onProgressUpdate() 方法在主线程上调用的。 From the Documentation for AsyncTask:

    onProgressUpdate(Progress...),调用后在 UI 线程上调用 到publishProgress(Progress...)。执行时间为 不明确的。此方法用于显示任何形式的进度 后台计算仍在执行时的用户界面。 例如,它可以用于动画进度条或显示登录 一个文本字段。

    doInBackground() 中执行任何应该在 UI 线程外完成的代码

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多