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

时间:2018-08-18 09:12:20

标签: android android-asynctask android-json

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

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 个答案:

答案 0 :(得分:2)

您正在使用get()方法来获取主线程或ui线程,直到异步任务完成

您应该避免使用get(),还可以使用onPreExecute中的进度对话框在向用户的网络通话中显示进度

相关问题