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

How can I show a ProgressDialog in Fragment for download

我想在 Fragment 中显示下载进度的进度对话框,但我无法显示 dialog.I 可以下载图片,但没有显示 ProgressDialog.There 是我的代码:

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 片段时,它可以工作,但按片段我不能 运行 它

正在创建进度对话框片段:

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 class 里面有两个这样的方法:

@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";

现在AsyncTaskonPreExecute方法调用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));
    }
}