android实现app版本更新案例

AndroidMainfest.xml。配置相关权限

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.mytest.versionupdate"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="21" />
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
View Code

 

main.xml,

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.mytest.autoupdate.MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

</RelativeLayout>
View Code

 

downloadapk_progress.xml,自定义下载进度view

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.mytest.autoupdate.MainActivity" >

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

</LinearLayout>
View Code

 

MainActivity.java 中调用自动更新

package com.mytest.autoupdate;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        new AutoUpdateManager(this).checkIsNeedUpdate();
    }

}
View Code

 

AutoUpdateManager.java

package com.mytest.autoupdate;

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

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

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.AlteredCharSequence;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;

public class AutoUpdateManager {

    private final String LOG_TAG = "AutoUpdateManager";
    private Context context;

    public AutoUpdateManager(Context context) {
        this.context = context;
    }

    // 判断版本更新url
    private final String CHECK_VERSION__URL = "http://192.168.23.1:8080/testapp/version_json";

    /**
     * 检查是否需要更新
     */
    public void checkIsNeedUpdate() {

        // 获取版本信息
        new Thread(new Runnable() {

            @Override
            public void run() {
                // 获取版本信息
                String versionJson = getVersionInfo();
                if (versionJson != null && !"".equals(versionJson.trim())) {
                    Message msg = versionInfoHandler.obtainMessage();
                    msg.obj = versionJson;
                    versionInfoHandler.sendMessage(msg);
                }

            }
        }).start();

        // 对比版本
        if (!isLastVersion()) {
            new AlertDialog.Builder(context).setTitle("提示").setMessage("软件有更新,是否下载更新?")
                    .setPositiveButton("立即更新", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            // 显示下载进度条
                            showDownLoadDialog();

                            // 下载apk文件
                            downloadAPKFile();

                            // 安装apk
                            // todo
                        }
                    }).setNegativeButton("下次再说", null).create().show();

        } else {
            Toast.makeText(context, "已经是最新版本", Toast.LENGTH_SHORT).show();
        }
    }



    private ProgressBar download_progressbar;
    private AlertDialog downLoadDialog;
    private boolean isCancelDownload = false;
    private final int DOWNLOAD_STATE_FININSH = 1;
    private final int DOWNLOAD_STATE_LOAD = 0;
    private int downloadCurProgress;

    private Handler downloadHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.arg1) {
            case DOWNLOAD_STATE_LOAD:
                download_progressbar.setProgress(downloadCurProgress);
                break;
            case DOWNLOAD_STATE_FININSH:
                downLoadDialog.dismiss();
                
                installAPK();
                
                break;
            }
        }

    };

    private void showDownLoadDialog() {
        downLoadDialog = new AlertDialog.Builder(context).setTitle("下载中")
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        isCancelDownload = true;
                    }
                }).create();

        View view = LayoutInflater.from(context).inflate(R.layout.downloadapk_progress, null);
        downLoadDialog.setView(view);

        download_progressbar = (ProgressBar) view.findViewById(R.id.download_progressbar);

        downLoadDialog.show();

    }

    /**
     * 下载apk文件
     */
    private void downloadAPKFile() {
        Log.v(LOG_TAG, "downloadAPKFile->" + versiondownloadurl);

        new Thread(new Runnable() {

            @Override
            public void run() {
                try {

                    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {

                        String dirPath = Environment.getExternalStorageDirectory() + "/";
                        saveApkPath = dirPath + "autoupdate";

                        File file = new File(saveApkPath);
                        if (file.exists() == false) {
                            file.mkdir();
                        }
                        saveApkFileName = "version" + versioncode;
                        File apkFile = new File(saveApkPath,saveApkFileName );
                        FileOutputStream fos = new FileOutputStream(apkFile);

                        HttpURLConnection conn = (HttpURLConnection) new URL(versiondownloadurl).openConnection();
                        int fileSize = conn.getContentLength();

                        InputStream is = conn.getInputStream();
                        int len = 0;
                        int count = 0;
                        byte[] buff = new byte[1024];
                        while (!isCancelDownload) {
                            len = is.read(buff);

                            // 计算当前进度
                            count += len;
//                            Log.v(LOG_TAG, "downloadCurProgress->"+"count:"+count+",fileSize:"+fileSize);
                            downloadCurProgress = (int) (((float)count / fileSize) * 100);
//                            Log.v(LOG_TAG, "downloadCurProgress->"+downloadCurProgress);
                            Message msg = downloadHandler.obtainMessage();
                            msg.arg1 = DOWNLOAD_STATE_LOAD;
                            downloadHandler.sendMessage(msg);

                            if (len < 0) {
                                Message msg2 = downloadHandler.obtainMessage();    
                                msg2.arg1 = DOWNLOAD_STATE_FININSH;
                                //注意必须发送新的消息对象
                                downloadHandler.sendMessage(msg2); 
                                break;
                            }

                            fos.write(buff, 0, len);
                        }

                        is.close();
                    }

                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
        }).start();
    
    }

    /**
     * 是否是最新版本
     * 
     * @return
     */
    private boolean isLastVersion() {
        try {
            int curVer = context.getPackageManager().getPackageInfo("com.mytest.autoupdate", 0).versionCode;

            if (curVer < versioncode) {
                return true;
            }
        } catch (NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return false;
    }

    // 版本信息。
    private int versioncode;
    private String versionname;
    private String versiondesc;
    private String versiondownloadurl;
    private String saveApkFileName;
    private String saveApkPath;// apk保存路径

    private Handler versionInfoHandler = new Handler() {
        public void handleMessage(Message msg) {
            String versionJson = (String) msg.obj;

            try {
                JSONTokener jt = new JSONTokener(versionJson);
                JSONObject obj = (JSONObject) jt.nextValue();

                // demo数据
                // {"versioncode":3,"versionname":"testapp","desc":"增加了XX功能","versiondownloadurl":"http://192.168.23.1:8080/testapp/VersionUpdate.apk"}

                versionname = obj.getString("versionname");
                versiondesc = obj.getString("versiondesc");
                versiondownloadurl = obj.getString("versiondownloadurl");
                versioncode = obj.getInt("versioncode");

                Log.v(LOG_TAG, versionname + "," + versioncode);

            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        };
    };

    /**
     * 获取版本信息
     */
    private String getVersionInfo() {
        StringBuffer jsonRst = new StringBuffer();
        try {
            HttpURLConnection conn = (HttpURLConnection) new URL(CHECK_VERSION__URL).openConnection();

            conn.setRequestMethod("GET");
            InputStream is = conn.getInputStream();

            int len = 0;
            byte[] buffer = new byte[1024];
            while ((len = is.read(buffer)) != -1) {
                jsonRst.append(new String(buffer, 0, len, "UTF-8"));
            }
            is.close();

        } catch (Exception e) {

            e.printStackTrace();
        }

        return jsonRst.toString();
    }

    /**
     * 安装apk
     */
    private void installAPK() {
        File file  = new File(saveApkPath+"/"+saveApkFileName);
        if(file.exists()==false){
            return;
        }
        
        Intent intent = new Intent();
        Uri uri = Uri.parse("file://"+file.toString());
        intent.setDataAndType(uri, "application/vnd.android.package-archive");
        context.startActivity(intent);
    };    
}
View Code

 

主要知识点:
1、handler与message的使用;
2、自定义dialog的使用(在下载进度中);
3、下载文件到sd中。
4、安装apk文件。
5、json网络获取与解析。

 

posted @ 2015-07-27 21:41  2015android  阅读(916)  评论(0编辑  收藏  举报