如何避免显示“应用程序无响应”对话框

How to avoid Application Not Responding dialog from showing

我正在使用下面的方法提取将XML转换为JSON。!

  1. 首先我将 url 传递给 xml 的 api 调用,然后提取 数据并将其放入字符串中。
  2. 然后使用这个Library,我 将 xml 转换为 JSON 对象。
  3. 最后我使用 json 对象数据 获取网络数据并填充我的 recyclerviews。

它运行良好,但有时会出现 ANR 对话框..!有帮助吗?

  public static void getResponse(final String xmlLink, final Activity activity,
      final GetJSONRespone getjson) {

    Handler uiHandler = new Handler(Looper.getMainLooper());
    uiHandler.post(new Runnable() {
      @Override
      public void run() {
        URL url = null;
        BufferedReader in = null;
        try {
          url = new URL(xmlLink);

          in = new BufferedReader(
              new InputStreamReader(
                  url.openStream(), "UTF-8")); 

          String inputLine;
          System.setProperty("http.keepAlive", "false");  

          StringBuilder builder = new StringBuilder();
          while ((inputLine = in.readLine()) != null) {
            builder.append(inputLine);
          }
          String urlContent = builder.toString();

          XmlToJson xmlToJson = new XmlToJson.Builder(urlContent).build();

          JSONObject response = xmlToJson.toJson();
          Log.i("response: ", response.toString());

          getjson.getJSON(response);


        } catch (IOException e) {
          e.printStackTrace();
        } finally {
          if (in != null) {
            try {
              in.close();
            } catch (IOException e) {
              e.printStackTrace();
            }
          }
        }
      }
    });
  }

当应用程序的主线程阻塞时间过长时出现此对话框。所以尝试使用 ASYNCTASK 来避免这种暂停。