UnknownHostException导致AsyncTask中出现致命错误

时间:2015-07-29 18:18:41

标签: android android-asynctask

我有以下代码,当我可以连接到服务器时,一切正常:

  public void getXMLData()
    {
        if (skipUpdate)
        {
            skipUpdate=false;
            return;
        }
        skipUpdate=true;
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        int SERVERPORT=0;
        try {
            SERVERPORT = Integer.parseInt(prefs.getString("pref_key_port_1","Port"));
        } catch (NumberFormatException e) {
            txtStatus.setText("Invalid Port Number");
            return;
        }
        String SERVERHOST = prefs.getString("pref_key_host_1","127.0.0.1");
        String PASSWORD = prefs.getString("pref_key_pass_1", "password");
        try {
            XMLFetcherTask myXMLFetcherTask = new XMLFetcherTask(SERVERHOST,SERVERPORT,PASSWORD);
            myXMLFetcherTask.execute();
        } catch (Exception e) {
            txtStatus.setText("Error "+e.getMessage());
            return;
        }


        skipUpdate=false;
    }


    public class XMLFetcherTask extends AsyncTask<Void, Void, Void> {

    String dstAddress;
    int dstPort;
    String response = "";
    String password="";

    XMLFetcherTask(String addr, int port, String pass){
        dstAddress = addr;
        dstPort = port;
        password=pass;
    }

    @Override
    protected Void doInBackground(Void... arg0) {

        Socket socket = null;

        try {
            socket = new Socket(dstAddress, dstPort);


            PrintWriter out = new PrintWriter(new BufferedWriter(
                    new OutputStreamWriter(socket.getOutputStream())),
                    true);
            out.println(password);

            response="";
            BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            while (response.toLowerCase().indexOf("</response>")<0)
            {
                response+=input.readLine();
            }

        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
           txtStatus.setText("UnknownHostException: " + e.getMessage());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            txtStatus.setText("IOException: " + e.getMessage());
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            txtStatus.setText("Exception: " + e.getMessage());
        } finally{
                try {
                    socket.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    //txtStatus.setText("Exception Finally: " + e.getMessage());
                }
            }
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {

        if( !(response.substring(0,5).equalsIgnoreCase("<resp") || response.substring(0,5).equalsIgnoreCase("<?xml")) ) //!response.substring(0,5).equalsIgnoreCase("<?xml") ||
        {
            txtStatus.setText("Server response doesn't look XML, please check password: '"+response.substring(0,5)+"'");
        } else {
            lastXMLData=response;
            txtStatus.setText("Resp Len: " + response.length());
            skipUpdate=false;
            updateFragmentListeners();
        }

        super.onPostExecute(result);
    }

}

现在,当我收到UnknownHostException时,app强制关闭以下堆栈跟踪:

07-29 15:52:08.754    1525-1538/android.process.acore V/BackupServiceBinder﹕ doBackup() invoked
07-29 15:52:08.766    1525-1538/android.process.acore E/DictionaryBackupAgent﹕ Couldn't read from the cursor
07-29 16:29:55.178    1525-1534/android.process.acore E/StrictMode﹕ A resource was acquired at attached stack trace but never released. See java.io.Closeable for information on avoiding resource leaks.
    java.lang.Throwable: Explicit termination method 'close' not called
            at dalvik.system.CloseGuard.open(CloseGuard.java:184)
            at android.os.ParcelFileDescriptor.<init>(ParcelFileDescriptor.java:180)
            at android.os.ParcelFileDescriptor$1.createFromParcel(ParcelFileDescriptor.java:916)
            at android.os.ParcelFileDescriptor$1.createFromParcel(ParcelFileDescriptor.java:906)
            at android.app.IBackupAgent$Stub.onTransact(IBackupAgent.java:71)
            at android.os.Binder.execTransact(Binder.java:446)
07-29 16:29:55.178    1525-1534/android.process.acore E/StrictMode﹕ A resource was acquired at attached stack trace but never released. See java.io.Closeable for information on avoiding resource leaks.
    java.lang.Throwable: Explicit termination method 'close' not called
            at dalvik.system.CloseGuard.open(CloseGuard.java:184)
            at android.os.ParcelFileDescriptor.<init>(ParcelFileDescriptor.java:180)
            at android.os.ParcelFileDescriptor$1.createFromParcel(ParcelFileDescriptor.java:916)
            at android.os.ParcelFileDescriptor$1.createFromParcel(ParcelFileDescriptor.java:906)
            at android.app.IBackupAgent$Stub.onTransact(IBackupAgent.java:64)
            at android.os.Binder.execTransact(Binder.java:446)
07-29 16:29:55.178    1525-1534/android.process.acore E/StrictMode﹕ A resource was acquired at attached stack trace but never released. See java.io.Closeable for information on avoiding resource leaks.
    java.lang.Throwable: Explicit termination method 'close' not called
            at dalvik.system.CloseGuard.open(CloseGuard.java:184)
            at android.os.ParcelFileDescriptor.<init>(ParcelFileDescriptor.java:180)
            at android.os.ParcelFileDescriptor$1.createFromParcel(ParcelFileDescriptor.java:916)
            at android.os.ParcelFileDescriptor$1.createFromParcel(ParcelFileDescriptor.java:906)
            at android.app.IBackupAgent$Stub.onTransact(IBackupAgent.java:57)
            at android.os.Binder.execTransact(Binder.java:446)

我不知道为什么会这样...... 我试图评论hte txtStatus.setText,因为它通常不应该从另一个线程工作,但没有变化。 在带有框架22的Android模拟器和带有框架21的手机上测试。 任何想法都会受到欢迎

1 个答案:

答案 0 :(得分:0)

好的,我设法使用线程来代替它,这是最终的代码:

 public void getXMLData()
    {
        if (skipUpdate)
        {
            skipUpdate=false;
            return;
        }
        skipUpdate=true;
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        int SERVERPORT=0;
        try {
            SERVERPORT = Integer.parseInt(prefs.getString("pref_key_port_1","Port"));
        } catch (NumberFormatException e) {
            txtStatus.setText("Invalid Port Number");
            return;
        }
        String SERVERHOST = prefs.getString("pref_key_host_1","127.0.0.1");
        String PASSWORD = prefs.getString("pref_key_pass_1", "password");
        try {
           // XMLFetcherTask myXMLFetcherTask = new XMLFetcherTask(SERVERHOST,SERVERPORT,PASSWORD);
           // myXMLFetcherTask.execute();
            XMLFetcherTask XMLFetcherTaskThread = new XMLFetcherTask();
            XMLFetcherTaskThread.dstAddress=SERVERHOST;
            XMLFetcherTaskThread.dstPort=SERVERPORT;
            XMLFetcherTaskThread.password=PASSWORD;
            Thread cThread = new Thread(XMLFetcherTaskThread);
            cThread.start();

        } catch (Exception e) {
            txtStatus.setText("Error "+e.getMessage());
            return;
        }


        skipUpdate=false;
    }

    public class XMLFetcherTask implements Runnable {
        String dstAddress;
        int dstPort;
        String response = "";
        String password="";

        private void setStatusFromThread(final String status)
        {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    setStatus(status);
                }
            });

        }

        private void updateListenersThread()
        {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    updateFragmentListeners();
                }
            });

        }

        public void run() {
            Socket socket = null;
            //BufferedReader input = null;
            //PrintWriter out = null;

            try {
                socket = new Socket(dstAddress, dstPort);


                PrintWriter out = new PrintWriter(new BufferedWriter(
                        new OutputStreamWriter(socket.getOutputStream())),
                        true);
                out.println(password);

                response="";
                BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                while (response.toLowerCase().indexOf("</response>") < 0) {
                    response+=input.readLine();
                }
                if( !(response.substring(0,5).equalsIgnoreCase("<resp") || response.substring(0,5).equalsIgnoreCase("<?xml")) ) //!response.substring(0,5).equalsIgnoreCase("<?xml") ||
                {
                    setStatusFromThread("Server response doesn't look XML, please check password: '" + response.substring(0, 5) + "'");
                } else {
                    lastXMLData=response;
                    Date dNow = new Date( );
                    SimpleDateFormat ft = new SimpleDateFormat ("hh:mm:ss");
                    setStatusFromThread("Last update: " + ft.format(dNow));
                    skipUpdate=false;
                    updateListenersThread();
                }

            } catch (UnknownHostException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                setStatusFromThread("UnknownHostException: " + e.getMessage());
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                setStatusFromThread("IOException: " + e.getMessage());
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                setStatusFromThread("Exception: " + e.getMessage());
            } finally{
                try {
                    socket.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    //txtStatus.setText("Exception Finally: " + e.getMessage());
                } catch (Exception e) {
                    // TODO Auto-generated catch block

                }
            }

        }
    }