Share with you the learning experience, how to achieve the android file download progress display function, I hope to help the general beginners.
First up Effect chart:
The blue progress bar above will be loaded according to the percentage of the file download, the middle text control is used to download the percentage of the file now, the bottom imageview is used to show the downloaded file, the project is to dynamically show the user the download volume of the file.
Here's the code implementation: first, the layout file:
<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= "/>" <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:la yout_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"/> </R
Elativelayout>
The following main activity code:
public class Mainactivity extends activity {ProgressBar PB;
TextView TV;
ImageView ImageView;
int fileSize;
int downloadfilesize;
String Fileex,filena,filename; Used to receive the number of file downloads sent by line Cheng, to update the UI interface private Handler Handler = new Handler () {@Override public void Handlemessage (Mes Sage msg) {//define a handler for handling the communication between the download thread and the UI if (! Thread.CurrentThread (). isinterrupted ()) {switch (msg.what) {Case 0:pb.setmax (file
Size);
Case 1:pb.setprogress (downloadfilesize);
int result = Downloadfilesize * 100/filesize;
Tv.settext (Result + "%");
Break
Case 2:toast.maketext (mainactivity.this, "File Download Complete", Toast.length_short). Show ();
FileInputStream FIS = null; try {fis = new FileInputStream (environment.getexternalstoragedirectory () + File.separator + "/ceshi/" + Filenam
e); catch (FileNotFoundException e) {e.printstacktrAce (); } Bitmap Bitmap = Bitmapfactory.decodestream (FIS);
Transfer into bitmap figure 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 {//download file, parameter: first URL, second store path Down_file ("Http://cdnq.d Uitang.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 (); /** * File download * @param url: File Download Address * @param path: File Save to Local address * @throws IOException/public void D Own_file (String url,string path) throws ioexception{//download function filename=url.substring (Url.lastindexof ("/") + 1
);
Gets the filename url myurl = new URL (URL);
URLConnection conn = Myurl.openconnection ();
Conn.connect ();
InputStream is = Conn.getinputstream (); This.filesize = Conn.getcontentlength ()//To get file size based on response (this.filesize <= 0) throw new RuntimeException ("Unable to learn file size
");
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);
Save data in path + filename byte buf[] = new byte[1024];
downloadfilesize = 0;
sendmsg (0);
do{//loop read int numread = Is.read (BUF);
if (Numread = = 1) {break;
} fos.write (buf, 0, Numread);
Downloadfilesize + = Numread;
Sendmsg (1);//update Progress bar} while (true);
Sendmsg (2);//Notify Download complete try{is.close ();
catch (Exception ex) {log.e ("tag", "Error:" + ex.getmessage (), ex); The download amount of the file sent to handler on the//thread, update of UI interface private void sendmsg (int flag) {Message msg = new MESSAG
E ();
Msg.what = Flag;
Handler.sendmessage (msg);
}
}
Finally, it is important to note that in the Androidmanifest.xml file, you add access to the network
<uses-permission android:name= "Android.permission.INTERNET"/>
Here about the Android file download dynamic display download progress content for everyone to share the end, I hope to help you learn.