我在點擊webview中的按鈕點擊下載PDF文件時出現問題。文件部分從Webview下載Android
文件下載,但該文件部分下載的,這就是爲什麼我得到以下錯誤
「的文件無法打開,因爲它不是一個有效的PDF文件」
下面是Asyncetask活動我要下載的文件:
public class DownloadPDFTask extends AsyncTask<String, Void, Integer>
{
protected ProgressDialog mWorkingDialog; // progress dialog
protected String mFileName; // downloaded file
protected String mError; // for errors
@Override
protected Integer doInBackground(String... urls)
{
String filename = "";
String str[] = urls[2].split(";");
String st[] =str[1].split("=");
filename = st[1];
String extStorageDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString();
File myDir = new File(extStorageDirectory, "NCR");
File file = new File(extStorageDirectory+"/NCR/"+filename);
// create the directory if it does not exist
if (!myDir.exists())
myDir.mkdirs();
if (file.exists()) {
System.out.println("INSIDE FILE EXIST");
file.delete();
}
try
{
byte[] dataBuffer = new byte[4096];
int nRead = 0;
mFileName = filename;
System.out.println("mFileName<><><> " +mFileName);
// download URL and store to strFileName
// connection to url
java.net.URL urlReport = new java.net.URL(urls[0]);
URLConnection urlConn = urlReport.openConnection();
urlConn.setRequestProperty("User-Agent", urls[1]);
urlConn.setRequestProperty("Content-Disposition", urls[2]);
urlConn.setRequestProperty("Content-Type", "application/pdf");
urlConn.setRequestProperty("Accept", "*/*");
InputStream streamInput = urlReport.openStream();
BufferedInputStream bufferedStreamInput = new BufferedInputStream(streamInput,8192);
FileOutputStream outputStream = new FileOutputStream(extStorageDirectory+"/NCR/"+mFileName);
while ((nRead = bufferedStreamInput.read(dataBuffer)) > 0)
outputStream.write(dataBuffer, 0, nRead);
streamInput.close();
outputStream.close();
// displayPdf(mFileName);
}
catch (Exception e)
{
Log.e("myApp", e.getMessage());
mError = e.getMessage();
return (1);
}
return (0);
}
@Override
protected void onPreExecute()
{
// show "Downloading, Please Wait" dialog
mWorkingDialog = ProgressDialog.show(context, "", "Downloading PDF Document, Please Wait...", true);
return;
}
@Override
protected void onPostExecute (Integer result)
{
if (mWorkingDialog != null)
{
mWorkingDialog.dismiss();
mWorkingDialog = null;
}
switch (result)
{
case 0: // a URL
try
{
displayPdf(mFileName);
}
catch (ActivityNotFoundException e)
{
Toast.makeText(context, "No PDF Viewer Installed", Toast.LENGTH_LONG).show();
}
break;
case 1: // Error
Toast.makeText(context, mError, Toast.LENGTH_LONG).show();
break;
}
}
}
朋友我被困在這,請幫幫我。
親愛Zusee,請你定義publishProgress((INT)((總* 100)/ lengthOfFile)); 請同時嘗試爲publisProgress放置代碼。 – Altavista
publishProgress()來自AsyncTask。它調用onProgressUpdate(),它經常用來更新像ProgressBar這樣的UI元素。 – ntv1000
@Altavista是的,因爲ntv100表示您必須擴展AsyncTask並調用它的方法。我更新了我的答案,以便讓你更清楚。我希望你現在有了路。 –