• android检查自动升级


    好像大半年没发点啥了,也不知道自己瞎忙啥,闲下来发给最近的东东《安卓在线升级》

    类已经封装好了,简单的调用就OK了。这里的数据交互,我是用.NET写的一个webservice来交互。废话也不说了,直接上代码了。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    package com.android.xt.dg;
     
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
     
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.json.JSONArray;
    import org.json.JSONObject;
     
    import com.android.xt.BLL.DGWebServicesBLL;
    import com.android.xt.common.AppSettingInfo;
    import com.android.xt.common.Common;
    import com.xt.dialog.XTAlertDialog;
    import com.xt.dialog.XTProgressDialog;
     
    import android.app.Activity;
    import android.app.ProgressDialog;
    import android.content.Context;
    import android.content.DialogInterface;
    import android.content.Intent;
    import android.content.pm.PackageManager.NameNotFoundException;
    import android.graphics.Bitmap.Config;
    import android.net.Uri;
    import android.os.Bundle;
    import android.os.Environment;
    import android.os.Handler;
    import android.os.Message;
     
    public class CheckUpgrade {
     
        public Activity Act;//调用该类的Activity
        public String  apkName= "dgapk.apk";//下载保存的APK名称
        public XTProgressDialog pBar;//进度条
        public CheckUpgrade(Activity act)
        {
            this.Act=act;
        }
        /*************
        *获取当前的apk版本代码
        ********************/
        public static int getVerCode(Context context) { 
            int verCode = -1
            try
                //com.android.xt.dg 为程序的包名。
                verCode = context.getPackageManager().getPackageInfo( 
                        "com.android.xt.dg", 0).versionCode; 
            } catch (NameNotFoundException e) { 
                
            
            return verCode; 
        
         /*************
        *获取当前的apk版本名称
        ********************/
        public static String getVerName(Context context) { 
            String verName = ""
            try
                //com.android.xt.dg 为程序的包名。
                verName = context.getPackageManager().getPackageInfo( 
                        "com.android.xt.dg", 0).versionName; 
            } catch (NameNotFoundException e) { 
               
            
            return verName;    
        }
        /*************
        *检查版本是升级。
        ********************/
        public void GetVersionInfo()
        {
            //显示进度条(此处进度条为自定义的一个进度条,可以修改为原生或者你自己的进度条,也可以直接去掉)
            pBar = XTProgressDialog.createDialog(Act).setMessage("正在检查,请稍候...");
            pBar.show();
            try {
            //启动一个线程调用webservice读取版本信息
            new Thread(new Runnable(){
                public void run(){
                    try {
                        DGWebServicesBLL bll=new DGWebServicesBLL();
                        String msg=bll.GetServerVersion();
                        Message message=new Message();
                        message.what=1;
                        Bundle data=new Bundle();
                        data.putString("msg", msg);
                        message.setData(data);
                        //读取数据近些界面的处理
                        myHandler.sendMessage(message);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }).start();
            } catch (Exception e) {
                e.printStackTrace();
                Common.Message(e.getMessage(), Act);
            }
        }
        Handler myHandler = new Handler() { 
            @Override
            public void handleMessage(Message msg) { 
                try
                {
                pBar.dismiss(); //关闭进度条
                switch(msg.what)
                {
                case 1:{
                    //取得数据并处理,我返回的数据格式为json格式,格式示例如下
                    //{"result":"true","versionCode":"1","versionName":"1.0","downFile":"http://www.968610.com.cn/app/dgapp.apk"}
                    Bundle  data=msg.getData();
                    String resultMsg=data.getString("msg");
                    JSONObject result=new JSONObject(resultMsg);
                    String jsonResult="";
                    jsonResult=result.getString("result");
                    if(jsonResult.equals("false"))
                    {
                        resultMsg=result.getString("msg");
                    }
                    else if(jsonResult.equals("true"))
                    {
                        //获取服务器版本
                        String ServerCodeStr =result.getString("versionCode");
                        int ServerCode=Integer.parseInt(ServerCodeStr);
                        //服务器版本名
                        String ServerName =result.getString("versionName");
                        String downFile =result.getString("downFile");
                        //获取本地版本信息
                        int localCode=getVerCode((Context)Act);
                        String localName=getVerName((Context)Act);
                         
                        if (ServerCode > localCode) { 
                            doNewVersionUpdate(ServerName,localName,downFile); // 更新新版本 
                        } else
                            notNewVersionShow(ServerName); // 提示当前为最新版本 
                        }      
                    }
                    else
                    {
                        resultMsg="读取出错.";
                    }
                }break;
                }
                }catch(Exception ex){
                    Common.Message(ex.getMessage(), Act);
                }
                super.handleMessage(msg);  
            }  
       };
       /******************
       *提示无最新版本,
       ********************************/
       private void notNewVersionShow(String ServerName) { 
            StringBuffer sb = new StringBuffer(); 
            sb.append("当前版本:"+ServerName); 
            sb.append(",已是最新版,无需更新!"); 
            //此处对话框也为自定义对话框,
            XTAlertDialog.Builder builder=new XTAlertDialog.Builder(Act);
            builder.setTitle("软件更新").setMessage(sb.toString());
            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            builder.create().show();
        }
         /******************
       *更新新版本
       ********************************/
       private void doNewVersionUpdate(String ServerName,String localName,final String DownFile) {   
            StringBuffer sb = new StringBuffer(); 
            sb.append("当前版本:"+localName); 
            sb.append(", 发现新版本:"+ServerName); 
            sb.append(", 是否更新?"); 
            XTAlertDialog.Builder builder=new XTAlertDialog.Builder(Act);
            builder.setTitle("软件更新").setMessage(sb.toString());
            builder.setPositiveButton("现在更新", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
    //              pBar = new XTProgressDialog(Act); 
    //                pBar.setTitle("正在下载"); 
    //                pBar.setMessage("请稍候...");
                    //pBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                     pBar = XTProgressDialog.createDialog(Act).setMessage("正在下载,请稍候...");
                     pBar.show();
                    downFile(DownFile);
                }
            });
            builder.setNegativeButton("暂不更新"
                      new DialogInterface.OnClickListener() { 
                          public void onClick(DialogInterface dialog, 
                                  int whichButton) { 
                              // 点击"取消"按钮之后退出程序
                              dialog.dismiss();
                          
                  });
            builder.create().show();
        }
       /*********************
       *下载文件操作
       **********************/
       void downFile(final String url) { 
            pBar.show(); 
            new Thread() {  //启动线程瞎子啊
                public void run() { 
                    HttpClient client = new DefaultHttpClient(); 
                    HttpGet get = new HttpGet(url); 
                    HttpResponse response; 
                    try
                        response = client.execute(get); 
                        HttpEntity entity = response.getEntity(); 
                        long length = entity.getContentLength(); 
                        InputStream is = entity.getContent(); 
                        FileOutputStream fileOutputStream = null
                        if (is != null) { 
                            File file = new File( 
                                    Environment.getExternalStorageDirectory(), 
                                  apkName); 
                            fileOutputStream = new FileOutputStream(file); 
                            byte[] buf = new byte[1024]; 
                            int ch = -1
                            int count = 0
                            while ((ch = is.read(buf)) != -1) { 
                                fileOutputStream.write(buf, 0, ch); 
                                count += ch; 
                                if (length > 0) { 
                                
                            
                        
                        fileOutputStream.flush(); 
                        if (fileOutputStream != null) { 
                            fileOutputStream.close(); 
                        
                        down();  //下载完成,并通知安装
                    } catch (ClientProtocolException e) { 
                        e.printStackTrace(); 
                    } catch (IOException e) { 
                        e.printStackTrace(); 
                    
                
            }.start(); 
        
        
       void down() { 
           myHandler.post(new Runnable() { 
               public void run() { 
                   pBar.cancel(); 
                   update();   //并通知安装
               
           }); 
       }
       void update() { 
            Intent intent = new Intent(Intent.ACTION_VIEW); 
            intent.setDataAndType(Uri.fromFile(new File(Environment 
                    .getExternalStorageDirectory(), apkName)), 
                    "application/vnd.android.package-archive"); 
            Act.startActivity(intent); 
       
     
    }

    这就封装好了。记得调用webservices检查新版本的方法我就不发了。那个就是个读取数据的而已。

    看看怎么调用吧。两句话搞定(其实应该是一句。)

    1
    2
    3
    4
    5
    public void btnCheckUpgrade_Click(View v)
    {
        CheckUpgrade cu=new CheckUpgrade(this);
        cu.GetVersionInfo();
    }

    不扯了,咱不是官场人士,废话不说,代码重要。。。。等有空继续发些其他的。

    本文从百度空间搬家到博客园

    邮箱:yunanwu@foxmail.com 微博:@提灯寻影(http://weibo.com/wuyunnan) 技术主页:http://www.cnblogs.com/yuanawu/ 可以白手起家不可手无寸铁!我是我命运的主宰者,我是我灵魂的掌舵人! 每一次的选择都将是一个挑战!
  • 相关阅读:
    软件项目版本号的命名规则及格式
    你必须知道的C#的25个基础概念
    Visual C#常用函数和方法集汇总
    web标准下的web开发流程思考
    设计模式(5)>模板方法 小强斋
    设计模式(9)>迭代器模式 小强斋
    设计模式(10)>策略模式 小强斋
    设计模式(8)>代理模式 小强斋
    设计模式(7)>观察者模式 小强斋
    设计模式(7)>观察者模式 小强斋
  • 原文地址:https://www.cnblogs.com/yunanwu/p/4168594.html
Copyright © 2020-2023  润新知