我在调用URLconnection时收到ANR

问题描述:

编辑:这是在AsyncTask中运行,我应该提到这一点。我在调用URLconnection时收到ANR

我已经收到了许多ANR的这个代码块:

URL url = new URL(sURL); 
     URLConnection connect = url.openConnection(); 
     connect.setConnectTimeout(R.integer.timeoutLengthWithACapitalT); 
     connect.setReadTimeout(R.integer.timeoutLengthWithACapitalT); 
     BufferedReader in = new BufferedReader(new InputStreamReader(connect.getInputStream())); //Problem Line 

R.integer.timeoutLengthWithACapitalT是1000

我不知道是什么原因造成这一点,我相信它应该超时。但是,我得到了ANR的堆栈跟踪。

堆栈跟踪: https://pastebin.com/hwJhGfVX

+0

主应用程序线程上你不应该执行这个代码。 – CommonsWare

+0

你是如何在没有Asynctask的情况下运行的? –

+0

请你多线程 –

你应该在主线程无法运行您的网络呼叫。我更喜欢使用AsyncTask进行所有网络通话。您可以使用下面的代码片段

private class MyAsyncTask extends AsyncTask<URL, Integer, Long> { 
    protected Long doInBackground(URL... urls) { 
     //your main network call code 
     return result; //this return will invoke onProgressCompleted 
    } 

    protected void onPreExecute() { 
     //network call in progress, you can show a loaded here if you want 
    } 

    protected void onPostExecute(Long result) { 
     //Once network call is completed 
    } 
} 

您还可以查看Android文档的更多细节 https://developer.android.com/reference/android/os/AsyncTask.html

+0

谢谢,我忘了提及我正在使用异步,所以这不是问题。 –

+0

@JonathanBurk分享你的错误堆栈跟踪也 – Arshad

+0

我将它添加到你的pastebin。如果你需要,我有更多,但他们都大致相同。 –