我正在使用一个使用http连接下载文件的项目.我在下载过程中显示一个进度条状态的水平进度条.
我的功能如下所示:
我的功能如下所示:
....... try { InputStream myInput = urlconnect.getInputStream(); BufferedInputStream buffinput = new BufferedInputStream(myInput); ByteArrayBuffer baf = new ByteArrayBuffer(capacity); int current = 0; while((current = buffinput.read()) != -1) { baf.append((byte) current); } File outputfile = new File(createRepertory(app,0),Filename); FileOutputStream myOutPut = new FileOutputStream(outputfile); myOutPut.write(baf.toByteArray()); ... }
我提前知道我的文件的大小,所以我需要检索的大小在下载(在我的while块).因此,我可以确定进度条的状态.
progressBarStatus = ((int) downloadFileHttp(url,app) * 100)/sizefile;
长的downloadFileHttp(..,..)是我的函数的名字.
我已经尝试通过使用outputfile.length来检索它,但是他的值为“1”,也许这是我要下载的文件数.
Is there any way to figure it out?
更新1
I haven’t got any thread which allow me to figure this out.
Currently I have got a horizontal progress bar whch displays only 0 and 100% whitout intermediate values. I
think about another approach. If I know the rate of my wifi and the
size of the file I can determinate the time of downloading.I know that I can retrieve the piece of information of my Wifi
connection and the size of my file to download.Is anybody already have worked or have thread on it?
解决方法
AsyncTask可能是您的完美解决方案:
private class DownloadFileTask extends AsyncTask<URL,Integer,Long> { protected Long doInBackground(URL... urls) { Url url = urls[0]; //connect to url here ....... try { InputStream myInput = urlconnect.getInputStream(); BufferedInputStream buffinput = new BufferedInputStream(myInput); ByteArrayBuffer baf = new ByteArrayBuffer(capacity); int current = 0; while((current = buffinput.read()) != -1) { baf.append((byte) current); //here you can send data to onProgressUpdate publishProgress((int) (((float)baf.length()/ (float)sizefile) * 100)); } File outputfile = new File(createRepertory(app,Filename); FileOutputStream myOutPut = new FileOutputStream(outputfile); myOutPut.write(baf.toByteArray()); ... } protected void onProgressUpdate(Integer... progress) { //here you can set progress bar in UI thread progressBarStatus = progress; }
}
new DownloadFileTask().execute(url);