鱼C论坛

 找回密码
 立即注册
查看: 2408|回复: 6

【原创】小白马卫士项目总结之版本更新

[复制链接]
发表于 2014-12-4 09:20:09 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 青玄 于 2014-12-4 09:21 编辑

版本版本更新:   
实现原理:通过向服务器端发送请求,获取服务端的版本信息,然后再与本机上的软件进行比对,如果版本不一致的话,那就得更新版本!
首先需要一个打开的欢迎界面:
搜狗截图14年12月04日0001_1.png

在这个欢迎界面打开的时候就要判断此软件的版本是否要更新!

需要说明的是在服务器端这边的时候,发给客户顿的是一个json数据,为了更加明确的说明一下,服务端的大概代码是这样的:

  1. import java.io.File;
  2. import java.io.IOException;
  3. import java.util.ArrayList;
  4. import java.util.List;

  5. import javax.servlet.ServletException;
  6. import javax.servlet.http.HttpServlet;
  7. import javax.servlet.http.HttpServletRequest;
  8. import javax.servlet.http.HttpServletResponse;

  9. import net.sf.json.JSONArray;

  10. import cn.cxrh.daomain.mobile;


  11. public class MobileSafeServlet extends HttpServlet {

  12.         File file = null;
  13.         
  14.         @Override
  15.         protected void doGet(HttpServletRequest req, HttpServletResponse resp)
  16.                         throws ServletException, IOException {
  17.                 // TODO Auto-generated method stub
  18.         
  19.                 List<mobile> mobiles = new ArrayList<mobile>();
  20.                 mobiles.add(new mobile("2.0","http://192.168.128.1:8080/safemobile_server/software/qqliulanqi.apk","小白马提醒您,软件是否更新!^_^!"));
  21.                
  22.                
  23.                 JSONArray json = JSONArray.fromObject(mobiles);
  24.                 resp.getOutputStream().write(json.toString().getBytes("utf-8"));
  25.                
  26.         }


  27.         @Override
  28.         protected void doPost(HttpServletRequest req, HttpServletResponse resp)
  29.                         throws ServletException, IOException {
  30.                 // TODO Auto-generated method stub
  31.                 super.doGet(req, resp);
  32.         }

  33.         
  34. }
复制代码
注意:这里要说明的是,在服务端进行json数据的发送的时候,还需要用到json的jar包!
然后就是客户端这边的处理了!
首先是需要的一个utils工具类:
  1. package com.example.safemobile_test.utils;

  2. import java.io.ByteArrayOutputStream;
  3. import java.io.File;
  4. import java.io.FileOutputStream;
  5. import java.io.IOException;
  6. import java.io.InputStream;
  7. import java.net.HttpURLConnection;
  8. import java.net.MalformedURLException;
  9. import java.net.ProtocolException;
  10. import java.net.URL;

  11. import org.json.JSONArray;
  12. import org.json.JSONException;
  13. import org.json.JSONObject;

  14. import android.app.ProgressDialog;
  15. import android.content.Context;
  16. import android.os.Environment;
  17. import android.util.Log;

  18. import com.example.safemobile_test.daomain.Info;

  19. public class Utils {

  20.         /**
  21.          * 读取服务端发过来的输入流信息,并把它转化为字符串
  22.          * @param is  输入流
  23.          * @return
  24.          * @throws Exception
  25.          */
  26.         public static String readJson(InputStream is) throws Exception
  27.         {
  28.                 ByteArrayOutputStream bao = new ByteArrayOutputStream();
  29.                 byte[] buffer = new byte[1024];
  30.                 int len = -1;
  31.                
  32.                 while((len = is.read(buffer)) != -1)
  33.                 {
  34.                         bao.write(buffer, 0, len);
  35.                 }
  36.                 is.close();
  37.                 bao.close();
  38.                
  39.                 return new String(bao.toByteArray());
  40.                
  41.         }
  42.         /**
  43.          *  用json解析来获取服务端的信息
  44.          * @param path 这个得路径指的是需要访问服务器端的地址
  45.          * @return   返回的是一个javabean的对象
  46.          * @throws Exception
  47.          */
  48.         public static Info getServerInfo(String path) throws  MalformedURLException,ProtocolException,JSONException,IOException,Exception
  49.         {
  50.                 URL url = new URL(path);
  51.                 HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  52.                 conn.setRequestMethod("GET");
  53.                 conn.setReadTimeout(5000);
  54.                 int code = conn.getResponseCode();
  55.                
  56.                 if(code == 200)
  57.                 {
  58.                         InputStream is = conn.getInputStream();
  59.                         
  60.                         JSONArray jsonArray = new JSONArray(readJson(is));
  61.                         Info info = new Info();
  62.                         
  63.                         for(int i=0; i < jsonArray.length(); i++)
  64.                         {
  65.                                 JSONObject object = jsonArray.getJSONObject(i);
  66.                                 info.setVersion(object.getString("version"));
  67.                                 info.setDesc(object.getString("desc"));
  68.                                 info.setPath(object.getString("path"));
  69.                                 Log.i("Utils", object.getString("version"));
  70.                                 
  71.                         }
  72.                         return info;
  73.                 }
  74.                 return null;
  75.                
  76.         }
  77.         /**
  78.          * 从服务端下载需要更新的软件
  79.          * @param file  要存放到sdcard的文件的对象
  80.          * @param path   要访问服务端的地址
  81.          * @param pd  进度条
  82.          * @return   返回存放文件的文件对象
  83.          */
  84.         public static File updateSoft(File file,String path,ProgressDialog pd)
  85.         {
  86.                
  87.                 try {
  88.                         URL url = new URL(path);
  89.                         HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  90.                         conn.setRequestMethod("GET");
  91.                         conn.setReadTimeout(5000);
  92.                         int fileLength = conn.getContentLength();
  93.                         pd.setMax(fileLength);
  94.                         int code = conn.getResponseCode();
  95.                         if(code == 200)
  96.                         {
  97.                                 FileOutputStream fos = new FileOutputStream(file);
  98.                                 
  99.                                 InputStream is= conn.getInputStream();
  100.                                 byte[] buffer = new byte[1024];
  101.                                 
  102.                                 int len = -1;
  103.                                 int total = 0;
  104.                                 
  105.                                 while((len = is.read(buffer)) != -1)
  106.                                 {
  107.                                         total += len;
  108.                                         fos.write(buffer, 0, len);
  109.                                         pd.setProgress(total);
  110.                                 }
  111.                                 fos.close();
  112.                                 is.close();
  113.                                 pd.dismiss();
  114.                                 return file;
  115.                         }
  116.                 } catch (MalformedURLException e) {
  117.                         // TODO Auto-generated catch block
  118.                         e.printStackTrace();
  119.                 } catch (ProtocolException e) {
  120.                         // TODO Auto-generated catch block
  121.                         e.printStackTrace();
  122.                 } catch (IOException e) {
  123.                         // TODO Auto-generated catch block
  124.                         e.printStackTrace();
  125.                 }
  126.                
  127.                 return null;
  128.         }
  129. }
复制代码

然后就是版本更新的主要代码,也是主类的代码:

  1. package com.example.safemobile_test;

  2. import java.io.File;
  3. import java.io.IOException;
  4. import java.net.MalformedURLException;

  5. import org.apache.http.ProtocolException;
  6. import org.json.JSONException;

  7. import com.example.safemobile_test.daomain.Info;
  8. import com.example.safemobile_test.utils.Utils;
  9. import com.example.service.BlackNumberService;

  10. import android.app.Activity;
  11. import android.app.AlertDialog;
  12. import android.app.AlertDialog.Builder;
  13. import android.app.ProgressDialog;
  14. import android.content.DialogInterface;
  15. import android.content.DialogInterface.OnClickListener;
  16. import android.content.Intent;
  17. import android.content.pm.PackageInfo;
  18. import android.content.pm.PackageManager;
  19. import android.content.pm.PackageManager.NameNotFoundException;
  20. import android.net.Uri;
  21. import android.os.Bundle;
  22. import android.os.Environment;
  23. import android.os.Handler;
  24. import android.os.Message;
  25. import android.util.Log;
  26. import android.widget.TextView;
  27. import android.widget.Toast;


  28. public class splashactivity extends Activity {
  29.         protected static final int URL_ERROR = 1;
  30.         protected static final int PROTOCOL_ERROR = 2;
  31.         protected static final int JSON_PARSER_ERROR = 3;
  32.         protected static final int INTERNET_ERROR = 4;
  33.         protected static final int READ_DATA_ERROR = 5;
  34.         protected static final int LOAD_MAIN = 6;
  35.         protected static final int SHOW_DIALOG = 7;
  36.         protected static final int UPDADTE_SOFT = 8;
  37.         protected static final int DOWNLOAD_FILE_FAILURE = 9;
  38.         private TextView tv_splash_version;
  39.         private Handler handler;
  40.         private long startTime = 0;
  41.         private Info info = null;
  42.         private ProgressDialog pd;
  43.         private File file;
  44.         
  45.         @Override
  46.         protected void onCreate(Bundle savedInstanceState) {
  47.                 // TODO Auto-generated method stub
  48.                 super.onCreate(savedInstanceState);
  49.                 setContentView(R.layout.activity_splash);
  50.                 tv_splash_version = (TextView) this.findViewById(R.id.te_splash_version);
  51.                 this.tv_splash_version.setText("版本:" + this.getVersion());  //获取当前的版本
  52.                 handler = new Handler(){

  53.                         @Override
  54.                         public void handleMessage(Message msg) {  //接收消息队列里面的消息
  55.                                 // TODO Auto-generated method stub
  56.                                 switch (msg.what) {
  57.                                 case URL_ERROR:
  58.                                         Toast.makeText(splashactivity.this, "url错误", Toast.LENGTH_LONG).show();
  59.                                         loadMain();
  60.                                         break;
  61.                                 case PROTOCOL_ERROR:
  62.                                         Toast.makeText(splashactivity.this, "请求方式错误", Toast.LENGTH_LONG).show();
  63.                                         loadMain();
  64.                                         break;
  65.                                 case JSON_PARSER_ERROR:
  66.                                         Toast.makeText(splashactivity.this, "JSON解析错误", Toast.LENGTH_LONG).show();
  67.                                         loadMain();
  68.                                         break;
  69.                                 case INTERNET_ERROR:
  70.                                         Toast.makeText(splashactivity.this, "网络链接错误", Toast.LENGTH_LONG).show();
  71.                                         loadMain();
  72.                                         break;
  73.                                 case READ_DATA_ERROR:
  74.                                         Toast.makeText(splashactivity.this, "数据解析错误", Toast.LENGTH_LONG).show();
  75.                                         loadMain();
  76.                                         break;
  77.                                 case LOAD_MAIN:
  78.                                         loadMain();
  79.                                         break;
  80.                                 case SHOW_DIALOG:
  81.                                         showDialog();
  82.                                         break;
  83.                                 case UPDADTE_SOFT:
  84.                                         File file = (File) msg.obj;
  85.                                         installApk(file);
  86.                                         break;
  87.                                 case DOWNLOAD_FILE_FAILURE:
  88.                                         Toast.makeText(splashactivity.this, "文件下载失败", Toast.LENGTH_LONG).show();
  89.                                         loadMain();
  90.                                         break;
  91.                                 }
  92.                         }
  93.                         
  94.                 };
  95.                 /********************************************************************************************/
  96.                 //子线程去检查服务器是否有新的版本
  97.                 this.checkServiceVersion();
  98.         }
  99.         /**
  100.          * ***************此方法是查找此软件的版本是否要更新
  101.          */
  102.         private void checkServiceVersion()
  103.         {
  104.                 new Thread()   //开一个子线程,因为主线程不要太多的工作,不然会容易阻塞的
  105.                 {
  106.                         public void run()
  107.                         {
  108.                                 //连接互联网
  109.                                 startTime = System.currentTimeMillis();
  110.                                 
  111.                                 String path = "http://192.168.128.1:8080/safemobile_server/safemobile_ser";  //访问服务端的地址
  112.                                 Message msg = Message.obtain();    //获得消息对象
  113.                                 try
  114.                                 {
  115.                                         //loadMain();
  116.                                         info = Utils.getServerInfo(path);   //通过json解析获得需要的信息
  117.                                         Log.i("splashactivity", "版本号:"+ info.getVersion());
  118.                                         if(getVersion().equals(info.getVersion()))
  119.                                         {
  120.                                                 msg.what = LOAD_MAIN;
  121.                                         }else
  122.                                         {
  123.                                                 msg.what = SHOW_DIALOG;
  124.                                         }
  125.                                 } catch (MalformedURLException e) {
  126.                                         e.printStackTrace();
  127.                                         msg.what=URL_ERROR;
  128.                                 } catch (ProtocolException e) {
  129.                                                 e.printStackTrace();
  130.                                                 msg.what=PROTOCOL_ERROR;
  131.                                 }catch (JSONException e) {
  132.                                         msg.what=JSON_PARSER_ERROR;
  133.                                 }catch (IOException e) {
  134.                                         e.printStackTrace();
  135.                                         msg.what=INTERNET_ERROR;
  136.                                 }catch (Exception e) {
  137.                                         e.printStackTrace();
  138.                                         msg.what=READ_DATA_ERROR;
  139.                                        
  140.                                 }finally
  141.                                 {
  142.                                         long edntime = System.currentTimeMillis();
  143.                                         long data = edntime-startTime;
  144.                                         if(data < 2000)
  145.                                         {
  146.                                                 try
  147.                                                 {
  148.                                                         Thread.sleep(2000 - data);
  149.                                                 }catch(Exception e)
  150.                                                 {
  151.                                                         e.printStackTrace();
  152.                                                 }
  153.                                        
  154.                                                 handler.sendMessage(msg);
  155.                                         }
  156.                                 }
  157.                         }
  158.                 }.start();
  159.         }
  160.         /**
  161.          * 如果要更新的话就显示一个更新的对话框
  162.          */
  163.         public void showDialog()
  164.         {
  165.                 AlertDialog.Builder builder = new Builder(this);
  166.                 builder.setIcon(R.drawable.ic_launcher);
  167.                 builder.setTitle("升级提醒");
  168.                 builder.setMessage(info.getDesc());
  169.                 builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
  170.                         
  171.                         @Override
  172.                         public void onCancel(DialogInterface dialog) {
  173.                                 // TODO Auto-generated method stub
  174.                                 loadMain();
  175.                         }
  176.                 });
  177.                
  178.                 builder.setNegativeButton("否", new OnClickListener(){

  179.                         @Override
  180.                         public void onClick(DialogInterface dialog, int which) {
  181.                                 loadMain();
  182.                                 
  183.                         }
  184.                         
  185.                 });
  186.                
  187.                 builder.setPositiveButton("是", new OnClickListener(){

  188.                         @Override
  189.                         public void onClick(DialogInterface dialog, int which) {
  190.                                 
  191.                                 if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
  192.                                 {
  193.                                         file = new File(Environment.getExternalStorageDirectory(), info.getPath().substring(info.getPath().lastIndexOf("/")+1));
  194.                                         pd = new ProgressDialog(splashactivity.this);
  195.                                         pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
  196.                                         pd.setIcon(R.drawable.ic_launcher);
  197.                                         pd.setTitle("下载文件");
  198.                                         pd.setMessage("文件正在下载,请稍后...");
  199.                                         pd.show();
  200.                                        
  201.                                         new Thread(){
  202.                                                 public void run()
  203.                                                 {
  204.                                                         File newFile = Utils.updateSoft(file, info.getPath(), pd);
  205.                                                         if(newFile !=null)
  206.                                                         {
  207.                                                                 installApk(newFile);
  208.                                                         }else
  209.                                                         {
  210.                                                                 Log.i("splashactivity-->newfile: ", newFile+"" + info.getPath());
  211.                                                                 Message msg = Message.obtain();
  212.                                                                 msg.what = DOWNLOAD_FILE_FAILURE;
  213.                                                                 handler.sendMessage(msg);
  214.                                                         }
  215.                                                 }
  216.                                         }.start();
  217.                                 }else
  218.                                 {
  219.                                         Toast.makeText(splashactivity.this, "sdcard不可用", Toast.LENGTH_LONG).show();
  220.                                 }
  221.                                 
  222.                         }
  223.                         
  224.                 });
  225.                 builder.show();
  226.         }
  227.         /**
  228.          * 跳转主页面的方法
  229.          */
  230.         public void loadMain()
  231.         {
  232.                 Intent intent = new Intent(this,MainActivity.class);
  233.                 startActivity(intent);
  234. //                Intent blackNumberintent = new Intent(this, BlackNumberService.class);
  235. //                startService(blackNumberintent);
  236.                 finish();
  237.         }
  238.         /**
  239.          *
  240.          * 安装应用
  241.          * @param file
  242.          */
  243.         public void installApk(File file)
  244.         {
  245.                 Intent intent = new Intent();
  246.                 intent.setAction(Intent.ACTION_VIEW);
  247.                 intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
  248.                 startActivity(intent);
  249.                 this.finish();
  250.         }
  251.         
  252.         /**
  253.          * 获取当前的版本
  254.          */
  255.         public String getVersion()
  256.         {
  257.                 PackageManager packageManager = this.getPackageManager();
  258.                 try
  259.                 {
  260.                         PackageInfo info = packageManager.getPackageInfo(getPackageName(), PackageManager.GET_ACTIVITIES);
  261.                         String version = info.versionName;
  262.                         return version;
  263.                 }catch(Exception e)
  264.                 {
  265.                         e.printStackTrace();
  266.                         return "";
  267.                 }
  268.                
  269.         }

  270. }
复制代码
如果地址错误或者连不上网的话,就出现这个:



如果连接正确的话就是:

搜狗截图14年12月04日0033_3.png

然后就进行下载更新:

搜狗截图14年12月04日0033_4.png

完成安装之后就进入到主界面:

搜狗截图14年12月04日0002_2.png



评分

参与人数 3荣誉 +37 鱼币 +37 贡献 +13 收起 理由
小甲鱼 + 30 + 30 + 10 大爱~~~
qingchen + 2 + 2 支持楼主!
拈花小仙 + 5 + 5 + 3 感谢楼主无私奉献!

查看全部评分

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2014-12-4 16:43:04 | 显示全部楼层
强烈支持玄玄哦~
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2014-12-4 18:59:25 | 显示全部楼层
好好,我在看某智的教程,一起学习
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2014-12-4 19:43:27 | 显示全部楼层

呵呵! 小仙客气了!
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2014-12-4 20:10:44 | 显示全部楼层
这感觉好难学的样子
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2015-1-1 23:02:46 | 显示全部楼层
哇塞,太赞了~~
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2015-1-5 15:32:17 | 显示全部楼层

   甲鱼大哥过奖了!
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-5-23 15:45

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表