如何添加下载取消按钮以在安卓应用程序中下载进度



我想让用户能够取消下载。我的下载和进度条运行良好。我希望能够添加取消下载。这是我的活动类代码:

package com.afromusics.afromusic;
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 android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class DownloadActivity extends ActionBarActivity {
    public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
    private Button startBtn;
    private ProgressDialog mProgressDialog;
    private final String KEY_TITLE = "Afromusics_file";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_download);

        TextView titlema = (TextView) findViewById(R.id.textView1);
        Intent intenttitle = getIntent();
        String titlem = intenttitle.getStringExtra("blogTitleKey");
        titlema.setText(titlem);
         startBtn = (Button)findViewById(R.id.startBtn);
            startBtn.setOnClickListener(new OnClickListener(){
                public void onClick(View v) {
                    startDownload();
                }
            });
    }
     private void startDownload() {
            Intent intent = getIntent();
            Uri fileUri = intent.getData();
            String url = fileUri.toString();
            new DownloadFileAsync().execute(url);

        }
        @Override
        protected Dialog onCreateDialog(int id) {
            switch (id) {
            case DIALOG_DOWNLOAD_PROGRESS:
                mProgressDialog = new ProgressDialog(this);
                mProgressDialog.setMessage("Downloading file..");
                mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                mProgressDialog.setCancelable(false);
                mProgressDialog.show();
                return mProgressDialog;
            default:
                return null;
            }
        }
    class DownloadFileAsync extends AsyncTask<String, String, String> {
        @SuppressWarnings("deprecation")
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            showDialog(DIALOG_DOWNLOAD_PROGRESS);

        }
        @Override
        protected String doInBackground(String... aurl) {
            int count;
        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);
        //Randow Number Works perfect
        //Random r = new Random();
        //int i1 = r.nextInt(80 - 65) + 65;
        Intent intenttitle = getIntent();
        String titlem = intenttitle.getStringExtra("blogTitleKey");
        InputStream input = new BufferedInputStream(url.openStream());
        OutputStream output = new FileOutputStream("/sdcard/Music/ " + titlem + ".mp3");
        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) {
             Log.d("ANDRO_ASYNC",progress[0]);
             mProgressDialog.setProgress(Integer.parseInt(progress[0]));
        }
        @SuppressWarnings("deprecation")
        @Override
        protected void onPostExecute(String unused) {
            dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
        }
    }
    }

这是活动文件:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/cream_dustapp"
    tools:context="com.afromusics.afromusic.DownloadActivity" >
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="32sp" />
    <Button
        android:id="@+id/startBtn"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView1"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="18dp"
        android:text="@string/download_btn" />

</RelativeLayout>

我认为拿督的答案并不完全是你想要的。它只是取消进度条。要停止异步任务,我会这样做:

向活动添加全局变量

private boolean running = false;

然后在您的onCreateDialog方法中,在以下行之间添加以下内容:

mProgressDialog.setCancelable(true);
running = true;
mProgressDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            //Cancel download task
            running = false;
            mProgressDialog.cancel();
        }
    });
mProgressDialog.show();

最后,在您的 AsyncTask 的doInBackground方法中更改以下行:

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

这些将完成 AsyncTask 或更精确的 while 循环。确保您正在处理进度对话框上的每个帖子操作,例如在OnPostDialog右侧关闭。例如:对话框将已关闭。

希望这有帮助!

使用此示例。

public class Test extends Activity
{
    public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
    private Button startBtn;
    private ProgressDialog mProgressDialog;
    private final String KEY_TITLE = "Afromusics_file";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mProgressDialog.setCancelable(true);
        mProgressDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //Cancel download task
                mProgressDialog.cancel();
            }
        });
    }
}

最新更新