`
从此醉
  • 浏览: 1040097 次
  • 性别: Icon_minigender_1
  • 来自: US
社区版块
存档分类
最新评论

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

 
阅读更多

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

效果如图:


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

  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. *<dl>
  24. *<dt>AppFileDownUtils.java</dt>
  25. *<dd>Description:文件下载</dd>
  26. *<dd>Copyright:Copyright(C)2011</dd>
  27. *<dd>Company:</dd>
  28. *<dd>CreateDate:2011-10-19</dd>
  29. *</dl>
  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

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

  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>

分享到:
评论

相关推荐

    Google Android SDK开发范例大全(第3版) 1/5

    余志龙、陈昱勋、郑名杰、陈小风,分别来自手机制造业、电视媒体业、网络、电信产业、软件开发等领域,擅长嵌入式系统软件设计、J2ME游戏开发、Android开发,以及12EE、JSP、Servlet、Java Bean、PHP、C#等程序语言...

    Google Android SDK开发范例大全(第3版) 4/5

    余志龙、陈昱勋、郑名杰、陈小风,分别来自手机制造业、电视媒体业、网络、电信产业、软件开发等领域,擅长嵌入式系统软件设计、J2ME游戏开发、Android开发,以及12EE、JSP、Servlet、Java Bean、PHP、C#等程序语言...

    Google Android SDK开发范例大全(第3版) 3/5

    余志龙、陈昱勋、郑名杰、陈小风,分别来自手机制造业、电视媒体业、网络、电信产业、软件开发等领域,擅长嵌入式系统软件设计、J2ME游戏开发、Android开发,以及12EE、JSP、Servlet、Java Bean、PHP、C#等程序语言...

    Google Android SDK开发范例大全(第3版) 5/5

    余志龙、陈昱勋、郑名杰、陈小风,分别来自手机制造业、电视媒体业、网络、电信产业、软件开发等领域,擅长嵌入式系统软件设计、J2ME游戏开发、Android开发,以及12EE、JSP、Servlet、Java Bean、PHP、C#等程序语言...

    《Google Android SDK开发范例大全(第3版)》.pdf

     全书共分11章,主要以范例集的方式来讲述android的知识点,详细介绍了开发android的人机交互界面、android常用的开发控件、android手机收发短信等通信服务、开发android手机的自动服务功能和娱乐多媒体功能以及...

    Google Android SDK开发范例大全(第3版)part2

     全书共分11章,主要以范例集的方式来讲述Android的知识点,详细介绍了开发Android的人机交互界面、Android常用的开发控件、Android手机收发短信等通信服务、开发Android手机的自动服务功能和娱乐多媒体功能以及...

    Google Android SDK开发范例大全(PDF高清完整版1)(4-1)

    Google Android SDK开发范例大全(完整版)共4个分卷 目录 第1章 了解.深入.动手做. 1.1 红透半边天的Android 1.2 本书目的及涵盖范例范围 1.3 如何阅读本书 1.4 使用本书范例 1.5 参考网站 第2章 Android初体验 2.1...

    Google Android SDK开发范例大全(PDF完整版4)(4-4)

    Google Android SDK开发范例大全(完整版)共4个分卷 目录 第1章 了解.深入.动手做. 1.1 红透半边天的Android 1.2 本书目的及涵盖范例范围 1.3 如何阅读本书 1.4 使用本书范例 1.5 参考网站 第2章 Android初体验 2.1...

    Google Android SDK开发范例大全(PDF高清完整版3)(4-3)

    Google Android SDK开发范例大全(完整版)共4个分卷 目录 第1章 了解.深入.动手做. 1.1 红透半边天的Android 1.2 本书目的及涵盖范例范围 1.3 如何阅读本书 1.4 使用本书范例 1.5 参考网站 第2章 Android初体验 2.1...

    Google Android SDK开发范例大全的目录

    8.14 远程下载安装Android程序——APKInstaller的应用 8.15 手机下载看3gp影片——Runnable混搭SurfaceView 8.16 访问网站LoginAPI——远程服务器验证程序运行权限 8.17 地震速报!——HttpURLConnection与Service...

    google android sdk开发范例大全 第二版 PDF 光盘代码

    google android sdk开发范例大全 第二版 PDF 和 随书光盘代码 ISBN:9787115229649 目录 第1章 了解、深入、动手做   1.1 红透半边天的Android   1.2 本书目的及范例涵盖范围   1.3 如何阅读本书 ...

    Google Android SDK开发范例大全(完整版附部分源码).pdf

    Google Android SDK开发范例大全(完整版) 包含部分书中源码 目录 第1章 了解.深入.动手做. 1.1 红透半边天的Android 1.2 本书目的及涵盖范例范围 1.3 如何阅读本书 1.4 使用本书范例 1.5 参考网站 第2章 ...

    Google Android SDK开发范例大全(完整版)

    余志龙,来自于手机制造业、电视媒体业、网络、电信产业、软件开发等领域,擅长嵌入式系统软件设计、J2ME游戏开发、Android开发,以及J2EE、JSP、Servlet、JavaBeans、PHP、C#等程序语言,熟悉面向对象技术与Eclipse...

    Android开发资料合集-World版!

    1、ANDROID文件系统与应用程序架构 7 1.1、ANDROID 文件系统 7 1.2、ANDROID应用程序架构 9 2、ANDROID应用程序结构 11 2.1、ACTIVITY 12 2.1.1、概述 12 2.1.2、Activity的生命周期 15 2.1.3、Activity 的创建 16 ...

    Android 开发技巧

    1、ANDROID文件系统与应用程序架构 7 1.1、ANDROID 文件系统 7 1.2、ANDROID应用程序架构 9 2、ANDROID应用程序结构 11 2.1、ACTIVITY 12 2.1.1、概述 12 2.1.2、Activity的生命周期 15 2.1.3、Activity 的创建 16 ...

    Google Android SDK 开发范例大全01

    Google Android SDK开发范例大全 目录 第1章 了解.深入.动手做. 1.1 红透半边天的Android 1.2 本书目的及涵盖范例范围 1.3 如何阅读本书 1.4 使用本书范例 1.5 参考网站 第2章 Android初体验 2.1 安装AndroidSDK与...

Global site tag (gtag.js) - Google Analytics