使用BufferedReader时,AsyncTask publishProgress不会在onProgressUpdate上更新

时间:2018-03-30 15:14:46

标签: android android-asynctask bufferedreader async-onprogressupdate

我想更新进度对话框的下载进度,但AsyncTask在使用 BufferedReader 时会挂起。未调用 publishProgress 而未在 onProgressUpdate 中更新进度对话框。此外,它不会在循环中打印Log。

我已经使用打印测试登录我的代码。

  • First Log正在LogCat
  • 打印
  • 第二个日志未打印
  • 第三个日志也不打印而不执行方法 的 publishProgress

    private class GetData extends AsyncTask<String, Integer, String>{
        private ProgressDialog dialog;
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
    
            dialog = new ProgressDialog(HomeScreen.this);
            dialog.setTitle("Be Patient");
            dialog.setMessage("Loading data for first time use only. Please don't close the application.");
            dialog.setCancelable(false);
            dialog.setIndeterminate(true);
            dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            dialog.show();
        }
    
        @Override
        protected void onProgressUpdate(Integer... progress) {
            super.onProgressUpdate(progress);
    
            dialog.setIndeterminate(false);
            dialog.setMax(100);
            dialog.setProgress(progress[0]);
        }
    
        @Override
        protected String doInBackground(String... params) {
    
            String serverResponse = null;
            BufferedReader in = null;
            java.net.URL myLink;
    
            try {
                Log.e("AsyncTask", "This log is printing");
                myLink = new java.net.URL(params[0]);
                in = new BufferedReader(new InputStreamReader(myLink.openStream()));
                Log.e("AsyncTask", "This log not printing");
                String inputLine;
                StringBuilder response = new StringBuilder();
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                    publishProgress(50);  // Not executing : Default value set is 50 just for cheecking.
                    Log.d("AsyncTask", "This log also not printing & publishProgress not executing");
                }
                serverResponse = response.toString();
    
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (in != null) in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return serverResponse;
        }
    
        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
    
            if (!HomeScreen.this.isFinishing() && dialog != null) {
                dialog.dismiss();
            }
        }
    }
    

0 个答案:

没有答案