Search code examples
androidandroid-download-manager

How to use Asynchronous task for download progress dialog in fragment?


In my application,when i click on file it will start downloading from server and progress will be shown in phone status bar.But i want progress bar to be shown on my application screen itself.

I followed this link :-

http://www.androidhive.info/2012/04/android-downloading-file-by-showing-progress-bar/

While approaching problem statement i come across these SYSTEM_DOWNLOADER and APP_DOWNLOADER .

  1. What these exactly do ?

  2. Above example is called in activity.I wanted to know how to call Asynch task with download progress bar in fragment.

I am editing question for clarification,Please help

        convertView.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                MoodleModule module = listObjects.get(position).module;
                if (module == null)
                    return;
                Intent i = new Intent(context, AppBrowserActivity.class);

                String modurl = module.getUrl();
                String courseurl = session.getmUrl()
                        + "/course/view.php?id=" + courseid;
                modurl = (modurl == null) ? courseurl : modurl;
                i.putExtra("url", modurl);

                if (!module.getModname().contentEquals("resource")) {
                    context.startActivity(i);
                    return;
                }

                if (module.getContents() == null) {
                    context.startActivity(i);
                    return;
                }

                if (module.getContents().isEmpty()) {
                    context.startActivity(i);
                    return;
                }

                MoodleModuleContent content = module.getContents().get(0);
                String path = "/s" + session.getCurrentSiteId() + "c"
                        + courseid + "/";
                File file = new File(Environment
                        .getExternalStoragePublicDirectory("/MDroid")
                        + path + content.getFilename());
                 //TODO here
                // Download if file doesn't already exist
                if (!file.exists()) {
                    String fileurl = content.getFileurl();
                    fileurl += "&token=" + session.getToken();
                    fName=content.getFilename();

                //FROM HERE I AM CALLING ASYNCHRONOUS TASK
                    startDownload();


                } else {
                    FileOpener.open(context, file);
                }

            }
        });

        return convertView;
    }

    private void startDownload() {
        String url = "http://farm1.static.flickr.com/114/298125983_0e4bf66782_b.jpg";
        new DownloadFileAsync().execute(url);
    }

    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case DIALOG_DOWNLOAD_PROGRESS:
                mProgressDialog = new ProgressDialog(getActivity());
                mProgressDialog.setMessage("Downloading file..");
                mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                mProgressDialog.setCancelable(false);

                return mProgressDialog;
            default:
                return null;
        }
    }
    class DownloadFileAsync extends AsyncTask<String, String, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            /*mProgressDialog = new ProgressDialog(getActivity());
            mProgressDialog.setMessage("Downloading file.");
            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            mProgressDialog.setCancelable(false);
            mProgressDialog.show();*/
            /*showDialog(DIALOG_DOWNLOAD_PROGRESS);*/

            mProgressDialog.show();
        }

        @Override
        protected String doInBackground(String... aurl) {
            int count;
            /*String fName=content.getFilename();*/
            /*InputStream input = null;
            OutputStream output = null;*/
            HttpURLConnection connection = null;
            try {

                URL url = new URL(aurl[0]);
                URLConnection conexion = url.openConnection();
                conexion.connect();

                int lenghtOfFile = conexion.getContentLength();
                Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);

           /* File f = new File(Environment.getExternalStorageDirectory()
                    + "/sdcard/");
            f.mkdirs();*/

                InputStream input = new BufferedInputStream(url.openStream());
                OutputStream output = new FileOutputStream("/sdcard/some_photo_from_gdansk_poland.jpg");

                byte data[] = new byte[1024];

                long total = 0;

                while ((count = input.read(data)) != -1) {
                    total += count;
                    publishProgress(""+(int)((total*100)/lenghtOfFile));
                    output.write(data, 0, count);
                }

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

        }
        protected void onProgressUpdate(String... progress) {

            mProgressDialog.setProgress(Integer.parseInt(progress[0]));
       /* mProgressDialog.dismiss();*/
        }

        @Override
        protected void onPostExecute(String unused) {
        /*dismissDialog(DIALOG_DOWNLOAD_PROGRESS);*/
            mProgressDialog.dismiss();
        }
    }

When i click on file,app gives force stop.what mistake i am doing??Please help me out.thanks


Solution

  • I found answer on my own.Hope it will help anybody.

    I wanted to call asynch task in fragment and wanted to show progress diolog which will show progress of downloading file in percentage.

    1> I called asynch task in class .

    DownloadTask.java class

    //This is important
    public DownloadTask(Context context) {
        this.context = context;
        mProgressDialog = new ProgressDialog(context);
    
        mProgressDialog.setMessage("Downloading file..");
        mProgressDialog.setIndeterminate(false);
        mProgressDialog.setMax(100);
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        mProgressDialog.setCanceledOnTouchOutside(false);
    }
    
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public void download(String fileUrl, String filepath, String fileName,
                         Boolean visibility, Boolean choice) {
        // Make directories if required
        this.fileUrl=fileUrl;
        this.filepath=filepath;
        this.fileName=fileName;
        this.visibility=visibility;
        File f = new File(
                Environment.getExternalStoragePublicDirectory("/MDroid")
                        + filepath);
        if (!f.exists())
            f.mkdirs();
    
    
        if (choice == SYSTEM_DOWNLOADER) {
    
            String url=fileUrl;
            new MyAsyncTask().execute(url);
    
        } else {
            mdroidDownload(fileUrl, fileName);
            reqId =0;
        }
    
    }
    
    class MyAsyncTask extends AsyncTask<String, String, Void> {
    
        boolean running;
    
    
        @Override
        protected Void doInBackground(String...fUrl) {
            int count;
    
    
            InputStream input = null;
            OutputStream output = null;
            HttpURLConnection connection = null;
            try {
    
                URL url = new URL(fUrl[0]);
                connection = (HttpURLConnection) url.openConnection();
                connection.connect();
    
                int lenghtOfFile = connection.getContentLength();
    
                // download the file
                input = connection.getInputStream();
                output = new FileOutputStream(
                        Environment.getExternalStorageDirectory() + "/MDroid/"
                                + fileName);
    
    //#################################
    
        mydownload(fileUrl, filepath, fileName,
            visibility);
    
    
    //##########################################
    
                byte data[] = new byte[4096];
                long total = 0;
                while ((count = input.read(data)) != -1) {
                    total += count;
                    publishProgress(""+(int)((total*100)/lenghtOfFile));
                    output.write(data, 0, count);
                }
    
                output.close();
                input.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
    return null;
    
        }
    
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            running = true;
    
            mProgressDialog.show();
        }
    
        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
    
            mProgressDialog.dismiss();
        }
    
        protected void onProgressUpdate(String... progress) {
    
            // Update the progress dialog
            mProgressDialog.setProgress(Integer.parseInt(progress[0]));
    
        }
    
    
    }
    
    
    
    
    public long mydownload(String fileUrl,String filepath,String fileName,Boolean visibility)
    {
        DownloadManager manager = (DownloadManager) context
                .getSystemService(Context.DOWNLOAD_SERVICE);
    
    /* TODO- Offer better alternative. Only a temporary, quick,
     * workaround for 2.3.x devices. May not work on all sites.
     */
        if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB)
            fileUrl = fileUrl.replace("https://", "http://");
        Request request = new Request(Uri.parse(fileUrl));
        try {
            request.setDestinationInExternalPublicDir("/MDroid", filepath
                    + fileName);
        } catch (Exception e) {
            Toast.makeText(context, "External storage not found!",
                    Toast.LENGTH_SHORT).show();
            return 0;
        }
        request.setTitle(fileName);
        request.setDescription("MDroid file download");
    
        // Visibility setting not available in versions below Honeycomb
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB)
            if (!visibility)
                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN);
            else
                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
    
        // -TODO- save this id somewhere for progress retrieval
        reqId = manager.enqueue(request);
        return reqId;
    }
    

    2>I called this download method from DownloadTask.java class file into my fragment activity like this

    // Download if file doesn't already exist
                    if (!file.exists()) {
                        fileurl = content.getFileurl();
    
                        fileurl += "&token=" + session.getToken();
                        fName = content.getFilename();
    
                        //FROM HERE I AM CALLING ASYNCHRONOUS TASK
    
                        DownloadTask dt = new DownloadTask(context);
                        dt.download(fileurl, path, content.getFilename(), false,
                                DownloadTask.SYSTEM_DOWNLOADER);
    
    
                    } else {
    
                        FileOpener.open(context, file);
                    }