Android file download progress detection, android File Download

Source: Internet
Author: User
Tags sendmsg

Android file download progress detection, android File Download

Recently, due to the needs of the project, I have studied the implementation of the Android file download progress display function. Next I will share with you how to help beginners.
First:

  

The blue progress bar on the top is loaded based on the percentage of files downloaded. The text control in the middle is used to display the percentage of files downloaded. The bottom ImageView is used to display the downloaded files, the purpose of the project is to dynamically display the download volume of files to users.

The code implementation is as follows: first, layout files:

<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 "> public class MainActivity extends Activity {ProgressBar pb; TextView TV; ImageView imageView; int fileSize; Int downLoadFileSize; String fileEx, fileNa, filename; // used to receive downloads of files sent by the thread, and update private Handler handler = new Handler () on the UI () {@ Override public void handleMessage (Message msg) {// defines a Handler for processing the communication between the download thread and the 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, "file download completed", Toast. LENGTH_SHORT ). show (); FileInputStream FCM = null; try {FD = new FileInputStream (Environment. getExternalStorageDirectory () + File. Separator + "/ceshi/" + filename);} catch (FileNotFoundException e) {e. printStackTrace ();} Bitmap bitmap = BitmapFactory. decodeStream (FCM); // converts the stream to a Bitmap image 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) ;}}; @ Overrideprotected void onCreate (Bu Ndle 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 storage path down_file ("http://cdnq.duitang.com/uploads/item/201406/15/20140615203435_A BQMa.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: * @ param path of the file: the address * @ throws IOException */public void down_file (String url, String path) Throws IOException {// download function filename = url. substring (url. lastIndexOf ("/") + 1); // obtain the file name URL myURL = new URL (url); URLConnection conn = myURL. openConnection (); conn. connect (); InputStream is = conn. getInputStream (); this. fileSize = conn. getContentLength (); // obtain the file size based on the response if (this. fileSize <= 0) throw new RuntimeException ("File size cannot be known"); if (is = null) throw new RuntimeException ("stream is null"); File f Ile1 = 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 to the path + file name byte buf [] = new byte [1024]; downLoadFileSize = 0; sendMsg (0); do {// read int numread = is cyclically. read (buf); if (numread =-1) {break;} fos. write (buf, 0, numread); downLoadFileSize + = numread; sendMsg (1); // update progress bar} while (true); sendMsg (2 ); // notification download completed. try {is. close ();} catch (Exception ex) {Log. e ("tag", "error:" + ex. getMessage (), ex) ;}// download volume of the file sent to Handler in the thread, and update private void sendMsg (int flag) on the UI) {Message msg = new Message (); msg. what = flag; handler. sendMessage (msg );}}

Finally, you must note that in the AndroidManifest. xml file, add the network access permission.

<uses-permission android:name="android.permission.INTERNET"/>

Here we will share with you the demo about how to dynamically display the download progress of Android files. I hope it will help you learn more.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.