android检测应用版本更新

来源:互联网 发布:网络诈骗如何判刑 编辑:程序博客网 时间:2024/05/21 04:40
android版本的更新,必须要了解VersionName和VersionCode,这两个参数在AndroidManifest.xml中
VersionCode:对消费者不可见,仅用于应用市场、程序内部识别版本,判断新旧等用途。
VersionName:展示给消费者,消费者会通过它认知自己安装的版本。

下面贴上主要类的代码:

package com.UpdateApk165285727;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

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.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;

public class UpdateApk {
    /**
     * 获取网址内容
     * 
     * @param url
     * @return
     * @throws Exception
     * 
     */

    public String TAG = "Update";
    public ProgressDialog pBar;
    public Handler handler = new Handler();
    public float newVerCode = 0;
    public String newVerName = "";
    Main Context;// 定义主界面的类型变量

    public String UPDATE_SERVER = "http://www.sevenpad.com/guess_x/";//软件更新地址
    //public String UPDATE_SERVER = "http://gdown.baidu.com/data/wisegame/f98d235e39e29031/";
    public String UPDATE_APKNAME = "UpdateApk.apk";
    //public String UPDATE_APKNAME = "baiduxinwen.apk";
    public String UPDATE_VERJSON = "ver.json";
    public String UPDATE_SAVENAME = "UpdateApk.apk";

    public String getContent(String url) throws Exception {
        StringBuilder sb = new StringBuilder();

        HttpClient client = new DefaultHttpClient();
        HttpParams httpParams = client.getParams();
        // 设置网络超时参数
        HttpConnectionParams.setConnectionTimeout(httpParams, 3000);
        HttpConnectionParams.setSoTimeout(httpParams, 5000);
        try {
            HttpResponse response = client.execute(new HttpGet(url));
            HttpEntity entity = response.getEntity();
            if (response.getStatusLine().getStatusCode() == 200) {
                // 取出回应字串
                if (entity != null) {
                    BufferedReader reader = new BufferedReader(
                            new InputStreamReader(entity.getContent(), "UTF-8"),
                            8192);
                    String line = null;
                    while ((line = reader.readLine()) != null) {
                        sb.append(line + "\n");
                    }
                    reader.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            sb.append("\n");
            return sb.toString();
        }
        Log.e(TAG, sb.toString());
        return sb.toString();
    }

    /*
     * 一下所有操作是更新apk的功能
     */
    public boolean getServerVerCode(Main context) {
        try {
//这里要根据服务器的版本号,我直接设置来测试了
//            Context = context;
//            String verjson = getContent(UPDATE_SERVER + UPDATE_VERJSON);
//            JSONArray array = new JSONArray(verjson);
//            if (array.length() > 0) {
//                JSONObject obj = array.getJSONObject(0);
//                try {
//                    newVerCode = Float.parseFloat(obj.getString("verCode"));
//                    newVerName = obj.getString("verName");
//                } catch (Exception e) {
//                    newVerCode = -1;
//                    newVerName = "";
//                    return false;
//                }
//            }
            Context = context;
            newVerCode = 4;
        } catch (Exception e) {
            Log.e(TAG, e.getMessage());
            return false;
        }
        Log.e(TAG, String.valueOf(newVerCode));
        return true;
    }

    /** 弹出是否更新对话框 */
    public void doNewVersionUpdate() {
        StringBuffer sb = new StringBuffer();
        sb.append("当前版本:");
        sb.append(getVerName(Context));
        //sb.append(" Code:");
        //sb.append(getVerCode(Context));
        sb.append(", 发现新版本:");
        sb.append(newVerName);
        sb.append(" Code:");
        sb.append(newVerCode);
        sb.append(", 是否更新?");
        Dialog dialog = new AlertDialog.Builder(Context).setTitle("软件更新")
                .setMessage(sb.toString())
                // 设置内容
                .setPositiveButton("更新",// 设置确定按钮
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog,
                                    int which) {
                                pBar = new ProgressDialog(Context);
                                pBar.setTitle("正在下载");
                                pBar.setMessage("请稍候...");
                                pBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);

                                downFile(UPDATE_SERVER + UPDATE_APKNAME);

                            }
                        }).setNegativeButton("暂不更新",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                    int whichButton) {
                                // 点击"取消"按钮之后退出程序
                                // finish();
                                return;

                            }
                        }).create();// 创建
        // 显示对话框
        dialog.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(), UPDATE_SAVENAME);
                        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() {
        handler.post(new Runnable() {
            public void run() {
                pBar.cancel();
                Context.update();
            }
        });
    }

    /** 获取当前版本的代码级别 */
    public Float getVerCode(Context context) {
        Float verCode = -1.0f;
        try {
            verCode = Float.valueOf(context.getPackageManager().getPackageInfo(
                    "com.UpdateApk165285727", 0).versionCode);
        } catch (NameNotFoundException e) {
            Log.e(TAG, e.getMessage());
        }
        return verCode;
    }

    /** 获取当前版本的程序名称 */
    public Float getVerName(Context context) {
        String verName = "";
        try {
            verName = context.getPackageManager().getPackageInfo(
                    "com.UpdateApk165285727", 0).versionName;
        } catch (NameNotFoundException e) {
            Log.e(TAG, e.getMessage());
        }
        Float verNumber =  Float.parseFloat(verName);
        return verNumber;
    }

}

在主java里判断调用:

package com.UpdateApk165285727;

import java.io.File;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;

public class Main extends Activity {
    /** Called when the activity is first created. */
    UpdateApk updateApk = new UpdateApk();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        // 比较服务器版本//在 onCreate函数中调用
        if (updateApk.getServerVerCode(this)) {
            if (updateApk.newVerCode > updateApk.getVerName(this)) {
                updateApk.doNewVersionUpdate();
            }
        }
    }

    /** 执行安装 */
    public void update() {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(new File(Environment
                .getExternalStorageDirectory(), updateApk.UPDATE_SAVENAME)),
                "application/vnd.android.package-archive");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }
}

这里我是根据VerName来判断的,如果用VerCode判断会发生一些问题。
由于VerName是string类型,所以要转成float。
原创粉丝点击