android - 如何在 Fragment 中显示 ProgressDialog 以供下载

标签 android android-fragments download progressdialog

我想在 Fragment 中显示下载进度的进度对话框,但我无法显示该对话框。我可以下载图片但不显示 ProgressDialog。这是我的代码:

import android.app.Dialog;
import android.app.ProgressDialog;

import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.rengwuxian.materialedittext.MaterialEditText;
import com.rey.material.widget.SnackBar;



import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

import static java.lang.Integer.*;


public class PicFragment extends Fragment {


    private static Button btndownload;
    private static MaterialEditText address;
    private static MaterialEditText name;
    private static SnackBar CheckNetSnack;
    private RelativeLayout relativeLayout;
    private static ImageView dlimg;
    private ProgressDialog pDialog;
    public static final int progress_bar_type = 0;

    // File url to download
    private static String file_url = "http://api.androidhive.info/progressdialog/hive.jpg";


    public PicFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_pic, container, false);

        relativeLayout = (RelativeLayout) view.findViewById(R.id
                .relativeLayout);

        dlimg = (ImageView) view.findViewById(R.id.dlimg);

        btndownload = (Button) view.findViewById(R.id.download);
        btndownload.setTypeface(Typeface.createFromAsset(getActivity().getAssets(), "fonts/iraniansans.ttf"));
        btndownload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Toast.makeText(getContext(), "Net is Ok", Toast.LENGTH_SHORT).show();
               new DownloadFileFromURL().execute("http://dl.esfandune.ir/android/esfandune.jpg");

                //new NetCheck().execute();

            }
        });

        address = (MaterialEditText) view.findViewById(R.id.addresEdittext);
        address.setTypeface(Typeface.createFromAsset(getActivity().getAssets(), "fonts/iraniansans.ttf"));


        return view;
    }
    /**
     * Showing Dialog
     * */
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case progress_bar_type:
                pDialog = new ProgressDialog(getActivity().getBaseContext());
                pDialog.setMessage("Downloading file. Please wait...");
                pDialog.setIndeterminate(false);
                pDialog.setMax(100);
                pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                pDialog.setCancelable(true);
                pDialog.show();
                return pDialog;
            default:
                return null;
        }
    }
    /**
     * Background Async Task to download file
     * */
     class DownloadFileFromURL extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread
         * Show Progress Bar Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
          getActivity().showDialog(progress_bar_type);
            
            }


        /**
         * Downloading file in background thread
         * */
        @Override
        protected String doInBackground(String... f_url) {
            int count;
            try {
                URL url = new URL(f_url[0]);
                URLConnection conection = url.openConnection();
                conection.connect();
                // getting file length
                int lenghtOfFile = conection.getContentLength();

                // input stream to read file - with 8k buffer
                InputStream input = new BufferedInputStream(url.openStream(), 8192);

                // Output stream to write file
                OutputStream output = new FileOutputStream("/sdcard/downloadedfile.jpg");

                byte data[] = new byte[1024];

                long total = 0;

                while ((count = input.read(data)) != -1) {
                    total += count;
                    // publishing the progress....
                    // After this onProgressUpdate will be called
                    publishProgress(""+(int)((total*100)/lenghtOfFile));

                    // writing data to file
                    output.write(data, 0, count);
                }

                // flushing output
                output.flush();

                // closing streams
                output.close();
                input.close();

            } catch (Exception e) {
                Log.e("Error: ", e.getMessage());
            }

            return null;
        }

        /**
         * Updating progress bar
         * */
        protected void onProgressUpdate(String... progress) {
            // setting progress percentage
           pDialog.setProgress(Integer.parseInt(progress[0]));
        }

        /**
         * After completing background task
         * Dismiss the progress dialog
         * **/
        @Override
        protected void onPostExecute(String file_url) {
            // dismiss the dialog after the file was downloaded
           getActivity().dismissDialog(progress_bar_type);

            // Displaying downloaded image into image view
            // Reading image path from sdcard
            String imagePath = Environment.getExternalStorageDirectory().toString() + "/downloadedfile.jpg";
            // setting downloaded into image view
            dlimg.setImageDrawable(Drawable.createFromPath(imagePath));
        }

    }
}

当我使用这个 whitout fragment 时它是有效的但是我无法运行它的 fragment

最佳答案

创建进度对话框 fragment :

import android.app.Dialog;
import android.app.DialogFragment;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;

public class ProgressDialogFragment extends DialogFragment
{
    public ProgressDialogFragment(Context context, String progressText, ProgressDialogCancellationSignal handler) 
    {
        mContext = context;
        mProgressText = progressText;
        mProgressDialogCancelHandler = handler;
    }

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) 
    {
        ProgressDialog progressDialog = new ProgressDialog(mContext, ProgressDialog.THEME_HOLO_LIGHT);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setCancelable(mProgressDialogCancelHandler == null ? false : false);
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.setIndeterminate(true);
        if (mProgressText != null)
        {
            progressDialog.setMessage(mProgressText);
        }
        return progressDialog;  
    }

    @Override
    public void onCancel(DialogInterface dialog) 
    {
        if (mProgressDialogCancelHandler != null)
        {
            mProgressDialogCancelHandler.onCancel();
        }
        super.onCancel(dialog);
    }

    /**
     * Used to set progress in progress dialog at runtime 
     * @param totalProgress : total progress done till now on the given task
     * @param totalValue    : total value of the given task
     * @param units         : measurement unit of progress of given task
     */
    public void setProgress(String totalProgress, String totalValue, String units)
    {
        Dialog dialog = getDialog();
        if (dialog instanceof ProgressDialog && mProgressText != null)
        { 
            ((ProgressDialog) dialog).setMessage(mProgressText + " " + totalProgress + units + " / " + totalValue + units);
        }
    }

    private String mProgressText;
    private Context mContext;
    private ProgressDialogCancellationSignal mProgressDialogCancelHandler; 

    public interface ProgressDialogCancellationSignal
    {
        void onCancel();
    }
}

在你的 DownloadFileFromURL 里面类有两个这样的方法:

@Override
public void showProgress()
{
    if (mProgressFragment == null)
    {
        mProgressFragment =  new ProgressDialogFragment(<your Activity>.this, 
                "text string", null);
    }
    mProgressFragment.setCancelable(false);
    mProgressFragment.show(<YourActivity>.this.getFragmentManager(), PROGRESS_DIALOG_TAG);
}

@Override
public void dismissProgress()
{
    if (mProgressFragment != null)
    {

        if (mProgressFragment.isAdded())
        {
            mProgressFragment.dismissAllowingStateLoss();
        }
        mProgressFragment = null;
    }
}

private DialogFragment mProgressFragment;
private static final String PROGRESS_DIALOG_TAG = "ProcessProgressDialog";

现在onPreExecute AsyncTask的方法|调用showProgress对话方法和onPostExecute AsyncTask的方法|调用dismissProgress对话方法和onProgressUpdate方法调用 setProgressMethod() .

编辑 1 您的 AsyncTask 将如下所示:

/**
 * Background Async Task to download file
 * */
class DownloadFileFromURL extends AsyncTask<String, String, String> {
    private DialogFragment mProgressFragment;
    private static final String PROGRESS_DIALOG_TAG = "ProcessProgressDialog";
    /**
     * Before starting background thread
     * Show Progress Bar Dialog
     * */
    public void showProgress()
    {
        if (mProgressFragment == null)
        {
            mProgressFragment =  new ProgressDialogFragment(PicFragment.this.getActivity(), 
                    "downloading...", null);
        }
        mProgressFragment.setCancelable(false);
        mProgressFragment.show(PicFragment.this.getActivity().getFragmentManager(), PROGRESS_DIALOG_TAG);
    }
    @Override
    public void dismissProgress()
    {
        if (mProgressFragment != null)
        {
            if (mProgressFragment.isAdded())
            {
                mProgressFragment.dismissAllowingStateLoss();
            }
            mProgressFragment = null;
        }
    }
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        showProgress();
    }
    /**
     * Downloading file in background thread
     * */
    @Override
    protected String doInBackground(String... f_url) {
        int count;
        try {
            URL url = new URL(f_url[0]);
            URLConnection conection = url.openConnection();
            conection.connect();
            // getting file length
            int lenghtOfFile = conection.getContentLength();
            // input stream to read file - with 8k buffer
            InputStream input = new BufferedInputStream(url.openStream(), 8192);
            // Output stream to write file
            OutputStream output = new FileOutputStream("/sdcard/downloadedfile.jpg");
            byte data[] = new byte[1024];
            long total = 0;
            while ((count = input.read(data)) != -1) {
                total += count;
                // publishing the progress....
                // After this onProgressUpdate will be called
                publishProgress(""+(int)((total*100)/lenghtOfFile));
                // writing data to file
                output.write(data, 0, count);
            }
            // flushing output
            output.flush();
            // closing streams
            output.close();
            input.close();
        } catch (Exception e) {
            Log.e("Error: ", e.getMessage());
        }
        return null;
    }
    /**
     * Updating progress bar
     * */
    protected void onProgressUpdate(String... progress) {
        // setting progress percentage
        mProgressFragment.setProgress(<total progress >, progress[0], "<units> example KB or MB");
    }
    /**
     * After completing background task
     * Dismiss the progress dialog
     * **/
    @Override
    protected void onPostExecute(String file_url) {
        // dismiss the dialog after the file was downloaded
        dismissProgress();
        // Displaying downloaded image into image view
        // Reading image path from sdcard
        String imagePath = Environment.getExternalStorageDirectory().toString() + "/downloadedfile.jpg";
        // setting downloaded into image view
        dlimg.setImageDrawable(Drawable.createFromPath(imagePath));
    }
}

关于android - 如何在 Fragment 中显示 ProgressDialog 以供下载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34254382/

相关文章:

android - 图库一次滚动一张图片

android - IllegalStateException: Activity 已被销毁 - 当应用程序再次尝试显示 DialogFragment 时

android - 旋转后所有 fragment 可见

Android:切换 fragment 后按钮 onClicklistener 不起作用

javascript - 将 Canvas 元素下载到图像

Android 架构组件 - ViewModel Observable & Proguard

android - 使用全屏隐藏 android 4.4+ 或 kitkat 中的状态栏

linux - wget附加已经下载的文件并跳过完成

php - CSV 文件作为页面打开

java - 无法在 AsyncTask 中为 ProgressDialog 调用 Looper.prepare() 的线程内创建处理程序