你的位置:首页 > 软件开发 > 操作系统 > Android应用程序更新并下载

Android应用程序更新并下载

发布时间:2017-03-30 12:00:22
创建一个新类,名为UpdateManager,代码如下: 1 import java.io.BufferedReader; 2 import java.io.File; 3 import java.io.FileOutputStream; 4 import java.io.IOE ...

创建一个新类,名为UpdateManager,代码如下:

Android应用程序更新并下载Android应用程序更新并下载
 1 import java.io.BufferedReader; 2 import java.io.File; 3 import java.io.FileOutputStream; 4 import java.io.IOException; 5 import java.io.InputStream; 6 import java.io.InputStreamReader; 7 import java.net.HttpURLConnection; 8 import java.net.MalformedURLException; 9 import java.net.URL; 10 import com.af.mobile.R; 11 import android.app.AlertDialog; 12 import android.app.Dialog; 13 import android.app.AlertDialog.Builder; 14 import android.content.Context; 15 import android.content.DialogInterface; 16 import android.content.Intent; 17 import android.content.DialogInterface.OnClickListener; 18 import android.content.pm.PackageManager.NameNotFoundException; 19 import android.net.Uri; 20 import android.os.Environment; 21 import android.os.Handler; 22 import android.os.Message; 23 import android.view.LayoutInflater; 24 import android.view.View; 25 import android.widget.ProgressBar; 26 import android.widget.Toast; 27  28  29 public class UpdateManager 30 {private URL url=null; 31   /* 下载中 */ 32   private static final int DOWNLOAD = 1; 33   /* 下载结束 */ 34   private static final int DOWNLOAD_FINISH = 2; 35   /* 保存解析的*/ 36   //HashMap<String, String> mHashMap; 37   /* 下载保存路径 */ 38   private String mSavePath; 39   /* 记录进度条数量 */ 40   private int progress; 41   /* 是否取消更新 */ 42   private boolean cancelUpdate = false; 43  44   private Context mContext; 45   /* 更新进度条 */ 46   private ProgressBar mProgress; 47   private Dialog mDownloadDialog; 48  49   private Handler mHandler = new Handler() 50   { 51     public void handleMessage(Message msg) 52     { 53       switch (msg.what) 54       { 55       // 正在下载 56       case DOWNLOAD: 57         // 设置进度条位置 58         mProgress.setProgress(progress); 59         break; 60       case DOWNLOAD_FINISH: 61         // 安装文件 62         installApk(); 63         break; 64       default: 65         break; 66       } 67     }; 68   }; 69  70   public UpdateManager(Context context) 71   { 72     this.mContext = context; 73   } 74  75   public void checkUpdate() 76   { 77     if (isUpdate()) 78     { 79       showNoticeDialog(); 80     } else 81     { 82        83     } 84   } 85  86   /** 87    * 检查软件是否有更新版本 88    *  89    * @return 90   */ 91   private boolean isUpdate() 92   { 93     // 获取当前软件版本 94     Double versionCode = getVersionCode(mContext); 95    96       Double serviceCode = 1.2; 97       // 版本判断 98       if (serviceCode > versionCode) 99       {100         return true;101       }102     103     return false;104   }105 106   // 获取软件版本号107   108   private Double getVersionCode(Context context)109   {110     Double versionCode = 0.0;111     try112     {113       // 获取软件版本号,对应AndroidManifest.114       versionCode = (double) context.getPackageManager().getPackageInfo("com.af.mobile", 0).versionCode;115     } catch (NameNotFoundException e)116     {117       e.printStackTrace();118     }119     return versionCode;120   }121 122   123   //显示软件更新对话框124   125   private void showNoticeDialog()126   {127     AlertDialog.Builder builder = new Builder(mContext);128     builder.setTitle("软件更新");129     String string=download("http://192.168.0.102:9313/daojuserver/uploads/version.//130     builder.setMessage(string);131 132     builder.setPositiveButton("更新", new OnClickListener()133     {134       @Override135       public void onClick(DialogInterface dialog, int which)136       {137         dialog.dismiss();138         // 显示下载对话框139         showDownloadDialog();140       }141     });142     // 稍后更新143     builder.setNegativeButton("稍后更新", new OnClickListener()144     {145       @Override146       public void onClick(DialogInterface dialog, int which)147       {148         dialog.dismiss();149       }150     });151     Dialog noticeDialog = builder.create();152     noticeDialog.show();153   }154 155   // 显示软件下载对话框156   157   private void showDownloadDialog()158   {159     // 构造软件下载对话框160     AlertDialog.Builder builder = new Builder(mContext);161     builder.setTitle("djfkjd");//提示信息内容162     // 给下载对话框增加进度条163     final LayoutInflater inflater = LayoutInflater.from(mContext);164     View v = inflater.inflate(R.layout.softupdate_progress, null);165     mProgress = (ProgressBar) v.findViewById(R.id.update_progress);166     builder.setView(v);167     // 取消更新168     builder.setNegativeButton("取消更新", new OnClickListener()169     {170       @Override171       public void onClick(DialogInterface dialog, int which)172       {173         dialog.dismiss();174         // 设置取消状态175         cancelUpdate = true;176       }177     });178     mDownloadDialog = builder.create();179     mDownloadDialog.show();180     // 现在文件181     downloadApk();182   }183 184 185   private void downloadApk()186   {187     // 启动新线程下载软件188     new downloadApkThread().start();189   }190 191   private class downloadApkThread extends Thread192   {193     @Override194     public void run()195     {196       try197       {198         // 判断SD卡是否存在,并且是否具有读写权限199         if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))200         {201           // 获得存储卡的路径202           String sdpath = Environment.getExternalStorageDirectory() + "/";203           mSavePath = sdpath + "download";204           URL url = new URL("http://192.168.0.102:9313/daojuserver/uploads/SpMobile.apk");//apk下载地址地址205           // 创建连接206           HttpURLConnection conn = (HttpURLConnection) url.openConnection();207           conn.connect();208           // 获取文件大小209           int length = conn.getContentLength();210           // 创建输入流211           InputStream is = conn.getInputStream();212 213           File file = new File(mSavePath);214           if (!file.exists())215           {216             file.mkdir();217           }218           File apkFile = new File(mSavePath, "dhfudh");219           FileOutputStream fos = new FileOutputStream(apkFile);220           int count = 0;221           // 缓存222           byte buf[] = new byte[1024];223           // 写入到文件中224           do225           {226             int numread = is.read(buf);227             count += numread;228             // 计算进度条位置229             progress = (int) (((float) count / length) * 100);230             // 更新进度231             mHandler.sendEmptyMessage(DOWNLOAD);232             if (numread <= 0)233             {234               mHandler.sendEmptyMessage(DOWNLOAD_FINISH);235               break;236             }237             fos.write(buf, 0, numread);238           } while (!cancelUpdate);239           fos.close();240           is.close();241         }242       } catch (MalformedURLException e)243       {244         e.printStackTrace();245       } catch (IOException e)246       {247         e.printStackTrace();248       }249       // 取消下载对话框显示250       mDownloadDialog.dismiss();251     }252   };253   254   private void installApk()255   {256     File apkfile = new File(mSavePath, "dhfudh");257     if (!apkfile.exists())258     {259       return;260     }261     // 通过Intent安装APK文件262     Intent i = new Intent(Intent.ACTION_VIEW);263     i.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");264     mContext.startActivity(i);265   }266   public String download(String urlString)267   {268     StringBuffer sbBuffer=new StringBuffer();269     String line=null;270     BufferedReader buffer=null;271   try {272     url=new URL(urlString);273     HttpURLConnection urlConn=(HttpURLConnection) url.openConnection();274     buffer=new BufferedReader(new InputStreamReader(urlConn.getInputStream()));275     while((line=buffer.readLine())!=null)276     {277       sbBuffer.append(line);278     }279   } catch (Exception e) {280     // TODO: handle exception281     e.printStackTrace();282   }283   finally284   {285     try {286       buffer.close();287     } catch (Exception e2) {288       // TODO: handle exception289       e2.printStackTrace();290     }291   }292   return sbBuffer.toString();293   }294 }

 


原标题:Android应用程序更新并下载

关键词:Android

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

可能感兴趣文章

我的浏览记录