Android开发之文件下载,状态时显示下载进度,点击自动安装

在进行软件升级时,需要进行文件下载,在这里实现自定义的文件下载,并在状态栏显示下载进度,下载完成后,点击触发安装。

效果如图:


用于下载文件和显示现在进度的线程类如下:

[java] view plain copy
  1. packagecom.channelsoft.ahzyfis.util;
  2. importjava.io.File;
  3. importjava.io.FileOutputStream;
  4. importjava.io.InputStream;
  5. importjava.net.HttpURLConnection;
  6. importjava.net.URL;
  7. importandroid.app.Notification;
  8. importandroid.app.NotificationManager;
  9. importandroid.app.PendingIntent;
  10. importandroid.content.Context;
  11. importandroid.content.Intent;
  12. importandroid.net.Uri;
  13. importandroid.os.Environment;
  14. importandroid.os.Handler;
  15. importandroid.os.Message;
  16. importandroid.util.Log;
  17. importandroid.widget.RemoteViews;
  18. importandroid.widget.Toast;
  19. importcom.channelsoft.ahzyfis.AhzyFisActivity;
  20. importcom.channelsoft.ahzyfis.R;
  21. /**
  22. *
  23. *
  24. *
    AppFileDownUtils.java
  25. *
    Description:文件下载
  26. *
    Copyright:Copyright(C)2011
  27. *
    Company:
  28. *
    CreateDate:2011-10-19
  29. *
  30. *
  31. *@authorZhanHua
  32. */
  33. publicclassAppFileDownUtilsextendsThread{
  34. privateContextmContext;
  35. privateHandlermHandler;
  36. privateStringmDownloadUrl;//文件下载url,已做非空检查
  37. privateStringmFileName;
  38. privateMessagemsg;
  39. privatefinalStringAPP_FOLDER="DownDemo";//sd卡应用目录
  40. privatefinalStringAPK_FOLDER="apkFile";//下载apk文件目录
  41. publicstaticfinalintMSG_UNDOWN=0;//未开始下载
  42. publicstaticfinalintMSG_DOWNING=1;//下载中
  43. publicstaticfinalintMSG_FINISH=1;//下载完成
  44. publicstaticfinalintMSG_FAILURE=2;//下载失败
  45. privateNotificationManagermNotifManager;
  46. privateNotificationmDownNotification;
  47. privateRemoteViewsmContentView;//下载进度View
  48. privatePendingIntentmDownPendingIntent;
  49. publicAppFileDownUtils(Contextcontext,Handlerhandler,
  50. StringdownloadUrl,StringfileName){
  51. mContext=context;
  52. mHandler=handler;
  53. mDownloadUrl=downloadUrl;
  54. mFileName=fileName;
  55. mNotifManager=(NotificationManager)mContext
  56. .getSystemService(Context.NOTIFICATION_SERVICE);
  57. msg=newMessage();
  58. }
  59. @Override
  60. publicvoidrun(){
  61. try{
  62. if(Environment.getExternalStorageState().equals(
  63. Environment.MEDIA_MOUNTED)){
  64. MessagedowningMsg=newMessage();
  65. downingMsg.what=MSG_DOWNING;
  66. mHandler.sendMessage(downingMsg);
  67. //SD卡准备好
  68. FilesdcardDir=Environment.getExternalStorageDirectory();
  69. //文件存放路径:sdcard/DownDemo/apkFile
  70. Filefolder=newFile(sdcardDir+File.separator+APP_FOLDER
  71. +File.separator+APK_FOLDER);
  72. if(!folder.exists()){
  73. //创建存放目录
  74. folder.mkdir();
  75. }
  76. FilesaveFilePath=newFile(folder,mFileName);
  77. System.out.println(saveFilePath);
  78. mDownNotification=newNotification(
  79. android.R.drawable.stat_sys_download,mContext
  80. .getString(R.string.notif_down_file),System
  81. .currentTimeMillis());
  82. mDownNotification.flags=Notification.FLAG_ONGOING_EVENT;
  83. mDownNotification.flags=Notification.FLAG_AUTO_CANCEL;
  84. mContentView=newRemoteViews(mContext.getPackageName(),
  85. R.layout.custom_notification);
  86. mContentView.setImageViewResource(R.id.downLoadIcon,
  87. android.R.drawable.stat_sys_download);
  88. mDownPendingIntent=PendingIntent.getActivity(mContext,0,newIntent(),0);
  89. booleandownSuc=downloadFile(mDownloadUrl,saveFilePath);
  90. if(downSuc){
  91. msg.what=MSG_FINISH;
  92. Notificationnotification=newNotification(
  93. android.R.drawable.stat_sys_download_done,mContext
  94. .getString(R.string.downloadSuccess),
  95. System.currentTimeMillis());
  96. notification.flags=Notification.FLAG_ONGOING_EVENT;
  97. notification.flags=Notification.FLAG_AUTO_CANCEL;
  98. Intentintent=newIntent(Intent.ACTION_VIEW);
  99. intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  100. intent.setDataAndType(Uri.fromFile(saveFilePath),
  101. "application/vnd.android.package-archive");
  102. PendingIntentcontentIntent=PendingIntent.getActivity(
  103. mContext,0,intent,0);
  104. notification.setLatestEventInfo(mContext,mContext
  105. .getString(R.string.downloadSuccess),null,
  106. contentIntent);
  107. mNotifManager.notify(R.drawable.icon,notification);
  108. }else{
  109. msg.what=MSG_FAILURE;
  110. Notificationnotification=newNotification(
  111. android.R.drawable.stat_sys_download_done,mContext
  112. .getString(R.string.downloadFailure),
  113. System.currentTimeMillis());
  114. notification.flags=Notification.FLAG_AUTO_CANCEL;
  115. PendingIntentcontentIntent=PendingIntent.getActivity(
  116. mContext,0,newIntent(),0);
  117. notification.setLatestEventInfo(mContext,mContext
  118. .getString(R.string.downloadFailure),null,
  119. contentIntent);
  120. mNotifManager.notify(R.drawable.icon,notification);
  121. }
  122. }else{
  123. Toast.makeText(mContext,Environment.getExternalStorageState(),
  124. Toast.LENGTH_SHORT).show();
  125. msg.what=MSG_FAILURE;
  126. }
  127. }catch(Exceptione){
  128. Log.e(AhzyFisActivity.TAG,"AppFileDownUtilscatchException:",e);
  129. msg.what=MSG_FAILURE;
  130. }finally{
  131. mHandler.sendMessage(msg);
  132. }
  133. }
  134. /**
  135. *
  136. *Desc:文件下载
  137. *
  138. *@paramdownloadUrl
  139. *下载URL
  140. *@paramsaveFilePath
  141. *保存文件路径
  142. *@returnture:下载成功false:下载失败
  143. */
  144. publicbooleandownloadFile(StringdownloadUrl,FilesaveFilePath){
  145. intfileSize=-1;
  146. intdownFileSize=0;
  147. booleanresult=false;
  148. intprogress=0;
  149. try{
  150. URLurl=newURL(downloadUrl);
  151. HttpURLConnectionconn=(HttpURLConnection)url.openConnection();
  152. if(null==conn){
  153. returnfalse;
  154. }
  155. //读取超时时间毫秒级
  156. conn.setReadTimeout(10000);
  157. conn.setRequestMethod("GET");
  158. conn.setDoInput(true);
  159. conn.connect();
  160. if(conn.getResponseCode()==HttpURLConnection.HTTP_OK){
  161. fileSize=conn.getContentLength();
  162. InputStreamis=conn.getInputStream();
  163. FileOutputStreamfos=newFileOutputStream(saveFilePath);
  164. byte[]buffer=newbyte[1024];
  165. inti=0;
  166. inttempProgress=-1;
  167. while((i=is.read(buffer))!=-1){
  168. downFileSize=downFileSize+i;
  169. //下载进度
  170. progress=(int)(downFileSize*100.0/fileSize);
  171. fos.write(buffer,0,i);
  172. synchronized(this){
  173. if(downFileSize==fileSize){
  174. //下载完成
  175. mNotifManager.cancel(R.id.downLoadIcon);
  176. }elseif(tempProgress!=progress){
  177. //下载进度发生改变,则发送Message
  178. mContentView.setTextViewText(R.id.progressPercent,
  179. progress+"%");
  180. mContentView.setProgressBar(R.id.downLoadProgress,
  181. 100,progress,false);
  182. mDownNotification.contentView=mContentView;
  183. mDownNotification.contentIntent=mDownPendingIntent;
  184. mNotifManager.notify(R.id.downLoadIcon,
  185. mDownNotification);
  186. tempProgress=progress;
  187. }
  188. }
  189. }
  190. fos.flush();
  191. fos.close();
  192. is.close();
  193. result=true;
  194. }else{
  195. result=false;
  196. }
  197. }catch(Exceptione){
  198. result=false;
  199. Log.e(AhzyFisActivity.TAG,"downloadFilecatchException:",e);
  200. }
  201. returnresult;
  202. }
  203. }

在下载过程中,如果需要和主线程(UI Main Thread)通信,及时让主线程了解下载进度和状态,可用通过Handle向主线程发送Message

进度条显示的布局文件如下:

[html] view plain copy
  1. xmlversion="1.0"encoding="utf-8"?>
  2. <LinearLayout
  3. android:id="@+id/custom_notification"
  4. xmlns:android="http://schemas.android.com/apk/res/android"
  5. android:orientation="horizontal"
  6. android:layout_width="fill_parent"
  7. android:layout_height="fill_parent">
  8. <ImageView
  9. android:id="@+id/downLoadIcon"
  10. android:layout_width="wrap_content"
  11. android:layout_height="wrap_content"
  12. android:layout_marginLeft="5dip"
  13. android:layout_gravity="center_vertical"
  14. />
  15. <TextView
  16. android:layout_height="fill_parent"
  17. android:layout_width="wrap_content"
  18. android:layout_marginLeft="5dip"
  19. android:text="@string/downloadProgress"
  20. android:gravity="center_vertical"
  21. />
  22. <ProgressBar
  23. android:id="@+id/downLoadProgress"
  24. style="?android:attr/progressBarStyleHorizontal"
  25. mce_style="?android:attr/progressBarStyleHorizontal"
  26. android:layout_marginLeft="10dip"
  27. android:layout_width="150dip"
  28. android:layout_height="wrap_content"
  29. android:layout_gravity="center_vertical"
  30. />
  31. <TextView
  32. android:id="@+id/progressPercent"
  33. android:layout_height="fill_parent"
  34. android:layout_width="wrap_content"
  35. android:layout_marginLeft="5dip"
  36. android:gravity="center_vertical"
  37. />
  38. LinearLayout>

你可能感兴趣的:(Android开发之文件下载,状态时显示下载进度,点击自动安装)