App 版本更新 versionUpdate

极客学院提供为期30天的免费编程课程,并有大量VIP等待领取。想在线学习编程的小伙伴们快来参与吧!

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

极客学院30天免费课程福利,大量VIP等着你领养,想在线学编程的小伙伴速来,手快戳

极客学院的学习记录:

App 版本更新步骤:
1、checkUpdate()//检测版本是否需要更新
2、downLoadAPK()//下载新版本的APP
3、installAPK()//安装新版本APP

分析:
1、线上线下版本号比对,判断是否需要更新:
1)访问服务器 请求服务器中App 版本信息。
2)查询本地App版本信息。
2、是否更新:
1)有新版本需要更新:
使用对话框询问用户是否选择更新
showNoticeDialog();
2)没有新版本不更新:
提示:已经是最新版本不需要更新。
3、更新:
downLoadAPK();
showDownLoadDialog() ;//显示现在进度

4、安装:installAPK;
使用Android自带安装方式安装。

java Code:

package com.autoupdate.zyh;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
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.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

/**
 * @author zyh
 * @version 创建时间:2015年7月28日 上午9:10:31 类说明:
 */
public class UpdateManager {

    private ProgressBar mProgressbar;
    private int mProgress;
    private Dialog mDownLoadDialog;
    private String mSavefilePath;// 下载的APK 保存地址
    private static final String path = "http://aps.yuandaitong.com/index.php?a=seed";
    private static final int DOWNLOADING = 1;// 加载中
    private static final int DOWNLOAD_FINISH = 2;// 加载完成
    private String mVersion_name; // APk名称
    private String mVersion_code;// apk版本号
    private String mVersion_desc;// 更新版本描述
    private String mVersion_path;// 下载 Apk 地址

    private boolean mIsCancel;// 是否取消下载

    private Context mContext;

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            try {
                Log.i("volley", msg.toString());
                JSONObject jsonObj = (JSONObject) msg.obj;
                String jsonStr = jsonObj.getString("data");
                JSONObject obj = new JSONObject(jsonStr);
                mVersion_code = obj.getString("version_code");
                mVersion_desc = obj.getString("version_desc");
                mVersion_name = obj.getString("version_name");
                mVersion_path = obj.getString("version_path");
                if (isUpdate()) {
                    showNoticeDialog();
                } else {
                    Toast.makeText(mContext, "已经是最新版本", 1).show();
                }
                Log.i("volley", mVersion_path);
            } catch (JSONException e) {
                e.printStackTrace();
            }

        };

    };

    private Handler mUpdateProgressHandler = new Handler() {
        public void handleMessage(Message msg) {

            switch (msg.what) {
            case DOWNLOADING:
                // 更新当前进度
                mProgressbar.setProgress(mProgress);
                break;
            case DOWNLOAD_FINISH:
                // 隐藏 下载对话框
                mDownLoadDialog.dismiss();
                // 安装下载的apk
                installAPK();
                break;

            default:
                break;
            }

        };
    };

    public UpdateManager(Context context) {
        this.mContext = context;
    }

    /**
     * 检测软件是否需要更新
     */
    public void checkUpdate() {
        RequestQueue requestQueue = Volley.newRequestQueue(mContext);

        JsonObjectRequest request = new JsonObjectRequest(path, null,
                new Listener<JSONObject>() {

                    @Override
                    public void onResponse(JSONObject response) {
                        Message msg = Message.obtain();
                        msg.obj = response;
                        mHandler.sendMessage(msg);

                    }

                }, new ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                });

        requestQueue.add(request);

    }

    /*
     * 与本地版本比较判断是否需要更新
     * 
     * @return
     */
    protected boolean isUpdate() {
        int serverVersion = Integer.valueOf(mVersion_code);
        int localVersion = 1;
        try {
            localVersion = mContext.getPackageManager().getPackageInfo(
                    "com.autoupdate.zyh", 0).versionCode;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        if (serverVersion > localVersion) {
            return true;
        }
        return false;
    }

    /*
     * 有更新时提示对话框
     */

    protected void showNoticeDialog() {
        AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
        dialog.setTitle("提示").setMessage("有新版发布,需要更新\n" + mVersion_desc)
                .setNegativeButton("取消", new OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).setPositiveButton("去更新", new OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        showDownLoadDialog();
                        dialog.dismiss();
                    }
                }).create().show();
    }

    /*
     * 显示下载进度 的对话框
     */
    protected void showDownLoadDialog() {
        View view = LayoutInflater.from(mContext).inflate(
                R.layout.dialog_progress, null);
        AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
        dialog.setTitle("下载中").setView(view);
        mProgressbar = (ProgressBar) view.findViewById(R.id.id_progress);

        dialog.setNegativeButton("取消", new OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {

                // 取消对话框
                dialog.dismiss();
                mIsCancel = true;// 取消下载

            }
        });
        mDownLoadDialog = dialog.create();
        mDownLoadDialog.show();

        // TODO 下载APK
        downLoadAPK();
    }

    /*
     * 下载APK文件
     */
    private void downLoadAPK() {
        new Thread() {
            public void run() {
                InputStream in = null;
                FileOutputStream out = null;
                try {
                    if (Environment.getExternalStorageState().equals(
                            Environment.MEDIA_MOUNTED)) {
                        String SDpath = Environment
                                .getExternalStorageDirectory() + File.separator;
                        mSavefilePath = SDpath + "DownLoadAPKS";
                        File dir = new File(mSavefilePath);
                        if (!dir.exists()) {
                            dir.mkdir();
                        }
                        HttpURLConnection conn = (HttpURLConnection) new URL(
                                mVersion_path).openConnection();
                        conn.setDoInput(true);
                        conn.setDoOutput(true);
                        conn.setConnectTimeout(30 * 1000);
                        conn.connect();
                        in = conn.getInputStream();
                        int length = conn.getContentLength();
                        File apkFile = new File(mSavefilePath, mVersion_name);
                        out = new FileOutputStream(apkFile);
                        int count = 0;
                        byte[] buffer = new byte[1024];
                        while (!mIsCancel) {
                            int numRead = in.read(buffer);
                            count += numRead;

                            // 计算进度条当前位置
                            mProgress = (int) ((float) count / length * 100);

                            mUpdateProgressHandler
                                    .sendEmptyMessage(DOWNLOADING);
                            // 下载完成
                            if (numRead < 0) {
                                mUpdateProgressHandler
                                        .sendEmptyMessage(DOWNLOAD_FINISH);
                                break;
                            }
                            out.write(buffer, 0, numRead);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    try {
                        out.close();
                        in.close();
                    } catch (Exception e2) {
                    }
                }
            };
        }.start();
    }

    private void installAPK() {

        File apkFile = new File(mSavefilePath, mVersion_name);
        if (!apkFile.exists()) {
            return;
        }

        Intent intent = new Intent(Intent.ACTION_VIEW);
        Uri uri = Uri.parse("file://" + apkFile.toString());
        intent.setDataAndType(uri, "application/vnd.android.package-archive");
        mContext.startActivity(intent);
    }

}

Dialog.xml:

?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

    <ProgressBar
        android:id="@+id/id_progress"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

说明:

(一)使用方式

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        new UpdateManager(this).checkUpdate();//看这里
    }

}

(二)这是Volley 框架 具体的Jar包 在文章结尾的源码中有 ,而且不需要积分。

/**
     * 检测软件是否需要更新
     */
    public void checkUpdate() {
        RequestQueue requestQueue = Volley.newRequestQueue(mContext);

        JsonObjectRequest request = new JsonObjectRequest(path, null,
                new Listener<JSONObject>() {

                    @Override
                    public void onResponse(JSONObject response) {
                        Message msg = Message.obtain();
                        msg.obj = response;
                        mHandler.sendMessage(msg);

                    }

                }, new ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                });

        requestQueue.add(request);

    }

免费源码下载

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值