2012-10-08 120 views
1

我有一个线程从互联网上获取一些数据。它接近它正确执行并检索数据。但是,如果我调用一个应该返回数据的方法,那么我就会留下空值。从那里我得出结论,线程在finning之前不知何故停止。为什么Android线程在完成执行之前被终止?

下面是代码:

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)){ 
.... 
+2

“从这里我得出结论,线程在finning之前就停止了。” - 或者,你有一个例外。 – CommonsWare

+0

您如何检索价值以证明它在完成之前确实停止。 –

+0

不@CommonsWare我真的得出了一个结论,我没有看到异常。 GregGiacovelli如果您可能将您的注意力引向我给出的代码示例,最后您会找到两行,并附上一些解释性评论。 – PovilasID

回答

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线程上,在主线程上执行。无论什么线程调用​​也应该是主线程。由于主线程的工作方式,您不能期望onPostCreate()发生,直到它首先调用​​时使用的任何回调完成为止。所以这就是为什么我添加回报。

+0

感谢您的清除。我一定是错过了那部分,同时阅读了关于线程的内容,并冲向了开发。 – PovilasID

相关问题