我正在尝试从我的在线资源下载文件。我遇到的问题是浏览器窗口在加载到下载服务器时不断出现。有什么方法可以隐藏这个吗?我已经在doInBackground
的{{1}}部分中使用了此代码,但似乎无法隐藏浏览器栏。这是我的代码:
AsyncTask
谢谢大家!
答案 0 :(得分:0)
这里是我的代码示例,没有浏览器下载:
private TextView mFileDownloadProgressBarPercent;
private ProgressBar mFileDownloadProgressBar;
private Runnable mFileExecutionTaskAfterDownload;
public String fileDownloadedResultPath;
和asynctask:
class DownloadFileFromURL extends AsyncTask<String, String, String> {
// Before starting background thread
// Show Progress Bar Dialog
@Override
protected void onPreExecute() {
super.onPreExecute();
if(mFileDownloadProgressBar != null)
mFileDownloadProgressBar.setVisibility(View.VISIBLE);
if(mFileDownloadProgressBarPercent != null)
mFileDownloadProgressBarPercent.setVisibility(View.VISIBLE);
}
// Downloading file in background thread
@Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
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);
String extStorageDirectory = Environment.getExternalStorageDirectory()
.toString();
File folder = new File(extStorageDirectory, "pdf"); // for example we are downloading pdf's so store in pdf dir.
folder.mkdir();
File subFolder = new File(extStorageDirectory+"/pdf", "fileId"); // here you can place files by id of category etc..
subFolder.mkdir();
String fileName = url.toString().substring(url.toString().lastIndexOf("/")+1);
fileDownloadedResultPath = subFolder + "/" + fileName;
// Output stream to write file
OutputStream output = new FileOutputStream(subFolder + "/" + fileName);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
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;
}
protected void onProgressUpdate(String... progress) {
if(mFileDownloadProgressBar != null)
mFileDownloadProgressBar.setProgress(Integer.parseInt(progress[0]));
if(mFileDownloadProgressBarPercent != null)
mFileDownloadProgressBarPercent.setText(mContext.getString(R.string.downloading_file) + " " + String.format("%s%%",Integer.parseInt(progress[0])+""));
}
@Override
protected void onPostExecute(String file_url) {
if(mFileDownloadProgressBar != null)
mFileDownloadProgressBar.setVisibility(View.GONE);
if(mFileDownloadProgressBarPercent != null)
mFileDownloadProgressBarPercent.setVisibility(View.GONE);
if(mFileExecutionTaskAfterDownload != null)
mFileExecutionTaskAfterDownload.run();
}
}