2014-12-22 2 views
0

웹 서버에서 PDF 파일을 다운로드 중입니다. &은 진행률 표시 줄에 업데이트 진행률을 표시합니다. 그러나 나는 progressbar가 업데이 트되지 않습니다. 파일은 배경 화면에서 다운로드되지만 진행 막대는 여전히 그림과 같습니다.진행률 표시 줄이 다운로드 중 업데이트되지 않습니다.

enter image description here 여기 내 코드입니다.

import java.io.BufferedInputStream; 
import java.io.File; 
import java.io.FileOutputStream; 
import java.io.InputStream; 
import java.io.OutputStream; 
import java.net.URL; 
import java.net.URLConnection; 

import android.app.Activity; 
import android.app.ProgressDialog; 
import android.content.Intent; 
import android.net.Uri; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.os.Environment; 
import android.util.Log; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 

public class DownloadsPDFTest extends Activity { 

ProgressDialog mProgressDialog; 
String mPdf_links = "http://nationalappsbangladesh.com/Files/02122014104948amar_bangla_boi2.pdf"; 
String mlist; 
String img_path; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    // TODO Auto-generated method stub 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_download_pdf); 


    ((Button) findViewById(R.id.button_start_download)) 
    .setOnClickListener(new OnClickListener() { 

    @Override 
    public void onClick(View v) { 

     startDownloadingOrOpen(); 

    } 
    }); 

} 

private void startDownloadingOrOpen() { 
    // set the file name from url 
    String filenameLink = mPdf_links.substring(
    mPdf_links.lastIndexOf('/') + 1, mPdf_links.length()); 
    System.out.println("FileName:" + filenameLink); 

    File downloadfile = new File("/sdcard/CONSTRUCTION/" + filenameLink); 

    if (!downloadfile.exists()) { 

    Log.e("DownloadsPDFTest", "First Part Working"); 

    mProgressDialog = new ProgressDialog(DownloadsPDFTest.this); 
    mProgressDialog.setMessage("Downloading.."); 
    mProgressDialog.setIndeterminate(false); 
    mProgressDialog.setProgress(0); 
    mProgressDialog.incrementProgressBy(1); 
    mProgressDialog.setMax(100); 
    mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); 

    // execute this when the downloader must be fired 
    DownloadFile downloadFile = new DownloadFile(); 
    System.out.println(mPdf_links); 
    downloadFile.execute(mPdf_links); 

    } else { 

    Log.e("DownloadsPDFTest", "Second Part Working"); 

    File file = new File(Environment.getExternalStorageDirectory() 
    .getAbsolutePath() + "/CONSTRUCTION/" + filenameLink); 
    Intent intent = new Intent(Intent.ACTION_VIEW); 
    intent.setDataAndType(Uri.fromFile(file), "application/pdf"); 
    intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY); 
    startActivity(intent); 

    } 
} 

private class DownloadFile extends AsyncTask<String, Integer, String> { 
    @Override 
    protected String doInBackground(String... sUrl) { 
    try { 
    URL url = new URL(sUrl[0]); 
    URLConnection c 
    connection.connect(); 
    // this will be useful so that you can show a typical 0-100% 
    // progress bar 
    int fileLength = connection.getContentLength(); 
    System.out.println("File length:" + fileLength); 
    System.out.println("TEST here in Downloadfile"); 
    // download the file 
    File wallpaperDirectory = new File("/sdcard/CONSTRUCTION/"); 
    // have the object build the directory structure, if needed. 
    wallpaperDirectory.mkdirs(); 
    // create a File object for the output file 

    String filename = sUrl[0].substring(
     sUrl[0].lastIndexOf('/') + 1, sUrl[0].length()); 
    System.out.println("FileName:" + filename); 
    InputStream input = new BufferedInputStream(url.openStream()); 
    OutputStream output = new FileOutputStream(
     "/sdcard/CONSTRUCTION/" + filename); 

    byte data[] = new byte[2048]; 
    long total = 0; 
    int count; 
    while ((count = input.read(data)) != -1) { 
    total += count; 
    System.out.println("Total downloaded" + total + " count:" 
     + count); 
    // publishing the progress.... 
    publishProgress((int) (total * 100/fileLength)); 
    output.write(data, 0, count); 
    } 

    output.flush(); 
    output.close(); 
    input.close(); 

    mProgressDialog.dismiss(); 

    File file = new File(Environment.getExternalStorageDirectory() 
     .getAbsolutePath() + "/CONSTRUCTION/" + filename); 
    Intent intent = new Intent(Intent.ACTION_VIEW); 
    intent.setDataAndType(Uri.fromFile(file), "application/pdf"); 
    intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY); 
    startActivity(intent); 

    } catch (Exception e) { 
    } 
    return null; 
    } 

    @Override 
    protected void onPreExecute() { 
    super.onPreExecute(); 
    mProgressDialog.show(); 
    } 

    @Override 
    protected void onProgressUpdate(Integer... progress) { 
    super.onProgressUpdate(progress); 
    mProgressDialog.setProgress(progress[0]); 
    } 
} 
} 

xml 여기에 있습니다.

<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" 
> 

<Button 
    android:id="@+id/button_start_download" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_centerHorizontal="true" 
    android:layout_centerVertical="true" 
    android:text="Click to Download PDF/ Open it" /> 

<TextView 
    android:id="@+id/textView_test_data" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_above="@+id/button_start_download" 
    android:layout_centerHorizontal="true" 
    android:layout_marginBottom="21dp" 
    android:text="Download Pdf Sample" /> 

업데이트 : >> 내 질문

http://farm1.static.flickr.com/114/298125983_0e4bf66782_b.jpg

: 자신의 문제인가

내 위의 코드처럼 다른 URL에 대해 잘 작동 내 다운로드 링크에? 아니면 큰 파일/pdf 파일을 처리하기 위해 추가 코드를 작성해야합니까?

내 서버 다운로드 링크는 http://nationalappsbangladesh.com/Files/02122014104948amar_bangla_boi2.pdf입니다.

어떤 아이디어 ??

+0

진행중인'얻을 무엇을 [0]'. 1-100 사이의 유효한 번호를 얻었습니까? 파일 다운로드가 정상입니까? 나에게 그것은 좋아 보인다, 나는 단지 당신이'mProgressDialog'을 설정하는 방식을 좋아하지 않는다. 나는'onPreExecute'에서 그렇게 하겠지만 그것은 나의 의견입니다. – Mike

답변

0

사용이 코드 :

private void startDownload() { 
    String url = "http://farm1.static.flickr.com/114/298125983_0e4bf66782_b.jpg"; 
    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> { 

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

InputStream input = new BufferedInputStream(url.openStream()); 
OutputStream output = new FileOutputStream("/sdcard/some_photo_from_gdansk_poland.jpg"); 

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

@Override 
protected void onPostExecute(String unused) { 
    dismissDialog(DIALOG_DOWNLOAD_PROGRESS); 
} 
} 
+0

코드가 다운로드 링크로 잘 작동합니다. 내 다운로드 링크가 작동하지 않습니다. 그래서 문제는 동일합니다. 배경에 의미 파일이 다운로드되고 진행률 표시 줄이 업데이트되지 않았습니다. :(문제는, 내 다운로드 서버 링크 또는 서버 종속성에 ?? –

+0

그렇다면 귀하의 서버 dependency.because에 문제가 내 경우에 Progressbar 업데이트. –

+0

아니, 업데이트 : 그 publishProgress (""+ ((total * 100)/lenghtOfFile));이 메서드는 정수 값만 사용합니다. 그러나 제 경우에는 정수 저장 범위를 건너 뜁니다. 두 번 또는 길어야합니다. 그래서 어떻게해야합니까? "+ (int) ((total * 100)/lenghtOfFile)의 값을 정수로 변환합니다. –

관련 문제