代码之家  ›  专栏  ›  技术社区  ›  Abhishek

在android中从服务器下载内容时屏幕冻结

  •  -1
  • Abhishek  · 技术社区  · 6 年前

    我在MainActivity中从服务器下载JSON内容,并将JSON从MainActivity传递到ListActivity,这里的问题是我在后端服务器(即从中获取数据的Php)中添加了10秒的睡眠时间。因为,响应将延迟,我希望屏幕打开并等待,直到响应到来并移动到下一个屏幕。 但现在的情况是,屏幕完全变白/变黑,直到收到响应并加载ListActivity,这里的问题是MainActivity永远不可见。以下是相同的代码:

    主要活动

    JSONData jsonData = new JSONData();
    String jsonList = jsonData.fetchList();
    
    Intent intent = new Intent(getApplicationContext(),ListActivity.class);
    intent.putExtra("jsonList",jsonList);
    startActivity(intent);
    finish();
    

    JSON数据类

    public String fetchList() {
            try {
                String list = new DownloadJSONData().execute(listURL).get().toString();
                return list;
            } catch (Exception e) {
                return "";
            }
        }
    
    private class DownloadJSONData extends AsyncTask<String, String, String> {
            protected void onPreExecute() {
                super.onPreExecute();
            }
    
            protected String doInBackground(String... params) {
    
                HttpURLConnection connection = null;
                BufferedReader reader = null;
                try {
                    URL url = new URL(params[0]);
                    connection = (HttpURLConnection) url.openConnection();
                    connection.connect();
                    InputStream stream = connection.getInputStream();
                    reader = new BufferedReader(new InputStreamReader(stream));
                    StringBuffer buffer = new StringBuffer();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        buffer.append(line + "\n");
                    }
                    return buffer.toString();
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (connection != null) {
                        connection.disconnect();
                    }
                    try {
                        if (reader != null) {
                            reader.close();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                return "";
            }
    
            @Override
            protected void onPostExecute(String result) {
                super.onPostExecute(result);
            }
        }
    
    1 回复  |  直到 6 年前
        1
  •  2
  •   Emdad Hossain    6 年前

    您正在使用get()方法,该方法在异步任务完成之前访问主线程或ui线程

    您应该避免使用get()并且还可以使用onPreExecute中的progress对话框在对用户的网络调用中显示进度