【问题标题】:How to use Asynchronous task for download progress dialog in fragment?如何在片段中使用异步任务进行下载进度对话框?
【发布时间】:2017-03-08 17:35:39
【问题描述】:

在我的应用程序中,当我单击文件时,它将开始从服务器下载,进度将显示在手机状态栏中。但我希望进度条显示在我的应用程序屏幕上。

我点击了这个链接:-

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

在处理问题陈述时,我遇到了这些SYSTEM_DOWNLOADERAPP_DOWNLOADER

  1. 这些到底是做什么的?

  2. 上面的例子是在activity中调用的。我想知道如何在片段中调用带有下载进度条的异步任务。

我正在编辑问题以进行澄清,请帮助

        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();
        }
    }

当我点击文件时,应用程序强制停止。我在做什么错误?请帮助我。谢谢

【问题讨论】:

  • 您可以使用ProgressBarProgressDialog 直到您的文件正在下载。
  • 所以我需要知道这两件事的区别
  • 如果您使用DownloadManager,那么您的进度将显示在通知栏中,直到您的文件下载,如果您在AsyncTask 中使用ProgressBarProgressDialog,那么它将在AsyncTaskonPostExecuted() 方法中被解雇
  • 我已经编辑了我的问题陈述。检查它并告诉我代码出了什么问题!

标签: android android-download-manager


【解决方案1】:

我自己找到了答案。希望对任何人都有帮助。

我想在片段中调用异步任务并希望显示进度对话框,它将以百分比显示下载文件的进度。

1> 我在课堂上调用了异步任务。

DownloadTask.java 类

//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>我将 DownloadTask.java 类文件中的这个下载方法调用到我的片段活动中,像这样

// 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);
                }

【讨论】:

    猜你喜欢
    • 2017-05-10
    • 2012-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多