Android 应用程序在尝试获取 HttpURL 时未在后台响应



我遇到了问题,当我尝试在应用程序后台更新某些信息时,我不断收到ANR的报告(没有响应(。

代码块如下

class getServerTime extends AsyncTask<String, Long, Long> {
private Long getInternetData() {
String sURL = "http://crystalmathlabs.com/tracker/api.php?type=time"; //just a string
// Connect to the URL using java's native library
HttpURLConnection connect = null;
try {
int responseCode = -1;
List<String> listSet = new ArrayList();
URL url = new URL(sURL);
connect = (HttpURLConnection) url.openConnection();
connect.setConnectTimeout(R.integer.timeoutLengthWithACapitalT);
connect.setReadTimeout(R.integer.timeoutLengthWithACapitalT);
connect.connect();  //this is the timeout line
responseCode = connect.getResponseCode();
if (responseCode < 400) {
BufferedReader in = new BufferedReader(new InputStreamReader(connect.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
listSet.add(inputLine);
in.close();
if (listSet.get(0) != null)
return Long.parseLong(listSet.get(0));
}
return -1L;
}
catch (java.io.FileNotFoundException e) {
Log.e("getServerTime", "File Not Found: " + e.getMessage());
} catch (Exception e) {
Log.e("getServerTime", "Unknown Exception " + e.getMessage());
}
finally{
if (connect != null)
connect.disconnect();
}
return -1L;
}
@Override
protected Long doInBackground(String[] params) {
Long response;
new Scores();
try {
response = getInternetData();
if (response != null) {
return response;
}
return -1L;
} catch (Exception e) {
Log.d("Error in getServerTime", "" + Log.getStackTraceString(e.getCause().getCause()));
}
return -1L;
}

}

在connect.connect上,我收到超时。

下面附上两个ANR报告的例子,我根本想不通,请帮忙!

https://pastebin.com/F7iZ267D https://pastebin.com/W1eSdH4F

at

android.os.AsyncTask.get (AsyncTask.java:507(
at com.yargonauts.burk.runescapemarketwatch.crystalMathLabs.a.a (水晶数学函数.java:30(

您正在调用AsyncTask.get(),这几乎否定了异步任务的使用,因为它会阻塞线程,直到异步任务完成。 此阻塞会导致 ANR,因为主线程卡住等待结果。

您需要覆盖onPostExecute(Result)方法并在那里执行后续工作。查看 asynctask javadoc 的Usage部分:https://developer.android.com/reference/android/os/AsyncTask.html

最新更新