和大家一起分享一下学习经验,如何实现android文件下载进度显示功能,希望对广大初学者有帮助。
先上效果图:
上方的蓝色进度条,会根据文件下载量的百分比进行加载,中部的文本控件用来现在文件下载的百分比,最下方的imageview用来展示下载好的文件,项目的目的就是动态向用户展示文件的下载量。
下面看代码实现:首先是布局文件:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
<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"
tools:context= "${relativepackage}.${activityclass}" >
<progressbar
android:id= "@+id/progressbar"
style= "?android:attr/progressbarstylehorizontal"
android:layout_width= "match_parent"
android:layout_height= "wrap_content"
android:max= "100" />
<textview
android:id= "@+id/textview"
android:layout_width= "wrap_content"
android:layout_height= "wrap_content"
android:layout_below= "@+id/progressbar"
android:layout_centerhorizontal= "true"
android:layout_margintop= "24dp"
android:text= "textview" />
<imageview
android:id= "@+id/imageview"
android:layout_margintop= "24dp"
android:layout_width= "match_parent"
android:layout_height= "wrap_content"
android:layout_alignparentbottom= "true"
android:layout_below= "@+id/textview"
android:contentdescription= "@string/app_name"
android:src= "@drawable/ic_launcher" />
</relativelayout>
|
接下来的主activity代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
|
public class mainactivity extends activity {
progressbar pb;
textview tv;
imageview imageview;
int filesize;
int downloadfilesize;
string fileex,filena,filename;
//用来接收线程发送来的文件下载量,进行ui界面的更新
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(mainactivity. this , "文件下载完成" , toast.length_short).show();
fileinputstream fis = null ;
try {
fis = new fileinputstream(environment.getexternalstoragedirectory() + file.separator + "/ceshi/" + filename);
} catch (filenotfoundexception e) {
e.printstacktrace();
}
bitmap bitmap = bitmapfactory.decodestream(fis); ///把流转化为bitmap图
imageview.setimagebitmap(bitmap);
break ;
case - 1 :
string error = msg.getdata().getstring( "error" );
toast.maketext(mainactivity. this , error, toast.length_short).show();
break ;
}
}
super .handlemessage(msg);
}
};
@override
protected void oncreate(bundle savedinstancestate) {
super .oncreate(savedinstancestate);
setcontentview(r.layout.activity_main);
pb=(progressbar)findviewbyid(r.id.progressbar);
tv=(textview)findviewbyid(r.id.textview);
imageview = (imageview) findviewbyid(r.id.imageview);
tv.settext( "0%" );
new thread(){
public void run(){
try {
//下载文件,参数:第一个url,第二个存放路径
down_file( "http://cdnq.duitang.com/uploads/item/201406/15/20140615203435_abqma.jpeg" , environment.getexternalstoragedirectory() + file.separator + "/ceshi/" );
} catch (clientprotocolexception e) {
// todo auto-generated catch block
e.printstacktrace();
} catch (ioexception e) {
// todo auto-generated catch block
e.printstacktrace();
}
}
}.start();
}
/**
* 文件下载
* @param url:文件的下载地址
* @param path:文件保存到本地的地址
* @throws ioexception
*/
public void down_file(string url,string path) throws ioexception{
//下载函数
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(); //根据响应获取文件大小
if ( this .filesize <= 0 ) throw new runtimeexception( "无法获知文件大小 " );
if (is == null ) throw new runtimeexception( "stream is null" );
file file1 = new file(path);
file file2 = new file(path+filename);
if (!file1.exists()){
file1.mkdirs();
}
if (!file2.exists()){
file2.createnewfile();
}
fileoutputstream fos = new fileoutputstream(path+filename);
//把数据存入路径+文件名
byte buf[] = new byte [ 1024 ];
downloadfilesize = 0 ;
sendmsg( 0 );
do {
//循环读取
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);
}
}
//在线程中向handler发送文件的下载量,进行ui界面的更新
private void sendmsg( int flag)
{
message msg = new message();
msg.what = flag;
handler.sendmessage(msg);
}
}
|
最后一定要注意的是:在androidmanifest.xml文件中,添加访问网络的权限
1
|
<uses-permission android:name= "android.permission.internet" />
|
到这里关于android文件下载动态显示下载进度的内容就为大家分享完毕,希望对大家的学习有所帮助。