Android文件下載進度條的實現(xiàn)代碼
更新時間:2013年01月21日 11:28:48 作者:
我們今天開始學習的是下載進度的實現(xiàn)。今天的這段代碼是網(wǎng)上找的,自己做了些小改,通過模擬器測試。文件下載進度條控制(就是為了高清壁紙加個進度條),自己研究了好久,但是進度條只能顯示緩存寫入文件的進度,不能顯示下載進度。找了好久,終于找到一段用的代碼,所以記錄下來,大家分享
main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView android:id="@+id/tv"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text=""
/>
<ProgressBar android:id="@+id/down_pb"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:max="100"
style="?android:attr/progressBarStyleHorizontal" mce_style="?android:attr/progressBarStyleHorizontal"
/>
</LinearLayout>
main.java:
package com.pocketdigi.download;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import org.apache.http.client.ClientProtocolException;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
public class main extends Activity {
/** Called when the activity is first created. */
ProgressBar pb;
TextView tv;
int fileSize;
int downLoadFileSize;
String fileEx,fileNa,filename;
private Handler handler = new Handler()
{
@Override
public void handleMessage(Message msg)
{//定義一個Handler,用于處理下載線程與UI間通訊
if (!Thread.currentThread().isInterrupted())
{
switch (msg.what)
{
case 0:
pb.setMax(fileSize);
case 1:
pb.setProgress(downLoadFileSize);
int result = downLoadFileSize * 100 / fileSize;
tv.setText(result + "%");
break;
case 2:
Toast.makeText(main.this, "文件下載完成", 1).show();
break;
case -1:
String error = msg.getData().getString("error");
Toast.makeText(main.this, error, 1).show();
break;
}
}
super.handleMessage(msg);
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
pb=(ProgressBar)findViewById(R.id.down_pb);
tv=(TextView)findViewById(R.id.tv);
new Thread(){
public void run(){
try {
down_file("http://wallpaper.pocketdigi.com/upload/1/bigImage/1284565196.jpg","/sdcard/");
//下載文件,參數(shù):第一個URL,第二個存放路徑
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}.start();
}
public void down_file(String url,String path) throws IOException{
//下載函數(shù)
filename=url.substring(url.lastIndexOf("/") + 1);
//獲取文件名
URL myURL = new URL(url);
URLConnection conn = myURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
this.fileSize = conn.getContentLength();//根據(jù)響應獲取文件大小
if (this.fileSize <= 0) throw new RuntimeException("無法獲知文件大小 ");
if (is == null) throw new RuntimeException("stream is null");
FileOutputStream fos = new FileOutputStream(path+filename);
//把數(shù)據(jù)存入路徑+文件名
byte buf[] = new byte[1024];
downLoadFileSize = 0;
sendMsg(0);
do
{
//循環(huán)讀取
int numread = is.read(buf);
if (numread == -1)
{
break;
}
fos.write(buf, 0, numread);
downLoadFileSize += numread;
sendMsg(1);//更新進度條
} while (true);
sendMsg(2);//通知下載完成
try
{
is.close();
} catch (Exception ex)
{
Log.e("tag", "error: " + ex.getMessage(), ex);
}
}
private void sendMsg(int flag)
{
Message msg = new Message();
msg.what = flag;
handler.sendMessage(msg);
}
}
大家看了以后就應該明白了,上面寫的是用一個循環(huán)來完成的這些事情,byte buf[] = new byte[1024];這句話中大家一定要寫1024,這個可不能改變呀。sendMsg(0);這句的括號里寫的是0,這個也要記得,是0而不是1.
復制代碼 代碼如下:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView android:id="@+id/tv"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text=""
/>
<ProgressBar android:id="@+id/down_pb"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:max="100"
style="?android:attr/progressBarStyleHorizontal" mce_style="?android:attr/progressBarStyleHorizontal"
/>
</LinearLayout>
main.java:
復制代碼 代碼如下:
package com.pocketdigi.download;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import org.apache.http.client.ClientProtocolException;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
public class main extends Activity {
/** Called when the activity is first created. */
ProgressBar pb;
TextView tv;
int fileSize;
int downLoadFileSize;
String fileEx,fileNa,filename;
private Handler handler = new Handler()
{
@Override
public void handleMessage(Message msg)
{//定義一個Handler,用于處理下載線程與UI間通訊
if (!Thread.currentThread().isInterrupted())
{
switch (msg.what)
{
case 0:
pb.setMax(fileSize);
case 1:
pb.setProgress(downLoadFileSize);
int result = downLoadFileSize * 100 / fileSize;
tv.setText(result + "%");
break;
case 2:
Toast.makeText(main.this, "文件下載完成", 1).show();
break;
case -1:
String error = msg.getData().getString("error");
Toast.makeText(main.this, error, 1).show();
break;
}
}
super.handleMessage(msg);
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
pb=(ProgressBar)findViewById(R.id.down_pb);
tv=(TextView)findViewById(R.id.tv);
new Thread(){
public void run(){
try {
down_file("http://wallpaper.pocketdigi.com/upload/1/bigImage/1284565196.jpg","/sdcard/");
//下載文件,參數(shù):第一個URL,第二個存放路徑
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}.start();
}
public void down_file(String url,String path) throws IOException{
//下載函數(shù)
filename=url.substring(url.lastIndexOf("/") + 1);
//獲取文件名
URL myURL = new URL(url);
URLConnection conn = myURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
this.fileSize = conn.getContentLength();//根據(jù)響應獲取文件大小
if (this.fileSize <= 0) throw new RuntimeException("無法獲知文件大小 ");
if (is == null) throw new RuntimeException("stream is null");
FileOutputStream fos = new FileOutputStream(path+filename);
//把數(shù)據(jù)存入路徑+文件名
byte buf[] = new byte[1024];
downLoadFileSize = 0;
sendMsg(0);
do
{
//循環(huán)讀取
int numread = is.read(buf);
if (numread == -1)
{
break;
}
fos.write(buf, 0, numread);
downLoadFileSize += numread;
sendMsg(1);//更新進度條
} while (true);
sendMsg(2);//通知下載完成
try
{
is.close();
} catch (Exception ex)
{
Log.e("tag", "error: " + ex.getMessage(), ex);
}
}
private void sendMsg(int flag)
{
Message msg = new Message();
msg.what = flag;
handler.sendMessage(msg);
}
}
大家看了以后就應該明白了,上面寫的是用一個循環(huán)來完成的這些事情,byte buf[] = new byte[1024];這句話中大家一定要寫1024,這個可不能改變呀。sendMsg(0);這句的括號里寫的是0,這個也要記得,是0而不是1.
您可能感興趣的文章:
相關文章
Android應用第一次安裝成功點擊“打開”后Home鍵切出應用后再點擊桌面圖標返回導致應用重啟問題的解決方法
這篇文章主要介紹了Android應用第一次安裝成功點擊“打開”后Home鍵切出應用后再點擊桌面圖標返回導致應用重啟問題的解決方法,需要的朋友可以參考下2016-11-11
Android string-array數(shù)據(jù)源簡單使用
這篇文章主要介紹了Android string-array數(shù)據(jù)源簡單使用的相關資料,需要的朋友可以參考下2016-09-09
Navigation?Bundle實現(xiàn)兩個Fragment參數(shù)傳遞
這篇文章主要為大家介紹了Navigation?Bundle實現(xiàn)兩個Fragment參數(shù)傳遞,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-04-04
android仿知乎ScrollView滾動改變標題欄透明度
這篇文章主要為大家詳細介紹了android仿知乎ScrollView滾動改變標題欄透明度,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-06-06
Android實現(xiàn)可輸入數(shù)據(jù)的彈出框
這篇文章主要為大家詳細介紹了Android實現(xiàn)可輸入數(shù)據(jù)的彈出框,文章提供了兩種方式,示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-01-01
Android中ScrollView監(jiān)聽滑動距離案例講解
這篇文章主要介紹了Android中ScrollView監(jiān)聽滑動距離案例講解,本篇文章通過簡要的案例,講解了該項技術的了解與使用,以下就是詳細內(nèi)容,需要的朋友可以參考下2021-08-08

