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

时间:2014-11-20 06:34:01

标签: android

我想让用户能够取消下载。我的下载和进度条工作得很好。我希望能够添加取消下载..这是我的活动类代码:

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>

2 个答案:

答案 0 :(得分:2)

我认为数据答案并不完全符合您的要求。它只是取消了ProgressBar。要停止Asynctask,我会这样做:

向您的活动添加全局变量

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循环。确保您正在处理ProgressDialog上的每个帖子操作,例如在您的OnPostDialog权限中解除。例如:Dialog将被解雇。

希望这有帮助!

答案 1 :(得分:0)

使用此示例。

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