码迷,mamicode.com
首页 > 移动开发 > 详细

Android--版本检测升级(不借助第三方)

时间:2015-12-06 20:52:43      阅读:333      评论:0      收藏:0      [点我收藏+]

标签:

我们应该都有类似的使用体验,当一款APP需要更新是,进入界面会提醒有新的更新是否更新,这里有那么几个步骤

1、首先检测当前版本

2、判断服务器中版本

3、如果有更新则点击更新,下载安装包,下载完成后自动安装

具体代码怎么实现呢?下面我们一起看一下

1
2
3
4
5
6
7
8
9
10
/*
* 获取当前程序的版本号
*/
private String getVersionName() throws Exception{
    //获取packagemanager的实例
    PackageManager packageManager = getPackageManager();
    //getPackageName()是你当前类的包名,0代表是获取版本信息
    PackageInfo packInfo = packageManager.getPackageInfo(getPackageName(), 0);
    return packInfo.versionName;
}

读取服务器版本号

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/*
* 用pull解析器解析服务器返回的xml文件 (xml封装了版本号)
*/
public static UpdataInfo getUpdataInfo(InputStream is) throws Exception{
    XmlPullParser  parser = Xml.newPullParser();
    parser.setInput(is, "utf-8");//设置解析的数据源
    int type = parser.getEventType();
    UpdataInfo info = new UpdataInfo();//实体
    while(type != XmlPullParser.END_DOCUMENT ){
        switch (type) {
        case XmlPullParser.START_TAG:
            if("version".equals(parser.getName())){
                info.setVersion(parser.nextText()); //获取版本号
            }else if ("url".equals(parser.getName())){
                info.setUrl(parser.nextText()); //获取要升级的APK文件
            }else if ("description".equals(parser.getName())){
                info.setDescription(parser.nextText()); //获取该文件的信息
            }
            break;
        }
        type = parser.next();
    }
    return info;
}

下载

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
public static File getFileFromServer(String path, ProgressDialog pd) throws Exception{
    //如果相等的话表示当前的sdcard挂载在手机上并且是可用的
    if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
        URL url = new URL(path);
        HttpURLConnection conn =  (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(5000);
        //获取到文件的大小
        pd.setMax(conn.getContentLength());
        InputStream is = conn.getInputStream();
        File file = new File(Environment.getExternalStorageDirectory(), "updata.apk");
        FileOutputStream fos = new FileOutputStream(file);
        BufferedInputStream bis = new BufferedInputStream(is);
        byte[] buffer = new byte[1024];
        int len ;
        int total=0;
        while((len =bis.read(buffer))!=-1){
            fos.write(buffer, 0, len);
            total+= len;
            //获取当前下载量
            pd.setProgress(total);
        }
        fos.close();
        bis.close();
        is.close();
        return file;
    }
    else{
        return null;
    }
}

版本匹配、自动安装

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
/*
* 从服务器获取xml解析并进行比对版本号
*/
public class CheckVersionTask implements Runnable{
 
    public void run() {
        try {
            //从资源文件获取服务器 地址
            String path = getResources().getString(R.string.serverurl);
            //包装成url的对象
            URL url = new URL(path);
            HttpURLConnection conn =  (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            InputStream is =conn.getInputStream();
            info =  UpdataInfoParser.getUpdataInfo(is);
 
            if(info.getVersion().equals(versionname)){
                Log.i(TAG,"版本号相同无需升级");
                LoginMain();
            }else{
                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_CLIENT:
            //对话框通知用户升级程序
            showUpdataDialog();
            break;
        case GET_UNDATAINFO_ERROR:
            //服务器超时
            Toast.makeText(getApplicationContext(), "获取服务器更新信息失败", 1).show();
            LoginMain();
            break;
        case DOWN_ERROR:
            //下载apk失败
            Toast.makeText(getApplicationContext(), "下载新版本失败", 1).show();
            LoginMain();
            break;
        }
    }
};
 
/*
*
* 弹出对话框通知用户更新程序
*
* 弹出对话框的步骤:
*  1.创建alertDialog的builder.
*  2.要给builder设置属性, 对话框的内容,样式,按钮
*  3.通过builder 创建一个对话框
*  4.对话框show()出来
*/
protected void showUpdataDialog() {
    AlertDialog.Builder builer = new Builder(this) ;
    builer.setTitle("版本升级");
    builer.setMessage(info.getDescription());
    //当点确定按钮时从服务器上下载 新的apk 然后安装
    builer.setPositiveButton("确定", new OnClickListener() {
    public void onClick(DialogInterface dialog, int which) {
            Log.i(TAG,"下载apk,更新");
            downLoadApk();
        }
    });
    //当点取消按钮时进行登录
    builer.setNegativeButton("取消", new OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            // TODO Auto-generated method stub
            LoginMain();
        }
    });
    AlertDialog dialog = builer.create();
    dialog.show();
}
 
/*
* 从服务器中下载APK
*/
protected void downLoadApk() {
    final ProgressDialog pd;    //进度条对话框
    pd = new  ProgressDialog(this);
    pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    pd.setMessage("正在下载更新");
    pd.show();
    new Thread(){
        @Override
        public void run() {
            try {
                File file = DownLoadManager.getFileFromServer(info.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");
    startActivity(intent);
}
 
/*
* 进入程序的主界面
*/
private void LoginMain(){
    Intent intent = new Intent(this,MainActivity.class);
    startActivity(intent);
    //结束掉当前的activity
    this.finish();
}

相关类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class UpdataInfo {
    private String version;
    private String url;
    private String description;
    public String getVersion() {
        return version;
    }
    public void setVersion(String version) {
        this.version = version;
    }
    public String getUrl() {
        return url;
    }
    public void setUrl(String url) {
        this.url = url;
    }
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }
}

相关布局

1
2
3
4
5
6
<?xml version="1.0" encoding="utf-8"?>
<info>
    <version&gt;2.0&lt;/version>
    <description>检测到最新版本,请及时更新!</description>
</info>

Android--版本检测升级(不借助第三方)

标签:

原文地址:http://www.cnblogs.com/zrui513/p/5010200.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!