如何取消下载文件当取消按钮onclick在android?

时间:2013-02-25 06:24:38

标签: android download android-asynctask

当下载文件我向用户显示这个progressBar和右边有取消按钮点击然后下载文件取消和SD卡删除下载文件。如何在Android中可能吗?我的代码如下:

public class MyListAdapter extends BaseAdapter {
    private LayoutInflater mInflater;
    //DownloadFileFromURL ddl = new DownloadFileFromURL();
     DownloadFileFromURL ddl;

    public MyListAdapter(Context context) {
        mInflater = LayoutInflater.from(context);
         ddl =  new DownloadFileFromURL();

    }

    public int getCount() {
        return list.size();
    }

    public Object getItem(int position) {
        return position;
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(final int position, View convertView,
            ViewGroup parent) {

        convertView = mInflater.inflate(R.layout.custome_list_view, null);

        final Button cl = (Button) convertView
                .findViewById(R.id.cancle_sedual);
        final Button dl = (Button) convertView
                .findViewById(R.id.download_sedual);
        final ProgressBar pr = (ProgressBar) convertView
                .findViewById(R.id.listprogressbar);
        final ImageView im = (ImageView) convertView
                .findViewById(R.id.list_image);
        im.setImageResource(list.get(position).images[position]);
        getProgress(pr, position, cl, dl);
        // pr.setProgress(getItem(position));
        cl.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                dl.setVisibility(View.VISIBLE);
                cl.setVisibility(View.GONE);
                //ddl.cancel(true);
                //new DownloadFileFromURL().cancel(true);
                 ddl.downloadFile();

            }
        });

        dl.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                str_start = list.get(position).url_video;
                dl.setVisibility(View.GONE);
                cl.setVisibility(View.VISIBLE);
                Log.v("log_tag", "str_start  " + str_start);

                //
                // new DownloadFileFromURL().execute(str_start);
                // new DownloadFileFromURL().execute(pr, str_start,
                // position);
                //ddl.execute(pr, str_start, position);
                 ddl.execute(pr, str_start, position);

            }
        });

        return convertView;
    }
}

class DownloadFileFromURL extends AsyncTask<Object, String, Integer> {

    int count = 0;
    ProgressDialog dialog;
    ProgressBar progressBar;
    int myProgress;
    int position;
     boolean download1 = false;

    /**
     * Before starting background thread Show Progress Bar Dialog
     * */



    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        ProgressBar progressBar;
        download1 = true;

    }



    /**
     * Downloading file in background thread
     * */
    @Override
    protected Integer doInBackground(Object... params) {
        Log.v("log_tag", "params  :::; " + params);
        int count;
        progressBar = (ProgressBar) params[0];
        position = (Integer) params[2];
        try {
            // URL url = new URL(f_url[0]);
            URL url = new URL((String) params[1]);
            Log.v("log_tag", "name  ::: " + url);
            name = ((String) params[1]).substring(((String) params[1])
                    .lastIndexOf("/") + 1);
            Log.v("log_tag", "name Substring ::: " + name);
            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);
            download = new File(Environment.getExternalStorageDirectory()
                    + "/download/");
            if (!download.exists()) {
                download.mkdir();
            }

            String strDownloaDuRL = download + "/" + name;
            Log.v("log_tag", " down url   " + strDownloaDuRL);
            FileOutputStream output = new FileOutputStream(strDownloaDuRL);

            byte data[] = new byte[1024];

            long total = 0;

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

                // writing data to file
                progressBar
                        .setProgress((int) ((total * 100) / lenghtOfFile));
                output.write(data, 0, count);
                setProgress(progressBar, position);
                 }

                 else {
                    break;
                }
            }
            // flushing output
            output.flush();
            if(!this.download1){
                File delete = new File(strDownloaDuRL);
                delete.delete();
                }              
            // closing streams
            output.close();
            input.close();

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

    }
    public void downloadFile(){
           this.download1 = false;
     }

    /**
     * Updating progress bar
     * */
    protected void onProgressUpdate(String... values) {

        super.onProgressUpdate(values);
        Log.v("log_tag", "progress :: " + values);
        // setting progress percentage
        // pDialog.setProgress(Integer.parseInt(progress[0]));
    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {

        Log.v("log", "login  ::: 4::: " + download);
        String videoPath = download + "/" + name;
        String chpName = name;
        Log.v("log_tag", "chpName  ::::" + chpName + "  videoPath "
                + videoPath);
        db.execSQL("insert into videoStatus (chapterNo,videoPath) values(\""
                + chpName + "\",\"" + videoPath + "\" )");

    }

}



private void setProgress(ProgressBar pr, int position) {
    ProgressBarSeek pbarSeek = new ProgressBarSeek();
    pbarSeek.setPosition(position);
    pbarSeek.setProgressValue(pr.getProgress());
    Log.v("log_tag", position + "  progress  " + pr.getProgress());
    progreeSeekList.add(pbarSeek);
}

private void getProgress(ProgressBar pr, int position, Button cl, Button dl) {
    if (progreeSeekList.size() > 0) {
        for (int j = 0; j < progreeSeekList.size(); j++) {
            if (position == progreeSeekList.get(j).getPosition()) {
                pr.setProgress(progreeSeekList.get(j).getProgressValue());
                dl.setVisibility(View.GONE);
                cl.setVisibility(View.VISIBLE);
            }
        }
    }
}

然后我点击取消按钮然后我在下面得到错误:

02-25 12:49:31.109: ERROR/AndroidRuntime(25082): FATAL EXCEPTION: main
02-25 12:49:31.109: ERROR/AndroidRuntime(25082): java.lang.IllegalStateException: Cannot execute task: the task is already running.
02-25 12:49:31.109: ERROR/AndroidRuntime(25082):     at android.os.AsyncTask.execute(AsyncTask.java:380)
02-25 12:49:31.109: ERROR/AndroidRuntime(25082):     at com.example.testhopelistnew.TestHopeListNew$MyListAdapter$2.onClick(TestHopeListNew.java:144)
02-25 12:49:31.109: ERROR/AndroidRuntime(25082):     at android.view.View.performClick(View.java:2485)
02-25 12:49:31.109: ERROR/AndroidRuntime(25082):     at android.view.View$PerformClick.run(View.java:9080)
02-25 12:49:31.109: ERROR/AndroidRuntime(25082):     at android.os.Handler.handleCallback(Handler.java:587)
02-25 12:49:31.109: ERROR/AndroidRuntime(25082):     at android.os.Handler.dispatchMessage(Handler.java:92)
02-25 12:49:31.109: ERROR/AndroidRuntime(25082):     at android.os.Looper.loop(Looper.java:130)
02-25 12:49:31.109: ERROR/AndroidRuntime(25082):     at android.app.ActivityThread.main(ActivityThread.java:3687)
02-25 12:49:31.109: ERROR/AndroidRuntime(25082):     at java.lang.reflect.Method.invokeNative(Native Method)
02-25 12:49:31.109: ERROR/AndroidRuntime(25082):     at java.lang.reflect.Method.invoke(Method.java:507)
02-25 12:49:31.109: ERROR/AndroidRuntime(25082):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
02-25 12:49:31.109: ERROR/AndroidRuntime(25082):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
02-25 12:49:31.109: ERROR/AndroidRuntime(25082):     at dalvik.system.NativeStart.main(Native Method)

2 个答案:

答案 0 :(得分:1)

尝试使用此代码,我将boolean download添加到您的代码true下载文件,否则他就会停止工作

public class MyListAdapter extends BaseAdapter {
        private LayoutInflater mInflater;
        DownloadFileFromURL ddl;

        public MyListAdapter(Context context) {
            mInflater = LayoutInflater.from(context);
            ddl = = new DownloadFileFromURL();
        }

        public int getCount() {
            return list.size();
        }

        public Object getItem(int position) {
            return position;
        }

        public long getItemId(int position) {
            return position;
        }

        public View getView(final int position, View convertView,
                ViewGroup parent) {

            convertView = mInflater.inflate(R.layout.custome_list_view, null);

            final Button cl = (Button) convertView
                    .findViewById(R.id.cancle_sedual);
            final Button dl = (Button) convertView
                    .findViewById(R.id.download_sedual);
            final ProgressBar pr = (ProgressBar) convertView
                    .findViewById(R.id.listprogressbar);
            final ImageView im = (ImageView) convertView
                    .findViewById(R.id.list_image);
            im.setImageResource(list.get(position).images[position]);
            getProgress(pr, position, cl, dl);
            // pr.setProgress(getItem(position));
            cl.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub

                    dl.setVisibility(View.VISIBLE);
                    cl.setVisibility(View.GONE);
                    ddl.downloadFile();


                }
            });

            dl.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    str_start = list.get(position).url_video;
                    dl.setVisibility(View.GONE);
                    cl.setVisibility(View.VISIBLE);
                    Log.v("log_tag", "str_start  " + str_start);

                    //
                    // new DownloadFileFromURL().execute(str_start);
                    // position);
                     ddl.execute(pr, str_start, position);

                }
            });

            return convertView;
        }
    }

    class DownloadFileFromURL extends AsyncTask<Object, String, Integer> {

        int count = 0;
        ProgressDialog dialog;
        ProgressBar progressBar;
        int myProgress;
        int position;
        // Boolean
        boolean download = false;

        /**
         * Before starting background thread Show Progress Bar Dialog
         * */

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            ProgressBar progressBar;
            download = true;

        }

        /**
         * Downloading file in background thread
         * */
        @Override
        protected Integer doInBackground(Object... params) {
            Log.v("log_tag", "params  :::; " + params);
            int count;
            progressBar = (ProgressBar) params[0];
            position = (Integer) params[2];
            try {
                // URL url = new URL(f_url[0]);
                URL url = new URL((String) params[1]);
                Log.v("log_tag", "name  ::: " + url);
                name = ((String) params[1]).substring(((String) params[1])
                        .lastIndexOf("/") + 1);
                Log.v("log_tag", "name Substring ::: " + name);
                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);
                download = new File(Environment.getExternalStorageDirectory()
                        + "/download/");
                if (!download.exists()) {
                    download.mkdir();
                }
                String strDownloaDuRL = download + "/" + name;
                Log.v("log_tag", " down url   " + strDownloaDuRL);
                FileOutputStream output = new FileOutputStream(strDownloaDuRL);

                byte data[] = new byte[1024];

                long total = 0;

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

                    // writing data to file
                    progressBar
                            .setProgress((int) ((total * 100) / lenghtOfFile));
                    output.write(data, 0, count);
                    setProgress(progressBar, position);
                    }
                }
                // flushing output
                output.flush();

                if(!this.download){
                File delete = new File(strDownloaDuRL);
                delete.delete();
                }                     

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

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

        }

        /**
         * Updating progress bar
         * */
        protected void onProgressUpdate(String... values) {

            super.onProgressUpdate(values);
            Log.v("log_tag", "progress :: " + values);
            // setting progress percentage
            // pDialog.setProgress(Integer.parseInt(progress[0]));
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {

            Log.v("log", "login  ::: 4::: " + download);
            String videoPath = download + "/" + name;
            String chpName = name;
            Log.v("log_tag", "chpName  ::::" + chpName + "  videoPath "
                    + videoPath);
            db.execSQL("insert into videoStatus (chapterNo,videoPath) values(\""
                    + chpName + "\",\"" + videoPath + "\" )");

        }

    }

    // to stop your downloading
    public void downloadFile(){
       this.download = false;
    }

    private void setProgress(ProgressBar pr, int position) {
        ProgressBarSeek pbarSeek = new ProgressBarSeek();
        pbarSeek.setPosition(position);
        pbarSeek.setProgressValue(pr.getProgress());
        Log.v("log_tag", position + "  progress  " + pr.getProgress());
        progreeSeekList.add(pbarSeek);
    }

    private void getProgress(ProgressBar pr, int position, Button cl, Button dl) {
        if (progreeSeekList.size() > 0) {
            for (int j = 0; j < progreeSeekList.size(); j++) {
                if (position == progreeSeekList.get(j).getPosition()) {
                    pr.setProgress(progreeSeekList.get(j).getProgressValue());
                    dl.setVisibility(View.GONE);
                    cl.setVisibility(View.VISIBLE);
                }
            }
        }
    }

答案 1 :(得分:0)

在取消onClick方法内插入以下代码。

DownloadFileFromURL lmib = new DownloadFileFromURL();

if(lmib.getStatus()== AsyncTask.Status.RUNNING){

lmib.cancel(真); }