安卓版本更新的简单Demo

以下就是版本更新的全部代码



注:加上网络权限和SD卡读写权限



这里是MainActivity的代码,仅仅只是点击事件调用检查更新方法

<pre name="code" class="java"><span style="color:#000000;">[java] view plain copy
print?

    <span style="color:#666666;">package com.bwie.updatev;  
      
    import android.os.Bundle;   
    import android.app.Activity;  
    import android.view.Menu;  
    import android.view.View;  
      
    public class MainActivity extends Activity {  
      
        @Override  
        protected void onCreate(Bundle savedInstanceState) {  
            super.onCreate(savedInstanceState);  
            setContentView(R.layout.activity_main);  
        }  
      
      
        public void update(View v){  
            UpdateVersionutil.getUpdataManger(this).checkUpdata();  
        }  
    }</span><span style="color:#ff0000;">  
    </span></span>  


 
这里是ManiActivity的布局 

<span style="color:#000000;">[java] view plain copy
print?

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
        xmlns:tools="http://schemas.android.com/tools"  
        android:layout_width="match_parent"  
        android:layout_height="match_parent"  
       >  
      
        <Button  
            android:layout_width="wrap_content"  
            android:layout_height="wrap_content"  
            android:text="更新"  
            android:onClick="update" />  
      
    </RelativeLayout>  </span>

接下来就是重点了

           这里贴出的就是解析服务器返回信息的实体类


<span style="color:#000000;">[java] view plain copy
print?

    package com.bwie.updatev;  
      
    import java.io.Serializable;  
    import java.util.ArrayList;  
      
    public class UpdataInfo implements Serializable{  
          
        public Update_Data data;</span>


<span style="color:#000000;">[java] view plain copy
print?

    <span style="color:#333333;">package com.bwie.updatev;  
      
    public class Update_Data {  
        public  String description;  
        public String forcibly;  
        public  String last_version;  
        public String needUpdate;  
        public String url;  
        public String version_Name;  
           
        public Update_Data(String description, String forcibly,  
                String last_version, String needUpdate, String url,  
                String version_Name) {  
            super();  
            this.description = description;  
            this.forcibly = forcibly;  
            this.last_version = last_version;  
            this.needUpdate = needUpdate;  
            this.url = url;  
            this.version_Name = version_Name;  
        }  
        public String getDescription() {  
            return description;  
        }  
        public void setDescription(String description) {  
            this.description = description;  
        }  
        public String getForcibly() {  
            return forcibly;  
        }  
        public void setForcibly(String forcibly) {  
            this.forcibly = forcibly;  
        }  
        public String getLast_version() {  
            return last_version;  
        }  
        public void setLast_version(String last_version) {  
            this.last_version = last_version;  
        }  
        public String getNeedUpdate() {  
            return needUpdate;  
        }  
        public void setNeedUpdate(String needUpdate) {  
            this.needUpdate = needUpdate;  
        }  
        public String getUrl() {  
            return url;  
        }  
        public void setUrl(String url) {  
            this.url = url;  
        }  
        public String getVersion_Name() {  
            return version_Name;  
        }  
        public void setVersion_Name(String version_Name) {  
            this.version_Name = version_Name;  
        }  
           
          
          
           
          
    }  
    </span>  </span>


紧接着是解析服务器信息的方法

[java] view plain copy
print?

    <span style="color:#666666;">package com.bwie.updatev;  
      
    import java.io.ByteArrayOutputStream;    
    import java.io.IOException;  
    import java.io.InputStream;  
       
    import com.google.gson.Gson;  
       
    /** 
     * 版本更新数据转换解析 
     * @author Administrator 
     * @date 2016-7-12 
     * 
     */  
    public class UpdataInfoParserUtil {  
          
          
        /** 
         * 用于解析版本更新的数据流,返回版本更新的对象那个 
         * @param is 
         * @return 
         */  
        public static UpdataInfo getUpdataInfo(InputStream is) {  
            // TODO Auto-generated method stub  
             String parseInputStream = parseInputStream(is);  
             System.out.println(parseInputStream);  
             Gson g=new Gson();  
             UpdataInfo fromJson = g.fromJson(parseInputStream, UpdataInfo.class);  
            return fromJson;  
        }  
              
        /** 
         * 将数据输入流转换为字符串 
         * @param is 
         * @return 
         */  
        private static String parseInputStream(InputStream is) {  
            ByteArrayOutputStream baos=new ByteArrayOutputStream();  
             int len=0;  
             byte[] b=new byte[1024];  
             try {  
                while((len=is.read(b))!=-1){  
                     baos.write(b, 0, len);  
                 }  
                return baos.toString("UTF-8").trim();  
            } catch (IOException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
            }  
            return null;  
        }  
      
    }</span><span style="color:#ff0000;">  
    </span> 


最后重中之重就是这里了

[java] view plain copy
print?

    package com.bwie.updatev;  
      
    import java.io.BufferedInputStream;    
    import java.io.File;  
    import java.io.FileNotFoundException;  
    import java.io.FileOutputStream;  
    import java.io.IOException;  
    import java.io.InputStream;  
    import java.net.HttpURLConnection;  
    import java.net.MalformedURLException;  
    import java.net.URL;  
       
      
    import android.app.AlertDialog;  
    import android.app.ProgressDialog;  
    import android.app.AlertDialog.Builder;  
    import android.content.Context;  
    import android.content.DialogInterface;  
    import android.content.Intent;  
    import android.content.pm.PackageInfo;  
    import android.content.pm.PackageManager;  
    import android.content.pm.PackageManager.NameNotFoundException;  
    import android.net.Uri;  
    import android.os.Environment;  
    import android.os.Handler;  
    import android.os.Message;  
    import android.util.Log;  
    import android.widget.Button;  
    import android.widget.Toast;  
      
    /** 
     * 更新版本的工具类 
     * @author Administrator 
     * @date 2016-7-11 
     * 
     */  
      
      
    public class UpdateVersionutil {  
      
        private final String TAG = this.getClass().getName();  
        private final int UPDATA_NONEED = 0;  
        private final int UPDATA_CLIENT = 1;  
        private final int GET_UNDATAINFO_ERROR = 2;  
        private final int SDCARD_NOMOUNTED = 3;  
        private final int DOWN_ERROR = 4;  
        private Button getVersion;  
        private static UpdataInfo info;  
        private String localVersion;  
        public static Context mContext;  
        private static UpdateVersionutil updateVersionutil;  
        public static boolean mNeedUpdate;  
          
        public UpdateVersionutil(Context mContext) {  
            super();  
            this.mContext = mContext;  
        }  
      
        public void startUpdate(){  
            localVersion = getVersionName();  
            CheckVersionTask cv = new CheckVersionTask();  
            new Thread(cv).start();  
        }  
          
        public static UpdateVersionutil  getUpdataManger(Context context){  
            if(updateVersionutil==null){  
                updateVersionutil=new UpdateVersionutil(context);  
            }  
            return updateVersionutil;  
        }  
          
        public static void checkUpdata(){  
            updateVersionutil.startUpdate();  
        }  
          
        private String getVersionName()   {  
            //getPackageName()是你当前类的包名,0代表是获取版本信息    
            PackageManager packageManager =mContext.getPackageManager();  
            PackageInfo packInfo = null;  
            try {  
                packInfo = packageManager.getPackageInfo(mContext.getPackageName(),  
                        0);  
            } catch (NameNotFoundException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
            }  
            return packInfo.versionName;  
        }  
      
      
        public class CheckVersionTask implements Runnable {  
            InputStream is;  
            public void run() {  
                try {  
                    URL url = new URL("http://m.yunifang.com/yunifang/mobile/version?random=67603&encode=e441af3089cbeeb6b58ac72393a66667&clientType=android&clientVersion=10000");  
                    HttpURLConnection conn = (HttpURLConnection) url  
                            .openConnection();  
                    conn.setConnectTimeout(5000);  
                    conn.setRequestMethod("GET");   
                    int responseCode = conn.getResponseCode();   
                    if (responseCode == 200) {   
                        // 从服务器获得一个输入流   
                        is = conn.getInputStream();   
                    }   
                    info = UpdataInfoParserUtil.getUpdataInfo(is);  
                     Url = info.data.getUrl();  
                    System.out.println("新版版本名:"+info.data.getVersion_Name());  
                    System.out.println("本地版本名:"+localVersion);  
                       
                    if (info.data.getVersion_Name().equals(localVersion)) {  
                        mNeedUpdate=false;  
                        Log.i(TAG, "版本号相同");  
                        Message msg = new Message();  
                        msg.what = UPDATA_NONEED;  
                        handler.sendMessage(msg);  
                        // LoginMain();  
                    } else {  
                        mNeedUpdate=true;  
                        Log.i(TAG, "版本号不相同 ");  
                        Message msg = new Message();  
                        msg.what = UPDATA_CLIENT;  
                        handler.sendMessage(msg);  
                    }  
                } catch (Exception e) {  
                    Message msg = new Message();  
                    msg.what = GET_UNDATAINFO_ERROR;  
                    handler.sendMessage(msg);  
                    e.printStackTrace();  
                }  
            }  
        }  
      
        Handler handler = new Handler() {  
            @Override  
            public void handleMessage(Message msg) {  
                // TODO Auto-generated method stub  
                super.handleMessage(msg);  
                switch (msg.what) {  
                case UPDATA_NONEED:  
                    Toast.makeText(mContext, "不需要更新",  
                            Toast.LENGTH_SHORT).show();  
                case UPDATA_CLIENT:  
                    //对话框通知用户升级程序     
                    showUpdataDialog();  
                    break;  
                case GET_UNDATAINFO_ERROR:  
                    //服务器超时     
                    Toast.makeText(mContext, "获取服务器更新信息失败", 1).show();   
                    break;  
                case DOWN_ERROR:  
                    //下载apk失败    
                    Toast.makeText(mContext, "下载新版本失败", 1).show();   
                    break;  
                }  
            }  
        };  
        /*  
         *   
         * 弹出对话框通知用户更新程序   
         *   
         * 弹出对话框的步骤:  
         *  1.创建alertDialog的builder.    
         *  2.要给builder设置属性, 对话框的内容,样式,按钮  
         *  3.通过builder 创建一个对话框  
         *  4.对话框show()出来    
         */    
        protected void showUpdataDialog() {  
            AlertDialog.Builder builer = new Builder(mContext);  
            builer.setTitle("版本升级");  
            builer.setMessage(info.data.getDescription());  
            //当点确定按钮时从服务器上下载 新的apk 然后安装   װ  
            builer.setPositiveButton("立马更新", new DialogInterface.OnClickListener() {  
                public void onClick(DialogInterface dialog, int which) {  
                    Log.i(TAG, "下载apk,更新");  
                    downLoadApk();  
                }  
            });  
            builer.setNegativeButton("稍后再说", new DialogInterface.OnClickListener() {  
                public void onClick(DialogInterface dialog, int which) {  
                    // TODO Auto-generated method stub  
                    //do sth  
                }  
            });  
            AlertDialog dialog = builer.create();  
            dialog.show();  
        }  
        /*  
         * 从服务器中下载APK  
         */    
        protected void downLoadApk() {    
            final ProgressDialog pd;    //进度条对话框    
            pd = new  ProgressDialog(mContext);    
            pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);    
            pd.setMessage("正在下载更新");    
            pd.show();    
            new Thread(){    
                @Override    
                public void run() {    
                    try {    
                        File file = DownLoadManager.getFileFromServer(info.data.getUrl(), pd);    
                        sleep(3000);    
                        installApk(file);    
                        pd.dismiss(); //结束掉进度条对话框    
                    } catch (Exception e) {    
                        Message msg = new Message();    
                        msg.what = DOWN_ERROR;    
                        handler.sendMessage(msg);    
                        e.printStackTrace();    
                    }    
                }}.start();    
        }    
      
        //安装apk     
        protected void installApk(File file) {    
            Intent intent = new Intent();    
            //执行动作    
            intent.setAction(Intent.ACTION_VIEW);    
            //执行的数据类型    
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");    
            mContext.startActivity(intent);    
        }    
       public static String Url;  
       public static String getUrl(){  
            
           return Url;  
       }  
      
      
        public static class DownLoadManager {  
              
            public static File getFileFromServer(String path, ProgressDialog pd)  {  
                //如果相等的话表示当前的sdcard挂载在手机上并且是可用的  
                if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){  
                    URL url = null;  
                    try {  
                        url = new URL(path);  
                    } catch (MalformedURLException e) {  
                        // TODO Auto-generated catch block  
                        e.printStackTrace();  
                    }  
                    HttpURLConnection conn = null;  
                    try {  
                        conn = (HttpURLConnection) url.openConnection();  
                    } catch (IOException e) {  
                        // TODO Auto-generated catch block  
                        e.printStackTrace();  
                    }  
                    conn.setConnectTimeout(5000);  
                    //获取到文件的大小   
                    pd.setMax(conn.getContentLength());  
                    InputStream is = null;  
                    try {  
                        is = conn.getInputStream();  
                    } catch (IOException e) {  
                        // TODO Auto-generated catch block  
                        e.printStackTrace();  
                    }  
                    File file = new File(Environment.getExternalStorageDirectory(), "updata.apk");  
                    FileOutputStream fos = null;  
                    try {  
                        fos = new FileOutputStream(file);  
                    } catch (FileNotFoundException e) {  
                        // TODO Auto-generated catch block  
                        e.printStackTrace();  
                    }  
                    BufferedInputStream bis = new BufferedInputStream(is);  
                    byte[] buffer = new byte[1024];  
                    int len ;  
                    int total=0;  
                    try {  
                        while((len =bis.read(buffer))!=-1){  
                            fos.write(buffer, 0, len);  
                            total+= len;  
                            //获取当前下载量  
                            pd.setProgress(total);  
                        }  
                    } catch (IOException e) {  
                        // TODO Auto-generated catch block  
                        e.printStackTrace();  
                    }  
                    try {  
                        fos.close();  
                    } catch (IOException e) {  
                        // TODO Auto-generated catch block  
                        e.printStackTrace();  
                    }  
                    try {  
                        bis.close();  
                    } catch (IOException e) {  
                        // TODO Auto-generated catch block  
                        e.printStackTrace();  
                    }  
                    try {  
                        is.close();  
                    } catch (IOException e) {  
                        // TODO Auto-generated catch block  
                        e.printStackTrace();  
                    }  
                    return file;  
                }  
                else{  
                    return null;  
                }  
            }  
        }  
         
           
    }  


好了,到这里,你就已经可以实现安卓的版本更新功能了,希望可以帮助到你  



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值