In Android, AsyncTask downloads files in the background and displays the download progress from the drop-down menu. androidasynctask

Source: Internet
Author: User

In Android, AsyncTask downloads files in the background and displays the download progress from the drop-down menu. androidasynctask

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

Now I have written a Demo that encapsulates the code for downloading files and displaying the progress of AsyncTask, which can be used directly during project development.

:



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 ideas are explained 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 (); private 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.exe cute ("http://apps.wandoujia.com/apps/com.sec.print.mobileprint/download", "Mobile Print.apk"); // two parameters must be input -- parameter 1: url; parameter 2: file Name (which can be null )}});}}

As long as you create a new AsyncTaskUtil object, you can pass in the url and file name to view the download progress in the background? The code is parsed as follows:


AsyncTaskRunnable: Used for the handler. post (Runnable) method to update the UI. The download progress is mainly displayed and updated through icationicationmanager, Notification, and RemoteView. If you do not understand it, you need to google it ~

Import java. text. decimalFormat; import android. app. notification; import android. app. icationicationmanager; 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"; // activityprivate Context mContext of the main thread; // notification Status: update or failure or private Int mStatus; // notification download ratio private float mSize; // manage the Notification information in the drop-down menu private icationicationmanager micationicationmanager; // The notification Information in the drop-down menu private Notification mNotification; // viewprivate RemoteViews mRemoteViews of the notification information in the drop-down menu; // The type of notification information in the drop-down menu idprivate static final int icationication_id = 1; // set the ratio and data public void setDatas (int status, float size) {this. mStatus = status; this. mSize = size;} // initialize public AsyncTaskRunnable (Co Ntext context) {this. mContext = context; micationicationmanager = (icationicationmanager) mContext. getSystemService (Context. NOTIFICATION_SERVICE); // initialize the Notification information of the drop-down menu mNotification = new Notification (); mNotification. icon = R. drawable. ic_launcher; // sets the iconmNotification of the download progress. tickerText = mContext. getResources (). getString (R. string. app_name); // set the download progress's titlemRemoteViews = new RemoteViews (mContext. getPackageName (), R. layout. down_notification); // For RemoteView usage, you need to find googlemRemoteViews if you do not understand it. setImageViewResource (R. id. id_download_icon, R. drawable. ic_launcher) ;}@ Overridepublic void run () {// determine the status of the notification in the update/download failed/download successful update drop-down menu switch (mStatus) {case AsyncTaskUtil. NOTIFICATION_PROGRESS_FAILED: // failed to download mNotificationManager. cancel (icationication_id); break; case AsyncTaskUtil. NOTIFICATION_PROGRESS_SUCCEED: // the download is successful. set TextViewText (R. id. id_download_textview, "Download completed! "); MRemoteViews. setProgressBar (R. id. id_download_progressbar, 100,100, false); mNotification. contentView = mRemoteViews; mNotificationManager. Y (ication_id _id, mNotification); mNotificationManager. cancel (icationication_id); Toast. makeText (mContext, "Download completed! ", Toast. LENGTH_SHORT ). show (); break; case AsyncTaskUtil. NOTIFICATION_PROGRESS_UPDATE: // DecimalFormat format = new DecimalFormat ("0.00") in the update; // convert the numeric format to 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, 100, (int) mSize, false); mNotification. contentView = mRemoteViews; mNotificationManager. Y (ication_id _id, mNotification); break ;}}}
You need to create a layout file for the download progress, as shown below:

<?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"        android:gravity="center"        android:orientation="horizontal"        android:background="@android:color/white" >        <ImageView            android:id="@+id/id_download_icon"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_marginRight="10dp"            android:layout_marginLeft="10dp"            android:src="@drawable/ic_launcher" />        <LinearLayout            android:layout_width="wrap_content"            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:color/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"                android:layout_marginTop="5dp"                android:max="100"                android:progress="0"                android:secondaryProgress="0" />            <TextView                android:id="@+id/id_download_textview"                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:text="Download completed : "                 android:textColor="@android:color/black"                android:textSize="12dip"                android:textStyle="bold" />        </LinearLayout>    </LinearLayout></LinearLayout>


Asynchronous download class: AsyncTaskUtil is used to download 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, Do Uble, Boolean> {public static final String TAG = "AsyncTaskUtil"; public static final int icationication_progress_update = 0x10; // The public static final int NOTIFICATION_PROGRESS_SUCCEED = 0x11 sign used to update the download progress; // It indicates that the download is successful. public static final int notificationication_progress_failed = 0x12; // indicates that the download failed // URLprivate String mUrl; // activityprivate Context mContext; // task Timer private Timer mTimer; // scheduled task private TimerTask mTask; // The Master thread passes Handlerprivate Handler mHandler; // the size of the file to be downloaded: private long mFileSize; // the size of the downloaded file: private long mTotalReadSize; // AsyncTaskRunnable implements the Runnable interface, used to update the display of download progress private AsyncTaskRunnable mRunnable; // constructor public AsyncTaskUtil (Context context, Handler handler) {mContext = context; mHandler = handler; mTimer = new Timer (); mTask = new TimerTask () {// scheduled task executed in the run method @ Overridepublic void run () {// size indicates the download progress percentage float s Ize = (float) mTotalReadSize * 100/(float) mFileSize; // the progress and status of the download through the setDatas method of AsyncTaskRunnable (update in progress, failed, successful) mRunnable. setDatas (icationication_progress_update, size); // Update Progress mHandler. post (mRunnable) ;}}; mRunnable = new AsyncTaskRunnable (mContext) ;}// perform time-consuming operations. params [0] is a url, params [1] is the file name (null is written) @ Overrideprotected Boolean doInBackground (String... params) {// The task Timer must start mTimer. schedule (mTask, 0,500); try {mUrl = Params [0]; // establish the URL URLConnection connection = new URL (mUrl ). openConnection (); // get the file size mFileSize = connection. getContentLength (); Log. d (TAG, "the count of the url content length is:" + mFileSize); // obtain the input stream InputStream is = connection. getInputStream (); // first create a folder File fold = new File (getFolderPath (); if (! Fold. exists () {fold. mkdirs ();} String fileName = ""; // determine the file name: User-defined or url-obtained 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) {// download failed mRunnable. setDatas (icationication_progress_failed, 0); // the error message returned when the download failed. post (mRunnable); if (mTimer! = Null & mTask! = Null) {mTimer. cancel (); mTask. cancel ();} e. printStackTrace (); return false;} // download succeeded mRunnable. setDatas (icationication_progress_succeed, 0); mHandler. post (mRunnable); if (mTimer! = Null & mTask! = Null) {mTimer. cancel (); mTask. cancel () ;}return true ;}// get the file name private String getFileName (String string) {return String. substring (string. lastIndexOf ("/") + 1);} // download the folder path private String getFolderPath () {return Environment. getExternalStorageDirectory (). toString () + "/AsyncTaskDownload/";} // called before the doInBackground method, initialize the UI @ Overrideprotected void onPreExecute () {super. onPreExecute ();} // call after the doInBackground Method Use @ Overrideprotected void onPostExecute (Boolean result) {super. onPostExecute (result); if (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 );}}

Okay. The above is the content shared today ~~ Time (~ Region ﹃~)~ ZZ

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.