Android版本更新

这个博客展示了如何在Android应用中实现自动检查新版本的功能。通过HttpUtils发送请求获取XML格式的版本信息,解析XML获取版本号和下载链接。如果检测到新版本,将弹出对话框询问用户是否更新,用户选择更新后会下载APK并进行安装。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package test.bwie.com.checkedversion;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.util.Xml;
import android.widget.Toast;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import org.xmlpull.v1.XmlPullParser;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends Activity {
    private String newVersion_result = null;
    private AlertDialog alert;
    private AlertDialog alertDialog;
    private List<Info> info = new ArrayList<>();
    private AlertDialogUtils alertUtils = new AlertDialogUtils();
    private Handler myHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            newVersion_result = (String) msg.obj;
            try {
                info = parseXml(newVersion_result);
                int oldVersion = oldVersion();
                if (oldVersion != 0 && info.get(0).getVersion_code() != 0) {
                    if (oldVersion < info.get(0).getVersion_code()) {
                        update(info.get(0).getDownloadUrl());
                    }
                    if (oldVersion == info.get(0).getVersion_code()) {
                        Toast.makeText(MainActivity.this, "当前已经是最高版本", Toast.LENGTH_LONG).show();
                    }

                } else {
                    Toast.makeText(MainActivity.this, "获取版本信息失败!!!", Toast.LENGTH_LONG).show();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //查询最新版本
        newVersion();
    }

    /**
     * Pull解析XML文件
     *
     * @param data
     * @return
     * @throws Exception
     */
    public List<Info> parseXml(String data) throws Exception {
        List<Info> mList = null;
        Info beauty = null;
        // 由android.util.Xml创建一个XmlPullParser实例
        XmlPullParser xpp = Xml.newPullParser();
        InputStream inputStream = new ByteArrayInputStream(data.getBytes());
        // 设置输入流 并指明编码方式
        xpp.setInput(inputStream, "UTF-8");
        // 产生第一个事件
        int eventType = xpp.getEventType();

        while (eventType != XmlPullParser.END_DOCUMENT) {
            switch (eventType) {
                // 判断当前事件是否为文档开始事件
                case XmlPullParser.START_DOCUMENT:
                    mList = new ArrayList<Info>(); // 初始化books集合
                    break;
                // 判断当前事件是否为标签元素开始事件
                case XmlPullParser.START_TAG:
                    if (xpp.getName().equals("oschina")) { // 判断开始标签元素是否是book
                        beauty = new Info();
                    } else if (xpp.getName().equals("versionCode")) {
                        eventType = xpp.next();//让解析器指向name属性的值
                        // 得到name标签的属性值,并设置beauty的name
                        beauty.setVersion_code(Integer.valueOf(xpp.getText()));
                    } else if (xpp.getName().equals("versionName")) {
                        eventType = xpp.next();//让解析器指向name属性的值
                        // 得到name标签的属性值,并设置beauty的name
                        beauty.setVersionName(xpp.getText());
                    } else if (xpp.getName().equals("downloadUrl")) { // 判断开始标签元素是否是book
                        eventType = xpp.next();//让解析器指向age属性的值
                        // 得到age标签的属性值,并设置beauty的age
                        beauty.setDownloadUrl(xpp.getText());
                    }
                    break;

                // 判断当前事件是否为标签元素结束事件
                case XmlPullParser.END_TAG:
                    if (xpp.getName().equals("oschina")) { // 判断结束标签元素是否是book
                        mList.add(beauty); // 将book添加到books集合
                        beauty = null;
                    }
                    break;
            }
            // 进入下一个元素并触发相应事件
            eventType = xpp.next();
        }
        return mList;

    }


    //安装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();
    }

    /**
     * 提示是否更新的对话框
     */
    public void update(String apk_path) {

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("更新");
        builder.setMessage("检测到有最新版本,是否更新?");
        builder.setPositiveButton("更新", new AlertDialog.OnClickListener() {

            public void onClick(DialogInterface dialogInterface, int i) {
                updateVersion(info.get(0).getDownloadUrl(), Environment.getExternalStorageDirectory().getPath() + "/update.apk");

            }
        });
        builder.setNegativeButton("暂不更新", new AlertDialog.OnClickListener() {

            public void onClick(DialogInterface dialogInterface, int i) {

                alert.cancel();
            }
        });
        alert = builder.create();
        alert.show();


    }

    /**
     * 得到当前版本
     *
     * @return
     */
    public int oldVersion() {
        int version_code = 0;
        //得到版本码和版本名
        try {
            version_code = this.getPackageManager().getPackageInfo("test.bwie.com.checkedversion", 0).versionCode;
            String versionName = this.getPackageManager().getPackageInfo("test.bwie.com.checkedversion", 0).versionName;
            Toast.makeText(MainActivity.this, "当前版本是:" + versionName, Toast.LENGTH_SHORT).show();
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return version_code;
    }

    /**
     * 获取新版本
     */
    public void newVersion() {
        HttpUtils hu = new HttpUtils();
        hu.send(HttpRequest.HttpMethod.GET, "http://www.oschina.net/MobileAppVersion.xml", new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                String result = responseInfo.result;
                Log.d("tag", result);
                Message msg = new Message();
                msg.obj = result;
                myHandler.sendMessage(msg);
            }

            @Override
            public void onFailure(HttpException e, String s) {
                Toast.makeText(MainActivity.this, "获取新版本信息失败!!!", Toast.LENGTH_LONG).show();
                Log.d("tag", e.toString());

            }
        });

    }

    /**
     * 更新版本
     *
     * @param url
     * @param path
     */
    public void updateVersion(String url, String path) {
        HttpUtils hu = new HttpUtils();
        hu.download(url, path, new RequestCallBack<File>() {
            @Override
            public void onLoading(long total, long current, boolean isUploading) {
                Toast.makeText(MainActivity.this, "正在更新,请稍后", Toast.LENGTH_LONG).show();
                super.onLoading(total, current, isUploading);
            }

            @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
            @Override
            public void onSuccess(ResponseInfo<File> responseInfo) {
                AlertDialog.Builder ab = new AlertDialog.Builder(MainActivity.this);
                ab.setMessage("更新包已下载完成,是否安装?");
                ab.setPositiveButton("安装", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        update_apk();
                        alertDialog.cancel();
                    }
                });
                ab.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        alertDialog.cancel();
                        Toast.makeText(MainActivity.this, "已取消安装", Toast.LENGTH_SHORT).show();
                    }
                });
                alertDialog = ab.create();
                alertDialog.show();
            }

            @Override
            public void onFailure(HttpException e, String s) {
                Toast.makeText(MainActivity.this, "下载失败", Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 安装apk
     */
    public void update_apk() {
        File apkfile = new File(
                Environment.getExternalStorageDirectory() + "/update.apk");
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(apkfile),
                "application/vnd.android.package-archive");
        startActivity(intent);
    }
}



package test.bwie.com.checkedversion;

/**
 * Created by HCM on 2016/7/27.
 */
public class Info {
    private int version_code;//版本号
    private String versionName;//版本名称
    private String downloadUrl;//下载apk的路径

    public int getVersion_code() {
        return version_code;
    }

    public void setVersion_code(int version_code) {
        this.version_code = version_code;
    }

    public String getVersionName() {
        return versionName;
    }

    public void setVersionName(String versionName) {
        this.versionName = versionName;
    }

    public String getDownloadUrl() {
        return downloadUrl;
    }

    public void setDownloadUrl(String downloadUrl) {
        this.downloadUrl = downloadUrl;
    }

    @Override
    public String toString() {
        return "Info{" +
                "version_code=" + version_code +
                ", versionName='" + versionName + '\'' +
                ", downloadUrl='" + downloadUrl + '\'' +
                '}';
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值