为什么Android线程在完成执行之前就被终止了?

时间:2012-10-08 22:24:17

标签: java android multithreading android-asynctask

我有一个从Internet获取一些数据的线程。它接缝正确执行并检索数据。但是,如果我调用一个应该返回数据的方法,它会留给我null。从那里我得出一个结论,线程在某种程度上在结束之前停止了。

以下是代码:

private class getHash extends AsyncTask<String, Void, String>{
    @Override
    protected String doInBackground(String... params) {
        String str = null;
        try {
            // Create a URL for the desired page
            URL url = new URL(params[0]);

            // Read all the text returned by the server
            InputStream is =  url.openStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader in = new BufferedReader(isr);
            str = in.readLine();
            is.close();
            isr.close();
            in.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        hash = str; //If I set a global variable here it gets passed without a hitch
        return str;
    }
    @Override
    protected void onPostExecute(String result) {
        hash = result; // If I comment the line above and live this one I left with a null
    }
}

编辑: 根据要求添加调用线程的代码:

            getHash hashThread =  new getHash();
            hashThread.execute(new String[] {"http://www.full.path/to/the/file.hash"});


            if(hash != null && !hash.equals(localHash)){
....

1 个答案:

答案 0 :(得分:1)

无论是什么推出了AsyncTask

{
 ....
 getHash hashThread =  new getHash(this);
 hashThread.execute(new String[] {"http://www.full.path/to/the/file.hash"});
 return; // ok now we just have to wait for it to finish ... can't read it until then
}

// Separate callback method
public void onHashComplete(String hash) {

   if(hash != null && !hash.equals(localHash)) {
      ....
   }
   ....
 }

现在在 GetHash类

public String doInBackground(String[] params) {
    .... // don't set hash here ... it will work but you will probably read it at the wrong time.
    return str;
}

public void onPostExecute(String str) {
    onHashComplete(str); // or just do all the work in here since it is a private inner class
}

...

希望这会有所帮助。记住doInBackground()发生在AsyncTask线程上,onPostExecute()在主线程上执行。任何称为execute()的线程也应该是主线程。由于主线程的工作方式,你不能指望onPostCreate()发生,直到它首先用来调用execute()的任何回调完成。这就是我添加回报的原因。