android做个版本下载更新

流程:1.到服务器那边拉去配置文件,然后解析配置文件来获取应用的地址,版本号,大小,md5和配置的更新的方式(可选更新与强制更新);

   2.断点续传方式拉去apk。

一下为代码:


[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. import java.io.BufferedInputStream;  
  2. import java.io.BufferedReader;  
  3. import java.io.File;  
  4. import java.io.IOException;  
  5. import java.io.InputStream;  
  6. import java.io.InputStreamReader;  
  7. import java.io.RandomAccessFile;  
  8. import java.net.HttpURLConnection;  
  9. import java.net.URL;  
  10.   
  11. import org.apache.http.HttpResponse;  
  12. import org.apache.http.HttpStatus;  
  13. import org.apache.http.client.ClientProtocolException;  
  14. import org.apache.http.client.HttpClient;  
  15. import org.apache.http.client.methods.HttpGet;  
  16. import org.apache.http.impl.client.DefaultHttpClient;  
  17. import org.apache.http.protocol.HTTP;  
  18. import org.apache.http.util.EntityUtils;  
  19. import org.json.JSONObject;  
  20.   
  21.   
  22. import com.longjiang.youzhong.R;  
  23. import com.uzone.util.Md5Check;  
  24.   
  25.   
  26. import android.app.Activity;  
  27. import android.app.AlertDialog;  
  28. import android.app.ProgressDialog;  
  29. import android.content.DialogInterface;  
  30. import android.content.Intent;  
  31. import android.content.pm.PackageInfo;  
  32. import android.content.pm.PackageManager.NameNotFoundException;  
  33. import android.net.Uri;  
  34. import android.os.AsyncTask;  
  35. import android.os.Bundle;  
  36. import android.os.Environment;  
  37. import android.os.Handler;  
  38. import android.os.Message;  
  39. import android.util.Log;  
  40. import android.view.WindowManager;  
  41.   
  42.   
  43. //下载配置的资源文件->解析资源文件来获取版本号和apk的下载地址、更新的方式的信息->对比版本号:(1)不需要更新,直接返回;(2)需要更新:a,强制更新 ;b,可选择更新.更新流程1.下载apk并且提示进度,下载完后自动安装  
  44. public  class VersionActivity extends Activity{  
  45.   
  46.     //请求配置服务器的配置文件url  
  47.     private static String requestUrl="http://192.168.1.46/updateversion/updateversion.php";  
  48.     private static String version ;  
  49.     private static String apkDownUrl;  
  50.     private static int updateType;//1,表示可以选择更新;2,表示强制更新  
  51.     private static ProgressDialog checkDialog;  
  52.     private static Activity context;      
  53.     private static  MyHandler mHandler;   
  54.     private static  int retry;   
  55.     private static String path;   
  56.     private static String packageName;  
  57.     private static String md5;    
  58.     private static long  fileTotalSize;   
  59.     private static ProgressDialog pbar;  
  60.     private String tag="VersionActivity";  
  61.     private int TryDownTotal=5;//下载失败再次尝试的次数  
  62.     private static String fileName="longjiang.apk";   
  63.     private interface  DialogHandler{  
  64.           void fun();  
  65.     }  
  66.       
  67.     @Override  
  68.     protected void onCreate(Bundle savedInstanceState) {  
  69.         super.onCreate(savedInstanceState);  
  70.         getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);  
  71.         setContentView(R.layout.yzupdate);  
  72.         pbar =new ProgressDialog(this);  
  73.           
  74.         context=this;  
  75.         mHandler=new MyHandler();  
  76.         checkDialog = ProgressDialog.show(this, null, getString(R.string.version_check_msg), true);  
  77.         checkDialog.setCancelable(false);  
  78.         checkVersion();  
  79.       
  80.       
  81.     }  
  82.       
  83.       
  84.       
  85.     public static void checkVersion()  
  86.     {  
  87.           
  88.         //下载配置服务器的配置文件  
  89.         new Thread(new Runnable() {  
  90.             @Override  
  91.             public void run() {  
  92.         // HttpGet连接对象    
  93.         HttpGet httpRequest = new HttpGet(requestUrl);    
  94.         try {    
  95.             // 取得HttpClient对象    
  96.             HttpClient httpclient = new DefaultHttpClient();    
  97.             // 请求HttpClient,取得HttpResponse    
  98.             HttpResponse httpResponse = httpclient.execute(httpRequest);    
  99.             // 请求成功    
  100.             if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {    
  101.                 String jsonResult = EntityUtils.toString(  
  102.                         httpResponse.getEntity(), HTTP.UTF_8);  
  103.                   
  104.                 JSONObject paramsjson = new JSONObject(jsonResult);  
  105.                 version=paramsjson.optString("version");  
  106.                 apkDownUrl=paramsjson.optString("apkDownUrl");  
  107.                 updateType=paramsjson.optInt("updateType");       
  108.                 md5=paramsjson.optString("md5");      
  109.                 fileTotalSize=Long.valueOf(paramsjson.optString("size"));     
  110.                   
  111.                 Message msg = Message.obtain(mHandler);  
  112.                 msg.what = 0;  
  113.                 //msg.obj = resultObj;  
  114.                 mHandler.sendMessage(msg);  
  115.             } else {    
  116.                //提示下载出错了  
  117.                   
  118.                 Message msg = Message.obtain(mHandler);  
  119.                 msg.what = 1;  
  120.                 //msg.obj = resultObj;  
  121.                 mHandler.sendMessage(msg);  
  122.                   
  123.             }    
  124.         } catch (ClientProtocolException e) {    
  125.             
  126.         } catch (IOException e) {    
  127.              
  128.         } catch (Exception e) {    
  129.          
  130.         }    
  131.             }  
  132.           
  133.             }).start();  
  134.   
  135.     }  
  136.       
  137.       
  138.       
  139.       
  140.       
  141.      //只考虑两种状态,左边的button单独存在或者两个button同时存在   
  142.     private static void showDialog(String title,String content,String rightButton,String leftButton,final DialogHandler Rhandler,final DialogHandler Lhandler)  
  143.     {  
  144.           
  145.           
  146.         if(rightButton==null)  
  147.         {  
  148.             new AlertDialog.Builder(context)  
  149.                     .setTitle(title)  
  150.                     .setMessage(content)  
  151.                     .setCancelable(false)  
  152.                     .setPositiveButton(leftButton,  
  153.                             new DialogInterface.OnClickListener() {  
  154.                                     public void onClick(DialogInterface dialog, int id) {  
  155.                                         dialog.dismiss();  
  156.                                                   
  157.                                         if(Lhandler!=null)  
  158.                                             Lhandler.fun();  
  159.                                                   
  160.                                     }  
  161.                                 }).show();  
  162.               
  163.         }  
  164.           
  165.         else if(leftButton!=null&&rightButton!=null)  
  166.         {  
  167.   
  168.             new AlertDialog.Builder(context)  
  169.                     .setTitle(title)  
  170.                     .setMessage(content)  
  171.                     .setCancelable(false)  
  172.                     .setPositiveButton(leftButton,  
  173.                             new DialogInterface.OnClickListener() {  
  174.                                 public void onClick(DialogInterface dialog, int id) {  
  175.                                     dialog.dismiss();  
  176.                                     Lhandler.fun();  
  177.                                 }  
  178.                             })  
  179.                     .setNegativeButton(rightButton,  
  180.                             new DialogInterface.OnClickListener() {  
  181.                                 public void onClick(DialogInterface dialog, int whichButton) {  
  182.                                     dialog.dismiss();  
  183.                                       
  184.                                     if(Rhandler!=null)  
  185.                                         Rhandler.fun();  
  186.                                 }  
  187.                             }).show();  
  188.               
  189.         }  
  190.     }  
  191.   
  192.         
  193.       private  class MyHandler extends Handler {  
  194.   
  195.             @Override  
  196.             public void handleMessage(final Message msg) {  
  197.   
  198.   
  199.                 switch (msg.what) {  
  200.                 case 0:  
  201.                     //检查apk的版本号  
  202.                     checkDialog.dismiss();  
  203.                     PackageInfo info;    
  204.                     try {    
  205.                         info = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);    
  206.                         // 当前应用的版本名称    
  207.                         //String versionName = info.versionName;    
  208.                         // 当前版本的版本号    
  209.                         int versionCode = info.versionCode;    
  210.                         packageName=info.applicationInfo.packageName;  
  211.                         //启动升级  
  212.                         if(versionCode<Integer.valueOf(version))  
  213.                         {  
  214.                             //升级代码  
  215.                               
  216.                             //可选择的更新  
  217.                             if(updateType==1)//test 0  
  218.                             {  
  219.                                  showDialog(context.getString(R.string.updatetitle),"是否从当前版本号"+versionCode+"升级到版本号"+version,"现在升级","以后再更新",new DialogHandler(){  
  220.                                        
  221.                                      public void fun(){       
  222.                                            
  223.                                          predownloadapk();  
  224.                                            
  225.                                         }                  
  226.                                  }  
  227.                                  , new DialogHandler(){  
  228.                                        
  229.                                      public void fun(){ startGame(); }                 
  230.                                        
  231.                                  });  
  232.                                   
  233.                             }  
  234.                             //强制更新  
  235.                             else if(updateType==1)  
  236.                             {  
  237.                                  showDialog(context.getString(R.string.updatetitle),"请点击确定更新为最新版本:"+version,null,"确定",null, new DialogHandler(){  
  238.                                        
  239.                                      public void fun(){   
  240.    
  241.                                          predownloadapk();  
  242.   
  243.                                          }                 
  244.                                  });  
  245.                             }  
  246.                         }  
  247.                         //不用下载apk,直接进入游戏  
  248.                         else  
  249.                         {  
  250.                             startGame();  
  251.                         }  
  252.                           
  253.                     } catch (NameNotFoundException e) {    
  254.                         e.printStackTrace();    
  255.                     }    
  256.                       
  257.                     break;  
  258.                 case 1:  
  259.                     //下载配置文件出错了  
  260.                      showDialog(context.getString(R.string.networkerror),context.getString(R.string.comfirmexist),null,context.getString(R.string.comfirmexist),null, new DialogHandler(){  
  261.                            
  262.                          public void fun(){ context.finish(); }                
  263.                            
  264.                      });  
  265.                     break;  
  266.                       
  267.                 case 2:  
  268.                       
  269.                        
  270.                     break;    
  271.                       
  272.                 case 3:  
  273.                     //启动安卓应用  
  274.                     if(md5.equals(Md5Check.md5sum(new File(path+"/"+fileName))))  
  275.                     {  
  276.                         ReplaceLaunchApk(path+"/"+fileName);  
  277.                     }  
  278.                     else if(retry<TryDownTotal)  
  279.                     {  
  280.                         retry++;  
  281.                         downloadapk();  
  282.                           
  283.                     }  
  284.                     else  
  285.                     {  
  286.                           
  287.                          showDialog(context.getString(R.string.networkerror),context.getString(R.string.comfirmexist),null,context.getString(R.string.comfirmexist),null, new DialogHandler(){  
  288.                                
  289.                              public void fun(){ context.finish(); }                
  290.                                
  291.                          });  
  292.                           
  293.                     }  
  294.                     break;  
  295.                       
  296.                 case 4:  
  297.                     //t卡不存在  
  298.                      showDialog("错误","请插入外部存储卡",null,context.getString(R.string.comfirmexist),null, new DialogHandler(){  
  299.                            
  300.                          public void fun(){ context.finish(); }                
  301.                            
  302.                      });  
  303.                     break;  
  304.                       
  305.                 case 5:  
  306.                     //t卡空降不够  
  307.                      showDialog("错误","存储卡剩余的空间不足,请先删掉些大的文件",null,context.getString(R.string.comfirmexist),null, new DialogHandler(){  
  308.                            
  309.                          public void fun(){ context.finish(); }                
  310.                            
  311.                      });  
  312.                     break;  
  313.                       
  314.                       
  315.                 default:  
  316.                     break;  
  317.                 }  
  318.             }  
  319.         }  
  320.   
  321.         
  322.   private void startGame()  
  323.       {  
  324.             Intent intent = new Intent(context, LongjiangActivity.class);  
  325.             startActivity(intent);    
  326.             context.finish();  
  327.             
  328.       }  
  329.     
  330.     
  331. //从url中下载apk  
  332.   private void predownloadapk()  
  333.   {  
  334.       retry=0;  
  335.   
  336.     //创建文件    
  337.       downloadapk();    
  338.   }  
  339.     
  340.   private void downloadapk()  
  341.   {  
  342.       //  
  343.       pbar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);  
  344.       pbar.setTitle("龙将游戏的版本号将升级为:"+version);  
  345.       pbar.setMessage("正在下载中,请稍后...");  
  346.       pbar.setCancelable(false);  
  347.       pbar.setMax(100);  
  348.       pbar.setProgress(0);  
  349.       pbar.show();  
  350.   
  351.       new DownloadFilesTask().execute(apkDownUrl);  
  352.         
  353.   }  
  354.     
  355.     
  356.   // 异步任务类  
  357.   class DownloadFilesTask extends AsyncTask<String,Integer,Long> {  
  358.   
  359.       private URL  url; // 资源位置  
  360.       private long beginPosition; // 开始位置  
  361.   
  362.   
  363.   
  364.   
  365.       @Override  
  366.       protected Long doInBackground(String... params) {  
  367.             
  368.             
  369.           InputStream inputStream = null;  
  370.           HttpURLConnection httpURLConnection =null;  
  371.           RandomAccessFile output = null;  
  372.           try {  
  373.               // 获取连接对象h  
  374.                 
  375.                 
  376.               //创建包名的文件夹  
  377.               boolean hasSD = Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED);          //只检验是否可读且可  
  378.               if(!hasSD)  
  379.               {  
  380.                     
  381.                 Message msg = Message.obtain(mHandler);  
  382.                 msg.what = 4;  
  383.                 mHandler.sendMessage(msg);  
  384.                 return (long) 0;  
  385.               }  
  386.               long availablesize=getUsableStorage();  
  387.               if(availablesize<100)  
  388.               {  
  389.                     
  390.                 Message msg = Message.obtain(mHandler);  
  391.                 msg.what = 5;  
  392.                 mHandler.sendMessage(msg);   
  393.                 return (long) 0;  
  394.               }  
  395.                 
  396.               String sddir=getSDCardPath() ;  
  397.                 
  398.               path=sddir+"/"+packageName;  
  399.               File destDir = new File(sddir+"/"+packageName);  
  400.               if (!destDir.exists()) {  
  401.                destDir.mkdirs();  
  402.               }  
  403.                 
  404.               File outFile = new File(sddir+"/"+packageName+"/"+fileName);    
  405.               if (!outFile.exists()) {    
  406.                     try {    
  407.                         //在指定的文件夹中创建文件    
  408.                         outFile.createNewFile();    
  409.                   } catch (Exception e) {    
  410.                   }    
  411.               }   
  412.                 
  413.            // 通过文件创建输出流对象RandomAccessFile,r:读 w:写 d:删除  
  414.          output = new RandomAccessFile(outFile, "rw");  
  415.           // 设置写入位置  
  416.        
  417.          long lenth=outFile.length();      
  418.   
  419.            
  420.          if(fileTotalSize==lenth)    
  421.          {  
  422.                
  423.             if(md5.equals(Md5Check.md5sum(outFile)) )  
  424.             {  
  425.                   
  426.                 //下载完的处理  
  427.                 publishProgress(100);  
  428.                 Message msg = Message.obtain(mHandler);  
  429.                 msg.what = 3;  
  430.                 mHandler.sendMessage(msg);  
  431.                 return lenth;  
  432.             }     
  433.             else  
  434.             {  
  435.                 beginPosition=0;  
  436.                   
  437.             }  
  438.   
  439.          }  
  440.          else  
  441.          {  
  442.              beginPosition=lenth;  
  443.          }  
  444.   
  445.               // 设置断点续传的开始位置   
  446.          url=new URL(params[0]);  
  447.          httpURLConnection = (HttpURLConnection) url.openConnection();  
  448.          httpURLConnection = (HttpURLConnection)url.openConnection();   
  449.          httpURLConnection.setAllowUserInteraction(true);   
  450.          httpURLConnection.setRequestMethod("GET");   
  451.          httpURLConnection.setReadTimeout(4000);   
  452.         // httpURLConnection.setRequestProperty("User-Agent","NetFox");   
  453.          httpURLConnection.setRequestProperty("Range", "bytes=" + beginPosition + "-");   
  454.          inputStream = httpURLConnection.getInputStream();   
  455.                 
  456.          output.seek(beginPosition);        
  457.          byte[] buf = new byte[1024*100];  
  458.          int readsize=0;  
  459.          // 进行循环输出  
  460.          while ((readsize=inputStream.read(buf)) != -1) {  
  461.                
  462.                
  463.                
  464.              output.write(buf, 0, readsize);  
  465.              beginPosition+=readsize;  
  466.              publishProgress((int)(beginPosition*100.0f/fileTotalSize));   
  467.   
  468.          }  
  469.            
  470.   
  471.           } catch (Exception ex) {  
  472.               ex.printStackTrace();  
  473.           }  
  474.           finally {   
  475.   
  476.               if(inputStream!=null) {   
  477.                   try {   
  478.                       inputStream.close();   
  479.   
  480.                             
  481.                      if(output!=null) {   
  482.                         output.close();   
  483.                       }   
  484.                       if(httpURLConnection!=null) {   
  485.                           httpURLConnection.disconnect();   
  486.                       }   
  487.                     }   
  488.                   catch (IOException e) {   
  489.                       e.printStackTrace();   
  490.                   }   
  491.               }   
  492.           }  
  493.           return beginPosition;  
  494.       }  
  495.         
  496.       /**   
  497.        * 更新下载进度,当publishProgress方法被调用的时候就会自动来调用这个方法   
  498.        */   
  499.       @Override   
  500.       protected void onProgressUpdate(Integer... values) {   
  501.           super.onProgressUpdate(values);   
  502.             
  503.           pbar.setProgress(values[0]);  
  504.           if(values[0]==100)  
  505.           {  
  506.             Message msg = Message.obtain(mHandler);  
  507.             msg.what = 3;  
  508.             mHandler.sendMessage(msg);    
  509.           }  
  510.       }  
  511.       //下载完的回调  
  512.       @Override   
  513.       protected void onPostExecute(Long size)  
  514.       {  
  515.   
  516.       }  
  517.   }  
  518.     
  519.   
  520.     
  521.   /**  
  522.    * 获取外置SD卡路径  
  523.    *   
  524.    * @return  
  525.    */  
  526.   public static String getSDCardPath() {  
  527.   
  528.       return Environment.getExternalStorageDirectory().getPath();  
  529.   }   
  530.     
  531.     
  532.     
  533.  /*   
  534.   * 返回SD卡可用容量  --#   
  535.   */    
  536.   private static long getUsableStorage(){    
  537.     String sDcString = android.os.Environment.getExternalStorageState();    
  538.           
  539.      if (sDcString.equals(android.os.Environment.MEDIA_MOUNTED)) {    
  540.          File pathFile = android.os.Environment    
  541.                  .getExternalStorageDirectory();    
  542.   
  543.          android.os.StatFs statfs = new android.os.StatFs(pathFile.getPath());    
  544.              
  545.      // 获取可供程序使用的Block的数量    
  546.          long nAvailaBlock = statfs.getAvailableBlocks();    
  547.   
  548.          long nBlocSize = statfs.getBlockSize();    
  549.   
  550.      // 计算 SDCard 剩余大小MB    
  551.          return nAvailaBlock * nBlocSize /1024 /1024;    
  552.      }    
  553.      else{    
  554.          return -1;    
  555.      }    
  556.          
  557.   
  558.  }     
  559.     
  560.     
  561.     
  562.   //启动安装替换apk  
  563.   private void ReplaceLaunchApk(String apkpath) {  
  564.       // TODO Auto-generated method stub  
  565.       File file=new File(apkpath);  
  566.       if(file.exists())  
  567.       {  
  568.           Log.e(tag, file.getName());  
  569.           Intent intent = new Intent();  
  570.           intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
  571.           intent.setAction(android.content.Intent.ACTION_VIEW);  
  572.           intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");  
  573.           startActivity(intent);  
  574.           context.finish();  
  575.       }  
  576.       else  
  577.       {  
  578.           Log.e(tag, "File not exsit:"+apkpath);  
  579.       }  
  580. }     
  581. }  




参考:http://www.eoeandroid.com/thread-1081-1-1.html等其他


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值