版本更新

在做版本更新之前需要准备实体类和工具类
实体类

package com.example.month;

public class Bean {

    private int versionCode;
    private String downloadUrl;
    private String updateLog;
    public int getVersionCode() {
        return versionCode;
    }
    public void setVersionCode(int versionCode) {
        this.versionCode = versionCode;
    }
    public String getDownloadUrl() {
        return downloadUrl;
    }
    public void setDownloadUrl(String downloadUrl) {
        this.downloadUrl = downloadUrl;
    }
    public String getUpdateLog() {
        return updateLog;
    }
    public void setUpdateLog(String updateLog) {
        this.updateLog = updateLog;
    }
    @Override
    public String toString() {
        return "Bean [versionCode=" + versionCode + ", downloadUrl="
                + downloadUrl + ", updateLog=" + updateLog + "]";
    }

}

方法
获得数据

/**
     * 设置数据
     */
    private void setData() {
        //设置请求的路径
        final String path = "设置数据的xml文件";
        new Thread() {
            @SuppressWarnings("deprecation")
            public void run() {
                URL url;
                try {
                    url = new URL(path);
                    HttpURLConnection conn = (HttpURLConnection) url
                            .openConnection();
                    conn.setRequestMethod("GET");
                    if (conn.getResponseCode() == 200) {
                        InputStream is = conn.getInputStream();
                        //解析xml的方法
                        List<Bean> pullXml = pullXml(is);
                        //进行handler发送
                        final Bean bean = pullXml.get(0);
                        Message message = Message.obtain();
                        message.obj = bean;
                        message.what = 0;
                        handler.sendMessage(message);

                        Log.e("tag", pullXml.toString());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

        }.start();
    }

解析xml

/**
     * 解析xml的方法
     * @param is
     * @return
     */
    private List<Bean> pullXml(InputStream is) {
        List<Bean> list = null;
        Bean bean = null;
        XmlPullParser parser = Xml.newPullParser();
        try {
            parser.setInput(is, "UTF-8");
            int eventType = parser.getEventType();
            while (eventType != XmlResourceParser.END_DOCUMENT) {
                String name = parser.getName();
                switch (eventType) {
                case XmlResourceParser.START_DOCUMENT:
                    list = new ArrayList<Bean>();
                    break;

                case XmlResourceParser.START_TAG:
                    if ("android".equals(name)) {
                        bean = new Bean();
                    } else if ("versionCode".equals(name)) {
                        bean.setVersionCode(Integer.parseInt(parser.nextText()));

                    } else if ("downloadUrl".equals(name)) {
                        bean.setDownloadUrl(parser.nextText());
                    } else if ("updateLog".equals(name)) {
                        bean.setUpdateLog(parser.nextText());
                    }
                    break;
                case XmlResourceParser.END_TAG:
                    if ("android".equals(name)) {
                        list.add(bean);
                        bean = null;
                    }
                    break;
                }
                eventType = parser.next();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    };

hangdler操作

private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            if (msg.what == 0) {
                Bean bean = (Bean) msg.obj;
                //网络帮本号
                int versionCode = bean.getVersionCode();
                int versionCode2;
                try {
                    //当前版本号
                    versionCode2 = getPackageManager().getPackageInfo(
                            "com.example.month", 0).versionCode;
                    if (versionCode != versionCode2) {
                        Log.e("tag", "============");
                        up(bean);

                    } else {
                        Toast.makeText(MainActivity.this, "版本相同",
                                Toast.LENGTH_SHORT).show();
                    }
                } catch (NameNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }

        }


    };

请求更新apk
/**
* 请求更新apk的方法
* @param downloadUrl 更新的路径
*/
private void download(final String downloadUrl) {
//创建ProgressDialog对象
m_progressDlg = new ProgressDialog(this);
m_progressDlg.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
// 设置ProgressDialog 的进度条是否不明确 false 就是不设置为不明确
m_progressDlg.setIndeterminate(false);
m_progressDlg.show();
new Thread() {
@SuppressWarnings(“deprecation”)
public void run() {
@SuppressWarnings(“deprecation”)
HttpClient client = new DefaultHttpClient();
@SuppressWarnings(“deprecation”)
HttpGet get = new HttpGet(downloadUrl);
@SuppressWarnings(“deprecation”)
HttpResponse response;
try {
response = client.execute(get);
HttpEntity entity = response.getEntity();
//得到内容的长度
long length = entity.getContentLength();
m_progressDlg.setMax((int) length);// 设置进度条的最大值

                InputStream is = entity.getContent();
                FileOutputStream fileOutputStream = null;
                if (is != null) {
                    File file = new File(
                            Environment.getExternalStorageDirectory(),
                            "aa.apk");
                    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) {
                            m_progressDlg.setProgress(count);

                        }
                    }

                    if (m_progressDlg.getProgress()==m_progressDlg.getMax()) {
                        m_progressDlg.dismiss();
                        //设置安装apk的方法
                        update();
                    }

                }
                //进行刷新
                fileOutputStream.flush();
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }

            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }.start();
}

安装apk

 /**
     * 安装apk的方法
     */
    void update() {  
        //使用隐身跳转
         Intent intent = new Intent(Intent.ACTION_VIEW); 
         //设置类型和数据
         intent.setDataAndType(Uri.fromFile(new File(Environment  
                 .getExternalStorageDirectory(), "aa.apk")),  
                 "application/vnd.android.package-archive");  
         //开始跳转
         startActivity(intent);  
     }  
/**
     * 进行点击显示对话框
     * @param bean
     */
    private void up(final Bean bean) {
        AlertDialog.Builder builder=new Builder(this);
        //设置标题
        builder.setTitle("版本更新");
        //设置内容
        builder.setMessage(bean.getUpdateLog());
        //设置确定按钮的
        builder.setPositiveButton("确定", new OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                //下载apk的方法
                download(bean.getDownloadUrl());
            }
        });
        //取消按钮的方法
        builder.setNegativeButton("取消", new OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                Toast.makeText(MainActivity.this, "暂不更新", Toast.LENGTH_SHORT).show();
            }
        });
        //进行显示
        builder.show();
    };

必须添加一些权限

 <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值