Android 应用程序在尝试获取 HttpURLConnection 时在后台没有响应

Android app not Responding in Background when trying to get HttpURLConnection

我遇到了一个问题,当我尝试在我的应用程序后台更新一些信息时,我不断收到 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 (crystalMathFunctions.java:30)

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

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