2013-02-25 46 views
2

当下载文件我展示给用户这个进度,右侧有取消点击按钮,然后下载文件取消和SD卡删除下载文件。如何可能在安卓下面我的代码:?如何取消下载文件当取消按钮onclick在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) 
+0

取消你已经开始,而不是新的同异步任务... yourasynctask.cancel(),并确保它取消了也检查isCancelled()返回true,否则 – Pragnani 2013-02-25 06:32:32

+0

Pragnani感谢您的回复>>但不从sdcard中取消文件。请给我答案!!! – crickpatel0024 2013-02-25 06:40:27

+1

检查文件是否存在于SD卡或不... File file = new File file = File(getExternalCacheDirectory(),“mytextfile.txt”); 如果(file.exists()){ file.delete() }如果存在 – Pragnani 2013-02-25 06:44:15

回答

0

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

DownloadFileFromURL lmib = new DownloadFileFromURL();

如果(lmib.getStatus()== AsyncTask.Status.RUNNING){

lmib.cancel(真); }

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); 
       } 
      } 
     } 
    } 
+0

谢谢回复,但//停止你下载 公共布尔downloadFile(){删除它 this.download1 = FALSE; } error得到download1无法解析或不是字段 – crickpatel0024 2013-02-25 06:51:36

+0

我改变了代码对不起,我忘了添加回报。我改变了代码尝试他! – 2013-02-25 06:54:30

+0

再次感谢亲爱的,但我编辑您的代码//停止您的下载 public void downloadFile(){ this.download1 = false; }然后错误获取download1无法解析或不是一个字段。 – crickpatel0024 2013-02-25 07:04:02