Asynctask in Android to download files in the background and display the download progress in the drop-down menu

Source: Internet
Author: User

During the development process, you will always need to download files from the network, and sometimes you need to display the download progress in the drop-down menu.

Now I've written a demo that encapsulates the code for asynctask download files and progress display, and can be used directly in the future when you're working on a project.



The main interface has only one button, which is relatively simple:

/layout/activity_main.xml:

<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 " >    <button        android:id= "@+id/button"        android:layout_width= "wrap_content"        android:layout_ height= "Wrap_content"        android:layout_alignparentleft= "true"        android:layout_alignparenttop= "true"        android:text= "Click to download"/></relativelayout>


Mainactivity: The explanation of the ideas is in the code:

Import Android.app.activity;import android.os.bundle;import Android.os.handler;import Android.view.View;import Android.view.view.onclicklistener;import Android.widget.button;public class Mainactivity extends Activity {private Handler Mhandler = new Handler ();p rivate asynctaskutil mdownloadasynctask;private Button Mbutton; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_ Main); Mbutton = (Button) Findviewbyid (R.id.button); Mbutton.setonclicklistener (new Onclicklistener () {@ overridepublic void OnClick (View v) {//asynctask asynchronous download Task Mdownloadasynctask = new Asynctaskutil (Mainactivity.this, Mhandler); Mdownloadasynctask.execute ("Http://apps.wandoujia.com/apps/com.sec.print.mobileprint/download", " Mobile print.apk ");//must pass in two parameters--parameter 1:url; parameter 2: File name (can be NULL)}});}}

The above as long as by creating a new Asynctaskutil object, the incoming URL and file name can be downloaded in the background file disease display download progress, is not very important? The specific code is parsed as follows:


Asynctaskrunnable: For the Handler.post (Runnable) method to update the UI, the download progress is mainly through Notificationmanager, notification and RemoteView to display, Update the progress of the download, do not understand the students need Google a bit ~

Import Java.text.decimalformat;import Android.app.notification;import Android.app.notificationmanager;import Android.content.context;import Android.util.log;import Android.widget.remoteviews;import android.widget.Toast; public class Asynctaskrunnable implements Runnable{public static final String TAG = "asynctaskrunnable";// The state of the main thread's activityprivate Context mcontext;//notification: Update or failure or success private int mstatus;//notification download ratio private Float msize;//Management drop-down menu notification information private Notificationmanager mnotificationmanager;//drop-down menu notification information private Notification    mnotification;//drop-down menu notification information viewprivate remoteviews mremoteviews; The type of notification information for the drop-down menu idprivate static final int notification_id = 1;//Set scale and data public void Setdatas (int status, float size) {this. Mstatus = Status;this.msize = size;} Initialize public asynctaskrunnable (context context) {This.mcontext = Context;mnotificationmanager = (notificationmanager) Mcontext.getsystemservice (Context.notification_service);//Initialize drop-down menu notification message mnotification = new NOTIFICATION (); mnotifIcation.icon = r.drawable.ic_launcher;//Set the download progress Iconmnotification.tickertext = Mcontext.getresources (). GetString ( R.string.app_name); Set the download progress titlemremoteviews = new Remoteviews (Mcontext.getpackagename (), r.layout.down_notification);// For the use of RemoteView, do not understand the need to find Googlemremoteviews.setimageviewresource (R.id.id_download_icon, r.drawable.ic_launcher);} @Overridepublic void Run () {//By judging a different status: Update in/download failed/download successful update drop-down menu notification Information switch (mstatus) {case Asynctaskutil.notification_ progress_failed://Download failed mnotificationmanager.cancel (notification_id); Break;case Asynctaskutil.notification_ progress_succeed://Download Successful Mremoteviews.settextviewtext (R.id.id_download_textview, "Download completed!"); Mremoteviews.setprogressbar (R.id.id_download_progressbar, N, +, false) Mnotification.contentview = MRemoteViews ; Mnotificationmanager.notify (notification_id, mnotification); Mnotificationmanager.cancel (NOTIFICATION_ID); Toast.maketext (Mcontext, "Download completed!", Toast.length_short). Show (); Break;case Asynctaskutil.notification_progress_update://Update in DecimalFormat format = new DecimalFormat ("0.00");//number format conversion string PROGRESS = Format.format ( Msize); LOG.D (TAG, "The progress of the download" + progress); Mremoteviews.settextviewtext (R.id.id_download_textview, " Download completed: "+ progress +"% "); Mremoteviews.setprogressbar (R.id.id_download_progressbar, +, (int) msize, fals e); Mnotification.contentview = Mremoteviews;mnotificationmanager.notify (notification_id, mNotification); break;}}}
It is necessary to create a layout file for the download progress as follows:

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "Android:layout_width=" Match_parent "android:layout_height=" match_parent "android:orientation=" vertical " > <linearlayout android:layout_width= "match_parent" android:layout_height= "Wrap_content" and        roid:gravity= "center" android:orientation= "horizontal" android:background= "@android: Color/white" > <imageview android:id= "@+id/id_download_icon" android:layout_width= "Wrap_content" and             roid:layout_height= "Wrap_content" android:layout_marginright= "10DP" android:layout_marginleft= "10DP" android:src= "@drawable/ic_launcher"/> <linearlayout android:layout_width= "Wrap_conten T "android:layout_height=" wrap_content "android:layout_marginright=" 10dip "android:layout _weight= "1" Android:orientation= "vertical" > <textview android:layout_width= "wrap_content" Android: layout_height= "Wrap_content" android:text= "@string/app_name" android:textcolor= "@android: Col                 Or/black "android:textsize=" 18dip "android:textstyle=" bold "/> <progressbar                Android:id= "@+id/id_download_progressbar" style= "? Android:attr/progressbarstylehorizontal" Android:layout_width= "Fill_parent" android:layout_height= "Wrap_content" Andro id:layout_margintop= "5DP" android:max= "android:progress=" 0 "Android:seco ndaryprogress= "0"/> <textview android:id= "@+id/id_download_textview" Andro Id:layout_width= "Wrap_content" android:layout_height= "wrap_content" android:text= "Download C            ompleted: "     Android:textcolor= "@android: Color/black" android:textsize= "12dip" android:textstyle= "bo LD "/> </LinearLayout> </LinearLayout></LinearLayout>


Asynchronous Download class: Asynctaskutil for downloading files:
Import Java.io.file;import java.io.fileoutputstream;import Java.io.inputstream;import Java.net.URL;import Java.net.urlconnection;import Java.util.timer;import Java.util.timertask;import Android.content.Context;import Android.os.asynctask;import Android.os.environment;import Android.os.handler;import Android.util.Log;import Android.widget.toast;public class Asynctaskutil extends Asynctask<string, Double, boolean> {public static final  String TAG = "Asynctaskutil";p ublic static final int notification_progress_update = 0x10;//flag to update download progress public static final int notification_progress_succeed = 0x11;//indicates download succeeded public static final int notification_progress_failed = 0x12;//indicates download failed// Urlprivate String murl;//activityprivate Context mcontext;//Task Timer Private timer mtimer;//timed task private TimerTask mtask;// Main Line path handed over handlerprivate Handler mhandler;//the file size to download private long mfilesize;//downloaded file size private long mtotalreadsize;// Asynctaskrunnable implements the Runnable interface to update the download progress of the display private asynctaskrunnable mrunnable;//constructorFrench public Asynctaskutil (context context, Handler Handler) {mcontext = Context;mhandler = Handler;mtimer = new Timer (); mtask  = new TimerTask () {//Perform scheduled tasks in the Run method @overridepublic void Run () {//size represents the percentage of download progress float size = (float) mtotalreadsize * 100/ (float) mfilesize;//The progress and status (update, failure, success) of the download through the Asynctaskrunnable Setdatas method Mrunnable.setdatas (Notification_progress_ update, size);//Updating Progress mhandler.post (mrunnable);}}; mrunnable = new Asynctaskrunnable (mcontext);} Execute time-consuming operation, Params[0] is url,params[1] is a file name (null writes NULL) @Overrideprotected Boolean doinbackground (String ... params) {// The task timer must start Mtimer.schedule (mtask, 0, +); try {murl = params[0];//establish link urlconnection connection = new URL (Murl). OpenConnection ();//Get file size Mfilesize = Connection.getcontentlength (); LOG.D (TAG, "The count of the URL content length is:" + mfilesize);//Get input stream InputStream is = Connection.getinputstream ();// First, create the folder file Fold = new file (GetFolderPath ()), if (!fold.exists ()) {fold.mkdirs ();} String filename = "";//Determine file name: User-defined or obtained by URL if (params[1]! = null) {FileName = params[1];} Else{filename = GetFileName (Params[0]);} File output stream FileOutputStream fos = new FileOutputStream (new file (GetFolderPath () + fileName); byte[] Buff = new Byte[1024];int Len;while (len = is.read (buff))! =-1) {mtotalreadsize + = len;fos.write (buff, 0, Len);} Fos.flush (); Fos.close ();} catch (Exception e) {///exception, download failed Mrunnable.setdatas (notification_progress_failed, 0);//Send display download failed Mhandler.post ( mrunnable); if (Mtimer! = NULL && Mtask! = null) {Mtimer.cancel (); Mtask.cancel ();} E.printstacktrace (); return false;} Download successful Mrunnable.setdatas (notification_progress_succeed, 0); Mhandler.post (mrunnable); if (Mtimer! = null && Mtask = null) {Mtimer.cancel (); Mtask.cancel ();} return true;} Get the file name from the URL private string GetFileName (String string) {return string.substring (String.LastIndexOf ("/") + 1);} Download folder path private String GetFolderPath () {return environment.getexternalstoragedirectory (). toString () + "/ Asynctaskdownload/";} Doinbackground method before calling, initializing ui@overrideprotected void OnPreExecute (){Super.onpreexecute ();} Called after the Doinbackground method @overrideprotected void OnPostExecute (Boolean result) {Super.onpostexecute (result); Result) {Toast.maketext (Mcontext, "Download completed!", Toast.length_short). Show ();} else {Toast.maketext (Mcontext, "Download Failed!", Toast.length_short). Show ();}} @Overrideprotected void Onprogressupdate (Double ... values) {super.onprogressupdate (values);}}

Well, that's what we're sharing today ~ ~ It's time (~"~) ~zz

Asynctask in Android to download files in the background and display the download progress in the drop-down menu

Related Article

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.