2013-03-21 3 views
5

.net 웹 서비스를 사용 중이고 sd 카드에서 파일을 다운로드 할 수 있지만 특정 파일이 다운로드되고 완료되면 진행률 표시 줄을 표시하고보기 및 취소와 같은 옵션을 표시하려고합니다.Android의 진행률 표시 줄에 다운로드 진행률을 표시하는 방법은 무엇입니까?

Click 이벤트 클래스 :

public void onItemClick(AdapterView<?> parent, View v, int position, long id) { 

        LazyAdapter ca = (LazyAdapter)parent.getAdapter(); 
        FolderList item_name = (FolderList)ca.getItem(position); 
        FolderList DocumentID = (FolderList)ca.getItem(position); 
        FolderList type = (FolderList)ca.getItem(position); 

        Intent mIntent = new Intent(); 
        mIntent.putExtra("item_name", item_name.folder_name); 
        mIntent.putExtra("item_id", DocumentID.ID); 
        mIntent.putExtra("item_type", type.type); 

        mIntent.getStringExtra("item_name"); 

        String Type = mIntent.getStringExtra("item_type"); 

        Log.i("Type", Type); 

        if 
    // Some code here..... 

        } else { 

         Intent i = new Intent(getApplicationContext(), Display_image.class); 
         i.putExtra("item_name", item_name.folder_name); 
         i.putExtra("ID", DocumentID.ID); 
         i.putExtra("item_type", type.type); 
         i.putExtra("User_ID",User_ID); 

         i.getStringExtra("item_name"); 
         Id = i.getStringExtra("ID"); 
         i.getStringExtra("item_type"); 
         startActivity(i); 
         } 
        } 
       }); 
    } 

내 코드 : 나는 다운로드 관리자

SoapPrimitive DocumentResponse = (SoapPrimitive)Envelope.getResponse(); 
     Log.i("DocumentResponse", DocumentResponse.toString()); 

     String DocAsString = DocumentResponse.toString(); 

     byte[] decodedString = Base64.decode(DocAsString, Base64.DEFAULT); 

     File direct = new File(Environment.getExternalStorageDirectory() + "/MyFolder"); 

     if(!direct.exists()) 
     { 
      direct.mkdir(); 
     } 
     File photo = new File(Environment.getExternalStorageDirectory() + "/MyFolder", Name); 

     if (photo.exists()) 
     { 
      photo.delete(); 
     } 
    try { 

     DownloadManager.Request request = new DownloadManager.Request(Uri.parse(Name)); 
     request.setDescription("Have Fun ;)"); 
     request.setTitle("Downloading..."); 
     // in order for this if to run, you must use the android 3.2 to compile your app 
     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { 
      request.allowScanningByMediaScanner(); 
      request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); 
     } 

     FileOutputStream fos=new FileOutputStream(photo.getPath()); 
     fos.write(decodedString); 
     fos.close(); 

     DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE); 
     manager.enqueue(request); 

     ContentValues values= new ContentValues(); 

     System.out.println(values); 

    } 
    catch (java.io.IOException e) 
    { 
     Log.e("PictureDemo", "Exception in photoCallback", e); 
    } 
    } 

사용할 그것으로 다운로드 관리자를 사용하는 방법을 제안 해주세요 ??? 덕분에

답변

13

이것을 달성하기 위해 ProgressBar를 사용할 수 있습니다.

첫째,이처럼 인터페이스에 진행 막대를 추가 : 다음

<ProgressBar 
    android:id="@+id/progress_bar" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    style="@android:style/Widget.ProgressBar.Small"/> 

를 코드 업데이트에서 귀하의 방법을 다음과 같이 :

protected ProgressBar mProgressBar; 
protected long downloadId; 
protected DownloadManager manager; 

public void startdownload(){ 
    //<SET UP DOWNLOAD MANAGER HERE> 
    downloadId = manager.enqueue(request); 
    mProgressBar = findViewById(R.id.progress_bar); 
    Timer myTimer = new Timer(); 
    myTimer.schedule(new TimerTask() {   
     @Override 
      public void run() { 
      DownloadManager.Query q = new DownloadManager.Query(); 
       q.setFilterById(downloadId); 
       Cursor cursor = manager.query(q); 
       cursor.moveToFirst(); 
       int bytes_downloaded = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR)); 
       int bytes_total = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES)); 
       cursor.close(); 
       int dl_progress = (bytes_downloaded * 100/bytes_total); 
       runOnUiThread(new Runnable(){ 
        @Override 
        public void run(){ 
         mProgressbar.setProgress(dl_progress); 
        } 
       }); 

     } 

    }, 0, 10); 

} 
+0

는 – Shweta

+0

는 백그라운드 스레드를 사용하는 예를 편집 elaborate..thanks. –

+0

'dl_progress' 그것은 bytes_downloaded와 bytes_total이 이산 값을 가지고 있지만 항상 0과 100에 있습니다 ... – dentex

1

사용 팔로우 방법

개인 티피 케이션 mNotifyManager을; NO 그것 understand..Please 할 수 working..Not되지

case R.id.btnSubmit: 
mNotifyManager = (NotificationManager)   context.getSystemService(Context.NOTIFICATION_SERVICE); 
      mBuilder = new NotificationCompat.Builder(context); 
      mBuilder.setContentTitle("BuyMixTapes") 
        .setContentText("Download in progress") 
        .setSmallIcon(R.drawable.appiconmain); 

new DownloadFile().execute(vv); 
public class DownloadFile extends AsyncTask<String, String, String> { 

    /** 
    * Before starting background thread 
    * Show Progress Bar Dialog 
    */ 
    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
     //context.showDialog(progress_bar_type); 

     mBuilder.setProgress(100, 0, false); 
     mNotifyManager.notify(id, mBuilder.build()); 
    } 


    protected String doInBackground(String... f_url) { 
     int count; 
     try { 
      for (int i = 0; i < f_url.length; i++) { 
       Log.e("0url",""+f_url[0]); 
       Log.e("1url",""+f_url[1]); 
       // Log.e("1url",""+f_url[1]); 
       URL url = new URL(f_url[i]); 
       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); 

       // Output stream to write file 
       // OutputStream output = new FileOutputStream("/sdcard/"+f_url[i]); 
       OutputStream output = new FileOutputStream(
         "/sdcard/" +i + "buymix.mp3"); 
       byte data[] = new byte[1024]; 

       long total = 0; 

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

        // writing data to file 
        output.write(data, 0, count); 
       } 


       // flushing output 
       output.flush(); 

       // closing streams 
       output.close(); 
       input.close(); 
      } 
     } catch (Exception e) { 
      Log.e("Error: ", e.getMessage()); 
     } 

     return null; 
    } 

    /** 
    * Updating progress bar 
    */ 

    /** 
    * After completing background task 
    * Dismiss the progress dialog 
    **/ 
    @Override 
    protected void onProgressUpdate(String... values) { 
     // Update progress 
     mBuilder.setProgress(100, Integer.parseInt(values[0]), false); 
     mNotifyManager.notify(id, mBuilder.build()); 
     super.onProgressUpdate(values); 
    } 

    protected void onPostExecute(String result) { 
     super.onPostExecute(result); 
     mBuilder.setContentText("Download complete"); 
     // Removes the progress bar 
     String imagePath = Environment.getExternalStorageDirectory() 
       .toString() + "/downloaded.mp3"; 
     mBuilder.setProgress(0, 0, false); 
     mNotifyManager.notify(id, mBuilder.build()); 
    } 

}