2013-02-26 96 views
1

在我的情況下,我點擊下載按鈕時,下載所有文件,但在顯示所有文件SD卡和一些文件顯示。和我使用線程。我的代碼中有什麼錯誤:取消(cl)按鈕工作,但在我用delted下載文件無法正常工作,{cl和dl按鈕} setVisibitly沒有改變。我下面的代碼:請Helpme>如何在Android中將所有文件下載並保存在SD卡中的所有文件?

 mainDownloadBtn.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View v) { 
       adtf.setAllDownload(); 
      } 
     }); 

    } 

    public class MyListAdapter extends BaseAdapter { 
     private LayoutInflater mInflater; 
     ProgressBar pr; 
     ProgressBar[] prArray = new ProgressBar[list.size()]; 
     Button cl, dl; 
     ImageView im; 
     DownloadFileFromURL downloadFileFromURL; 

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

     } 

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

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

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

     public void setAllDownload() { 
      if (prArray.length > 0) { 
       for (int i = 0; i < prArray.length; i++) { 
        try { 
         Thread.sleep(5000); 
        } catch (InterruptedException e) { 
         e.printStackTrace(); 
        } 
        downloadFileFromURL = new DownloadFileFromURL(dl, cl); 
        downloadFileFromURL.execute(pr, list.get(i).url_video, i); 
       } 
      } 
     } 

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

      convertView = mInflater.inflate(R.layout.custome_list_view, null); 
      cl = (Button) convertView.findViewById(R.id.cancle_sedual); 
      dl = (Button) convertView.findViewById(R.id.download_sedual); 
      pr = (ProgressBar) convertView.findViewById(R.id.listprogressbar); 
      prArray[position] = pr; 
      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) { 
        Log.v("log_tag","Cancle Button Click"); 
       // dl.setVisibility(View.VISIBLE); 

        dl.setVisibility(View.VISIBLE); 

        cl.setVisibility(View.GONE); 
        downloadFileFromURL = new DownloadFileFromURL(dl, cl); 
        //downloadFileFromURL.cancel(true); 
        downloadFileFromURL.downloadFile(); 
        pr.setProgress(0); 
       } 
      }); 


      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","Start Button Click "); 
        // 
        // new DownloadFileFromURL().execute(str_start); 
        downloadFileFromURL = new DownloadFileFromURL(dl, cl); 
        downloadFileFromURL.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; 
     Button start, cancel; 
     boolean download1 = false; 

     public DownloadFileFromURL(Button start, Button cancel) { 
      this.start = start; 
      this.cancel = cancel; 
     } 

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

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

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

     } 
     @Override 
     protected void onCancelled() { 
      super.onCancelled(); 

     } 

     /** 
     * 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) { 
        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, start, cancel, this); 
       } 
       } 
       // 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; 

     } 

     /** 
     * 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(final ProgressBar pr, final int position, 
      final Button Start, final Button cancel, 
      final DownloadFileFromURL downloadFileFromURL) { 
     ProgressBarSeek pbarSeek = new ProgressBarSeek(); 
     pbarSeek.setPosition(position); 
     pbarSeek.setProgressValue(pr.getProgress()); 
     //Log.v("log_tag", position + " progress " + pr.getProgress()); 
     progreeSeekList.add(pbarSeek); 
    /* cancel.setOnClickListener(new OnClickListener() { 

      @Override 
      public void onClick(View v) { 

       Log.v("log_tag","Cancle Button Click Set progress"); 
       Start.setVisibility(View.VISIBLE); 
       cancel.setVisibility(View.GONE); 
       downloadFileFromURL.cancel(true); 
       pr.setProgress(0); 
      } 
     }); 
     Start.setOnClickListener(new OnClickListener() { 

      @Override 
      public void onClick(View v) { 
       Log.v("log_tag","Start Button Click set Progress"); 
       str_start = list.get(position).url_video; 
       Start.setVisibility(View.GONE); 
       cancel.setVisibility(View.VISIBLE); 
       Log.v("log_tag", "str_start " + str_start); 
       // 
       // new DownloadFileFromURL().execute(str_start); 
       DownloadFileFromURL downloadFileFromU = new DownloadFileFromURL(
         Start, cancel); 
       downloadFileFromU.execute(pr, str_start, position); 
      } 
     });*/ 
    } 

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

回答

2

您可以嘗試使用下面的代碼從URL下載文件,並保存到SD卡:

public void DownloadFromUrl(String DownloadUrl, String fileName) { 
    try { 
     File root = android.os.Environment.getExternalStorageDirectory(); 
     File dir = new File (root.getAbsolutePath() + "/xmls"); 
     if(dir.exists()==false) { 
      dir.mkdirs(); 
     } 

     URL url = new URL(DownloadUrl); //you can write here any link 
     File file = new File(dir, fileName); 

     long startTime = System.currentTimeMillis(); 
     Log.d("DownloadManager", "download url:" + url); 

     /* Open a connection to that URL. */ 
     URLConnection ucon = url.openConnection(); 

     /* 
     * Define InputStreams to read from the URLConnection. 
     */ 
     InputStream is = ucon.getInputStream(); 
     BufferedInputStream bis = new BufferedInputStream(is); 

     /* 
     * Read bytes to the Buffer until there is nothing more to read(-1). 
     */ 
     ByteArrayBuffer baf = new ByteArrayBuffer(5000); 
     int current = 0; 
     while ((current = bis.read()) != -1) { 
      baf.append((byte) current); 
     } 

     /* Convert the Bytes read to a String. */ 
     FileOutputStream fos = new FileOutputStream(file); 
     fos.write(baf.toByteArray()); 
     fos.flush(); 
     fos.close(); 
     Log.d("DownloadManager", "download ready in" + ((System.currentTimeMillis() - startTime)/1000) + " sec"); 
    } catch (IOException e) { 
    Log.d("DownloadManager", "Error: " + e); 
    } 
} 

而且要記住,您在清單文件中指定以下權限。

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission> 
<uses-permission android:name="android.permission.INTERNET"></uses-permission> 
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission> 
<uses-permission android:name="android.permission.READ_PHONE_STATE"></uses-permission> 

我希望這會幫助你。

感謝

+0

感謝您的回覆Grishu。但我用的AsyncTask,我想設置進度所有文件下載和我的代碼中給出,請看到它。 – crickpatel0024 2013-02-26 13:15:59

+0

使用帶進度條的Asynctask檢查鏈接。 http://www.androidhive.info/2012/04/android-downloading-file-by-showing-progress-bar/我希望它能幫助你。 – GrIsHu 2013-02-26 13:25:38

+0

你的代碼工作,但我的視頻不下載0位置下載第二位。爲什麼造成這個問題。 – crickpatel0024 2013-02-26 13:35:06

相關問題