android實現app版本更新案例

來源:互聯網
上載者:User

標籤:

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網路擷取與解析。

 

android實現app版本更新案例

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.