android自动更新新版模块(简单,实用)

来源:互联网 发布:程序员空闲 编辑:程序博客网 时间:2024/04/30 23:47

http://blog.csdn.net/hytfly/article/details/8549858

每一个好的android应用都得有自动更新的模块

直接上代码了,非常简单。

[java] view plaincopyprint?
  1. public class MainActivity extends Activity {  
  2.     /** Called when the activity is first created. */  
  3.     String newVerName = "";//新版本名称  
  4.     int newVerCode = -1;//新版本号  
  5.     ProgressDialog pd = null;  
  6.     String UPDATE_SERVERAPK = "ApkUpdateAndroid.apk";  
  7.     @Override  
  8.     public void onCreate(Bundle savedInstanceState) {  
  9.         super.onCreate(savedInstanceState);  
  10.         setContentView(R.layout.main);  
  11.         if(getServerVer()){  
  12.             int verCode = this.getVerCode(this);  
  13.             if(newVerCode>verCode){  
  14.                 doNewVersionUpdate();//更新版本  
  15.             }else{  
  16.                 notNewVersionUpdate();//提示已是最新版本  
  17.             }  
  18.         }  
  19.     }  
  20.      
  21.     /** 
  22.      * 获得版本号 
  23.      */  
  24.     public int getVerCode(Context context){  
  25.         int verCode = -1;  
  26.         try {  
  27.             verCode = context.getPackageManager().getPackageInfo("com.update.apk"0).versionCode;  
  28.         } catch (NameNotFoundException e) {  
  29.             // TODO Auto-generated catch block  
  30.             Log.e("版本号获取异常", e.getMessage());  
  31.         }  
  32.         return verCode;  
  33.     }  
  34.      
  35.     /** 
  36.      * 获得版本名称 
  37.      */  
  38.     public String getVerName(Context context){  
  39.         String verName = "";  
  40.         try {  
  41.             verName = context.getPackageManager().getPackageInfo("com.update.apk"0).versionName;  
  42.         } catch (NameNotFoundException e) {  
  43.             Log.e("版本名称获取异常", e.getMessage());  
  44.         }  
  45.         return verName;  
  46.     }  
  47.      
  48.     /** 
  49.      * 从服务器端获得版本号与版本名称 
  50.      * @return 
  51.      */  
  52.     public boolean getServerVer(){  
  53.         try {  
  54.             URL url = new URL("http://10.0.2.2:8080/ApkUpdateService/ver");  
  55.             HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();  
  56.             httpConnection.setDoInput(true);  
  57.             httpConnection.setDoOutput(true);  
  58.             httpConnection.setRequestMethod("GET");  
  59.             httpConnection.connect();  
  60.             InputStreamReader reader = new InputStreamReader(httpConnection.getInputStream());  
  61.             BufferedReader bReader = new BufferedReader(reader);  
  62.             String json = bReader.readLine();  
  63.             JSONArray array = new JSONArray(json);  
  64.             JSONObject jsonObj = array.getJSONObject(0);  
  65.             newVerCode = Integer.parseInt(jsonObj.getString("verCode"));         
  66.             newVerName = jsonObj.getString("verName");  
  67.         } catch (Exception e) {  
  68.             // TODO Auto-generated catch block  
  69.             e.printStackTrace();  
  70.             return false;  
  71.         }  
  72.         return true;  
  73.     }  
  74.      
  75.     /** 
  76.      * 不更新版本 
  77.      */  
  78.     public void notNewVersionUpdate(){  
  79.         int verCode = this.getVerCode(this);  
  80.         String verName = this.getVerName(this);  
  81.         StringBuffer sb = new StringBuffer();  
  82.         sb.append("当前版本:");  
  83.         sb.append(verName);  
  84.         sb.append(" Code:");  
  85.         sb.append(verCode);  
  86.         sb.append("\n已是最新版本,无需更新");  
  87.         Dialog dialog = new AlertDialog.Builder(this)  
  88.         .setTitle("软件更新")  
  89.         .setMessage(sb.toString())  
  90.         .setPositiveButton("确定"new DialogInterface.OnClickListener() {  
  91.              
  92.             @Override  
  93.             public void onClick(DialogInterface dialog, int which) {  
  94.                 // TODO Auto-generated method stub  
  95.                 finish();  
  96.             }  
  97.         }).create();  
  98.         dialog.show();  
  99.     }  
  100.      
  101.     /** 
  102.      * 更新版本 
  103.      */  
  104.     public void doNewVersionUpdate(){  
  105.         int verCode = this.getVerCode(this);  
  106.         String verName = this.getVerName(this);  
  107.         StringBuffer sb = new StringBuffer();  
  108.         sb.append("当前版本:");  
  109.         sb.append(verName);  
  110.         sb.append(" Code:");  
  111.         sb.append(verCode);  
  112.         sb.append(",发现版本:");  
  113.         sb.append(newVerName);  
  114.         sb.append(" Code:");  
  115.         sb.append(verCode);  
  116.         sb.append(",是否更新");  
  117.         Dialog dialog = new AlertDialog.Builder(this)  
  118.         .setTitle("软件更新")  
  119.         .setMessage(sb.toString())  
  120.         .setPositiveButton("更新"new DialogInterface.OnClickListener() {  
  121.              
  122.             @Override  
  123.             public void onClick(DialogInterface dialog, int which) {  
  124.                 // TODO Auto-generated method stub  
  125.                 pd = new ProgressDialog(MainActivity.this);  
  126.                 pd.setTitle("正在下载");  
  127.                 pd.setMessage("请稍后。。。");  
  128.                 pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);  
  129.                 downFile("http://10.0.2.2:8080/ApkUpdateService/ApkUpdateAndroid.apk");  
  130.             }  
  131.         })  
  132.         .setNegativeButton("暂不更新"new DialogInterface.OnClickListener() {  
  133.              
  134.             @Override  
  135.             public void onClick(DialogInterface dialog, int which) {  
  136.                 // TODO Auto-generated method stub  
  137.                 finish();  
  138.             }  
  139.         }).create();  
  140.         //显示更新框  
  141.         dialog.show();  
  142.     }  
  143.      
  144.     /** 
  145.      * 下载apk 
  146.      */  
  147.     public void downFile(final String url){  
  148.         pd.show();  
  149.         new Thread(){  
  150.             public void run(){  
  151.                 HttpClient client = new DefaultHttpClient();  
  152.                 HttpGet get = new HttpGet(url);  
  153.                 HttpResponse response;  
  154.                 try {  
  155.                     response = client.execute(get);  
  156.                     HttpEntity entity = response.getEntity();  
  157.                     long length = entity.getContentLength();  
  158.                     InputStream is =  entity.getContent();  
  159.                     FileOutputStream fileOutputStream = null;  
  160.                     if(is != null){  
  161.                         File file = new File(Environment.getExternalStorageDirectory(),UPDATE_SERVERAPK);  
  162.                         fileOutputStream = new FileOutputStream(file);  
  163.                         byte[] b = new byte[1024];  
  164.                         int charb = -1;  
  165.                         int count = 0;  
  166.                         while((charb = is.read(b))!=-1){  
  167.                             fileOutputStream.write(b, 0, charb);  
  168.                             count += charb;  
  169.                         }  
  170.                     }  
  171.                     fileOutputStream.flush();  
  172.                     if(fileOutputStream!=null){  
  173.                         fileOutputStream.close();  
  174.                     }  
  175.                     down();  
  176.                 }  catch (Exception e) {  
  177.                     // TODO Auto-generated catch block  
  178.                     e.printStackTrace();  
  179.                 }  
  180.             }  
  181.         }.start();  
  182.     }  
  183.      
  184.     Handler handler = new Handler() {  
  185.   
  186.         @Override  
  187.         public void handleMessage(Message msg) {  
  188.   
  189.             super.handleMessage(msg);                 
  190.             pd.cancel();  
  191.             update();  
  192.         }  
  193.     };  
  194.      
  195.     /** 
  196.      * 下载完成,通过handler将下载对话框取消 
  197.      */  
  198.     public void down(){  
  199.         new Thread(){  
  200.             public void run(){  
  201.                 Message message = handler.obtainMessage();  
  202.                 handler.sendMessage(message);  
  203.             }  
  204.         }.start();  
  205.     }  
  206.      
  207.     /** 
  208.      * 安装应用 
  209.      */  
  210.     public void update(){  
  211.         Intent intent = new Intent(Intent.ACTION_VIEW);  
  212.         intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory(),UPDATE_SERVERAPK))  
  213.                 , "application/vnd.android.package-archive");  
  214.         startActivity(intent);  
  215.     }  
  216. }   

0 0
原创粉丝点击