Good day. I am writing an Android application, you need to connect via the Internet and get data from the server. Data loading was done through AsyncTask, but at runtime AsyncTask the main thread is blocked.

private void doit () { //Загружаем данные через интернет String resp = ""; //То, что скачали с интернета pd = new ProgressDialog(this); //Инициализация прогресс диалога try { //Запускаем новый поток GetHTTPResponseTask task = new GetHTTPResponseTask(); task.execute(); resp = task.get(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); resp = "Error"; } catch (ExecutionException e) { // TODO Auto-generated catch block e.printStackTrace(); resp = "Error"; } Toast.makeText(this, resp, Toast.LENGTH_LONG).show(); } 

Class AsyncTask

 //Этот класс находится в том же классе, что и текущая Activity private class GetHTTPResponseTask extends AsyncTask<Void, Void, String> { @Override protected void onPreExecute() { // TODO Auto-generated method stub super.onPreExecute(); pd.setTitle("Авторизация"); pd.setMessage("Заходим..."); pd.show(); //Запускаем прогресс диалог } @Override protected String doInBackground(Void... p) { // TODO Auto-generated method stub String _text = ""; //Для возврата результата HttpURLConnection cn = null; try { //Что-нибудь подлиннее, чтобы показать, насколько всё плохо URL url = new URL("http://dl.zaycev.net/127833/2206682/ruki_vverkh_-_ruki_vverkh_(zaycev.net).mp3"); cn = (HttpURLConnection)url.openConnection(); cn.setRequestMethod("GET"); cn.setRequestProperty("Accept-Charset", "UTF-8"); cn.setRequestProperty("Content-Type", "text/plain; charset=utf-8"); cn.setConnectTimeout(5000); cn.setReadTimeout(7000); cn.connect(); InputStream in = cn.getInputStream(); StringBuffer bf = new StringBuffer(); BufferedReader br = new BufferedReader(new InputStreamReader(in)); String line; //Построчное чтение while ((line = br.readLine()) != null) { bf.append(line); } _text = bf.toString(); cn.disconnect(); } catch (MalformedURLException e) { _text = "Error"; } catch (UnknownHostException e) { _text = "Error"; } catch (FileNotFoundException e) { // TODO Auto-generated catch block _text = "Error"; } catch (IOException e) { e.printStackTrace(); _text = "Error"; } return _text; } @Override protected void onPostExecute(String result) { // TODO Auto-generated method stub super.onPostExecute(result); pd.dismiss(); //Закрываем прогресс диалог } } 

Did as described in the examples on many sites, the result is the same, 2 problems:

  1. The main thread UI hangs, although in debug it shows what it does in a separate thread;

  2. ProgressDialog does not appear while loading a large file. On the virtual device, you can see that it appeared after the download. If you comment out the pd.Dismiss () line, then ProgressDialog starts up before the file starts to download, but does not stop.

Has anyone encountered such problems?

Thread list. List of threads

  • The get() method of AsyncTask-a blocks the main thread until a result is obtained. You need to use the onPostExecute() override onPostExecute() see these answers - pavlofff pm
  • @pavlofff Thank you, corrected, now everything works fine;) - Konstantin Poltaratsky

1 answer 1

Your main thread has a get method that waits for AsynTask to complete its work and returns the result. To get the result, use a listener or use the Loader instead of AsynkTask. And no need to show extra code that does not apply to the issue.

  • Thanks, already answered above;) I didn’t know which one was superfluous, so I threw off more and with comments - Konstantin Poltaratsky