/*
* Download using progress bar control program According to class case ....
*/
public class Aty_httpdownload_progressbar extends Activity {
Private ProgressBar PB;
Private TextView tv_progress;
private static final int downloading=1;
private static final int download_success=2;
Private double totalsize;
Private double currentsize;
Private Handler Handler = new Handler () {
@Override
public void Handlemessage (Message msg) {
Switch (msg.what) {
Case 1://is still being downloaded
Double Progress=currentsize/totalsize*pb.getmax ();
Pb.setprogress ((int) progress);
Tv_progress.settext ((int) progress+ "%");
Break
Case 2://Download complete
Pb.setvisibility (View.gone);
Tv_progress.settext ("100%, Download Complete");
Toast.maketext (Getapplicationcontext (), "Download Done",
Toast.length_short). Show ();
Break
Default
Break
}
}
};
@Override
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.http_downaload_progressbar);
Initwidgets ();
Downloadimage ();
}
private void Initwidgets () {
PB = (ProgressBar) Findviewbyid (R.ID.PB);
Tv_progress = (TextView) Findviewbyid (r.id.tv_progress);
Pb.setmax (100);
}
Write a new method, read the image data from the net, display on the interface
public void Downloadimage () {
New Thread (New Runnable () {
@Override
public void Run () {
try {
URL url = new URL (
"Http://10.0.2.2:8080/News/assets/myradio.mp4");
HttpURLConnection connection = (httpurlconnection) URL
. OpenConnection ();
Connection.setconnecttimeout (5000);
Connection.setdefaultusecaches (FALSE);
Connection.setdoinput (TRUE);
Connection.setdooutput (TRUE);
Connection.setreadtimeout (5000);
Connection.setrequestmethod ("POST");
InputStream is = Connection.getinputstream ();
Totalsize=connection.getcontentlength ();//File Total size
Character reading with BufferedReader, byte with DataInputStream
Write the memory card, put it in that position: put it on the SD card, name App7.png
File DownloadFile = new file (environment
. getExternalStorageDirectory (), "/myradio.mp4");
DataOutputStream dos = new DataOutputStream (
New FileOutputStream (DownloadFile));
int len = 0;
byte[] buffer = new byte[4096];
while (len = is.read (buffer))! =-1) {
currentsize+=len;//the file size currently being read
Dos.write (buffer, 0, Len);
Handler.sendemptymessage (downloading);
}
Handler.sendemptymessage (download_success);
Dos.close ();
Is.close ();
} catch (Malformedurlexception e) {
E.printstacktrace ();
} catch (IOException e) {
E.printstacktrace ();
}
}
}). Start ();
}
}
Use the progress bar to show the progress of downloading files from the network