运行AsyncTask

时间:2017-02-15 17:38:59

标签: android android-studio exception

我在Exception上获得了Runtime AsyncTask课程。但我无法确切地确定BufferReader while循环中的确切位置。我可以在调试器中看到在我的设备上读取第一行文件和第二行,但我认为在创建Node对象或更新进度的这一点上它是抛出Exception的时候。任何帮助表示赞赏。

package com.example.george.droidscanner;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    Button btnRead;
    TextView textResult;

    ListView listViewNode;
    ArrayList<Node> listNote;
    ArrayAdapter<Node> adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnRead = (Button)findViewById(R.id.readclient);
        textResult = (TextView)findViewById(R.id.result);

        listViewNode = (ListView)findViewById(R.id.nodelist);
        listNote = new ArrayList<>();
        ArrayAdapter<Node> adapter = new ArrayAdapter<Node>(
                        MainActivity.this,
                        android.R.layout.simple_list_item_1,
                        listNote);
        listViewNode.setAdapter(adapter);

        btnRead.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new TaskReadAddresses(listNote, listViewNode).execute();
            }
        });
    }


    private class TaskReadAddresses extends AsyncTask<Void, Node, Void> {

        ArrayList<Node> array;
        ListView listView;

        TaskReadAddresses(ArrayList<Node> array, ListView v){
            listView = v;
            this.array = array;
            array.clear();
            textResult.setText("querying...");
        }

        @Override
        protected Void doInBackground(Void... params) {
            readAddresses();
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            textResult.setText("Done");
        }

        @Override
        protected void onProgressUpdate(Node... values) {
            listNote.add(values[0]);
            ((ArrayAdapter)(listView.getAdapter())).notifyDataSetChanged();
        }

        private void readAddresses() {
            BufferedReader bufferedReader = null;

            try {
                bufferedReader = new BufferedReader(new FileReader("/proc/net/arp"));

                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    String[] splitted = line.split(" +");
                    if (splitted != null && splitted.length >= 4) {
                        String ip = splitted[0];
                        String mac = splitted[3];
                        if (mac.matches("..:..:..:..:..:..")) {
                            Node thisNode = new Node(ip, mac);
                            publishProgress(thisNode);
                        }
                    }
                }

            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally{
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

节点类

package com.example.george.droidscanner;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * Created by george on 2/14/17.
 */

public class Node {
    String ip;
    String mac;
    String CanonicalHostName;
    String HostName;
    String LocalHostCanonicalHostName;
    String LocalHostHostName;
    String remark;
    boolean isReachable;

    Node(String ip, String mac){
        this.ip = ip;
        this.mac = mac;
        queryHost();
    }

    @Override
    public String toString() {
        return "IP: " + ip + "\n" +
                "MAC: " + mac + "\n" +
                "CanonicalHostName:\t" + CanonicalHostName + "\n" +
                "HostName:\t" + HostName + "\n" +
                "getLocalHost().getCanonicalHostName():\t" + LocalHostCanonicalHostName + "\n" +
                "getLocalHost().getHostName():\t" + LocalHostHostName + "\n" +
                "isReachable: " + isReachable +
                "\n" + remark;
    }

    private void queryHost(){
        try {
            InetAddress inetAddress = InetAddress.getByName(ip);
            CanonicalHostName = inetAddress.getCanonicalHostName();
            HostName = inetAddress.getHostName();
            LocalHostCanonicalHostName = inetAddress.getLocalHost().getCanonicalHostName();
            LocalHostHostName = inetAddress.getLocalHost().getHostName();
            isReachable = inetAddress.isReachable(3000);

        } catch (UnknownHostException e) {
            e.printStackTrace();
            remark = e.getMessage();
        } catch (IOException e) {
            e.printStackTrace();
            remark = e.getMessage();
        }
    }
}

XML文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    android:orientation="vertical"
    tools:context="com.example.george.droidscanner.MainActivity">


    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:autoLink="web"
        android:text="http://android-er.blogspot.com/"
        android:textStyle="bold" />

    <Button
        android:id="@+id/readclient"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAllCaps="false"
        android:text="Read Ip/MAC addresses"/>

    <TextView
        android:id="@+id/result"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:typeface="monospace"
        android:textSize="24sp"/>

    <ListView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/nodelist">

    </ListView>

</LinearLayout>

运行时异常错误

E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
                  Process: com.example.george.droidscanner, PID: 18522
                  java.lang.RuntimeException: An error occured while executing doInBackground()
                      at android.os.AsyncTask$3.done(AsyncTask.java:304)
                      at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
                      at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
                      at java.util.concurrent.FutureTask.run(FutureTask.java:242)
                      at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
                      at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
                      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
                      at java.lang.Thread.run(Thread.java:818)
                   Caused by: java.lang.SecurityException: Permission denied (missing INTERNET permission?)
                      at java.net.InetAddress.lookupHostByName(InetAddress.java:451)
                      at java.net.InetAddress.getLocalHost(InetAddress.java:396)
                      at com.example.george.droidscanner.Node.queryHost(Node.java:44)
                      at com.example.george.droidscanner.Node.<init>(Node.java:24)
                      at com.example.george.droidscanner.MainActivity$TaskReadAddresses.readAddresses(MainActivity.java:95)
                      at com.example.george.droidscanner.MainActivity$TaskReadAddresses.doInBackground(MainActivity.java:67)
                      at com.example.george.droidscanner.MainActivity$TaskReadAddresses.doInBackground(MainActivity.java:53)
                      at android.os.AsyncTask$2.call(AsyncTask.java:292)
                      at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                      at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) 
                      at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) 
                      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) 
                      at java.lang.Thread.run(Thread.java:818) 
                   Caused by: android.system.GaiException: android_getaddrinfo failed: EAI_NODATA (No address associated with hostname)
                      at libcore.io.Posix.android_getaddrinfo(Native Method)
                      at libcore.io.ForwardingOs.android_getaddrinfo(ForwardingOs.java:55)
                      at java.net.InetAddress.lookupHostByName(InetAddress.java:438)
                      at java.net.InetAddress.getLocalHost(InetAddress.java:396) 
                      at com.example.george.droidscanner.Node.queryHost(Node.java:44) 
                      at com.example.george.droidscanner.Node.<init>(Node.java:24) 
                      at com.example.george.droidscanner.MainActivity$TaskReadAddresses.readAddresses(MainActivity.java:95) 
                      at com.example.george.droidscanner.MainActivity$TaskReadAddresses.doInBackground(MainActivity.java:67) 
                      at com.example.george.droidscanner.MainActivity$TaskReadAddresses.doInBackground(MainActivity.java:53) 
                      at android.os.AsyncTask$2.call(AsyncTask.java:292) 
                      at java.util.concurrent.FutureTask.run(FutureTask.java:237) 
                      at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) 
                      at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) 
                      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) 
                      at java.lang.Thread.run(Thread.java:818) 

2 个答案:

答案 0 :(得分:3)

在Manifest中添加以下行:

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

答案 1 :(得分:3)

正如您在日志中看到的那样。这是由

引起的

Caused by: java.lang.SecurityException: Permission denied (missing INTERNET permission?)

将以下权限添加到AndroidManifest

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