user1424489
user1424489

Reputation: 63

how to know if download finishes in android development

I'm using the following code to download a pdf from a list of pdfs depending on which is selected. I want to then open the pdf downloaded. The problem is that the code to open the pdf occurs before the download is finished. How do I make it so that the code to open the pdf doesn't run until the download is finished.....

Note: the reason i'm reading in the pdf originally as a text/html is because I originally have the pdf as a website url and then it automatically downloads when opened in a url.

  public class pdfSelectedListener implements OnItemClickListener{

    @Override
    public void onItemClick(AdapterView<?> parent,
            View view, int pos, long id) {
        String pdfName = "";

        for(int i=0;i<nameList.size();i++){
            if(nameList.get(i).equals(parent.getItemAtPosition(pos).toString())){
                try{
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setDataAndType(Uri.parse(websiteList.get(i)), "text/html");


                int slashIndex = websiteList.get(i).lastIndexOf('/');
                pdfName = websiteList.get(i).substring(slashIndex+1, websiteList.get(i).length());

                startActivity(intent);
                }catch(Exception e){
                    Toast.makeText(PDFActivity.this, "Invalid link.", Toast.LENGTH_LONG).show();
                }
            }
        }

//I dont want the the following code to excute until the above code is done downloading the pdf from the internet.

                    File file = new File("/mnt/sdcard/Download/"+pdfName);
                        if (file.exists()) {
                            Uri path = Uri.fromFile(file);
                            Intent intent = new Intent(Intent.ACTION_VIEW);
                            intent.setDataAndType(path, "application/pdf");
                            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

                            try {
                                startActivity(intent);
                            } 
                            catch (ActivityNotFoundException e) {
                                Toast.makeText(PDFActivity.this, 
                                    "No Application Available to View PDF", 
                                    Toast.LENGTH_SHORT).show();
                            }
                        }else{
                            Toast.makeText(PDFActivity.this, 
                                    "File doesn't exist.", 
                                    Toast.LENGTH_SHORT).show();
                        }
        }
    }   

Upvotes: 2

Views: 643

Answers (2)

Venky
Venky

Reputation: 11107

Use AsyncTask and show the download progress in a dialog

// declare the dialog as a member field of your activity
ProgressDialog mProgressDialog;

// instantiate it within the onCreate method
mProgressDialog = new ProgressDialog(YourActivity.this);
mProgressDialog.setMessage("A message");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

// execute this when the downloader must be fired
DownloadFile downloadFile = new DownloadFile();
downloadFile.execute("the url to the file you want to download");

The AsyncTask will look like this:

private class DownloadFile extends AsyncTask<String, Integer, String> {
@Override
protected String doInBackground(String... sUrl) {
    try {
        URL url = new URL(sUrl[0]);
        URLConnection connection = url.openConnection();
        connection.connect();
        // this will be useful so that you can show a typical 0-100% progress bar
        int fileLength = connection.getContentLength();

        // download the file
        InputStream input = new BufferedInputStream(url.openStream());
        OutputStream output = new FileOutputStream("/sdcard/file_name.extension");

        byte data[] = new byte[1024];
        long total = 0;
        int count;
        while ((count = input.read(data)) != -1) {
            total += count;
            // publishing the progress....
            publishProgress((int) (total * 100 / fileLength));
            output.write(data, 0, count);
        }

        output.flush();
        output.close();
        input.close();
    } catch (Exception e) {
    }
    return null;
}

The method above (doInBackground) runs always on a background thread. You shouldn't do any UI tasks there. On the other hand, the onProgressUpdate and onPreExecute run on the UI thread, so there you can change the progress bar:

@Override
protected void onPreExecute() {
    super.onPreExecute();
    mProgressDialog.show();
}

@Override
protected void onProgressUpdate(Integer... progress) {
    super.onProgressUpdate(progress);
    mProgressDialog.setProgress(progress[0]);
}

}

For further reference check link Possible ways to download files and show Progress.

Upvotes: 1

Paresh Mayani
Paresh Mayani

Reputation: 128428

You should implement AsyncTask for downloading PDF files.

  • Inside doInBackground(), download PDF files
  • Inside onPostExecute(), do whatever you want to do for downloaded PDFs.

Upvotes: 1

Related Questions