For long-running operations, use: AsyncTask Example of implementing the Post request, where we get the answer in data. Of course, this is not a downloader for me, but you can change it to fit your needs.
private static class SendLoginData extends AsyncTask<String, String, String> { @Override protected String doInBackground(String... urls) { try { String myURL = urls[0]; String request = urls[1]; byte[] data; InputStream is; try { URL url = new URL(myURL); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestProperty("Content-Length", "" + Integer.toString(request.getBytes().length)); OutputStream os = conn.getOutputStream(); data = request.getBytes("UTF-8"); os.write(data); conn.connect(); int responseCode= conn.getResponseCode(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); if (responseCode == 200) { is = conn.getInputStream(); byte[] buffer = new byte[8192]; int bytesRead; while ((bytesRead = is.read(buffer)) != -1) { baos.write(buffer, 0, bytesRead); } data = baos.toByteArray(); return new String(data, "UTF-8"); } } catch (Exception ignored) {} } catch (Exception ignored) {} return null; } }
If you need to communicate with the user during operation, here is an approximate scheme:
private class MyAsyncTask extends AsyncTask<String, Integer, Integer> { @Override protected void onProgressUpdate(Integer... progress) { // [... Обновите индикатор хода выполнения, уведомления или другой // элемент пользовательского интерфейса ...] } @Override protected void onPostExecute(Integer... result) { // [... Сообщите о результате через обновление пользовательского // интерфейса, диалоговое окно или уведомление ...] } @Override protected Integer doInBackground(String... parameter) { int myProgress = 0; // [... Выполните задачу в фоновом режиме, обновите переменную myProgress...] publishProgress(myProgress); // [... Продолжение выполнения фоновой задачи ...] // Верните значение, ранее переданное в метод onPostExecute return result; } }