Search code examples
androidmultithreadingandroid-activityresume

Android: how to resume main thread after download is finished


What can I do, if I'm in any Activity and I want download a file (using thread) and at same time I want the main thread waits until download is finished?


Solution

  • Use AsyncTask.. from activity

    new DownloadTask(this).execute();
    

    The task for example:

    public class DownloadTask extends AsyncTask<Void, Void, String>  {
    
    private ProgressDialog progressDialog;  
    private Context context;
    
    /**
     * 
     * @param context
     * @param pdfDoc the document of the PDF
     */
    public DownloadTask(Context context) {
        this.context = context;
    
        progressDialog = new ProgressDialog(context);
    }
    
    @Override
    protected void onPreExecute() {  
            progressDialog.setMessage("Downloading...");
            progressDialog.setIndeterminate(true);
            progressDialog.show();
    }
    
    @Override
    protected String doInBackground(Void... arg0) {
        //download here
    }
    
    @Override
    protected void onPostExecute(final String result) {
            progressDialog.dismiss();
    
    }
    }