phoneGap中android程序自動更新代碼

package com.phonegap.test;

import org.apache.cordova.DroidGap;
import android.os.Bundle;


import android.view.Menu; 
import android.view.MenuItem;

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

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
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.util.Log;

public class PhoneGap_jqmActivity extends DroidGap {
 /** Called when the activity is first created. */
    String newVerName = "";//新版本名稱
    int newVerCode = -1;//新版本號
    ProgressDialog pd = null;
    String UPDATE_SERVERAPK = "ApkUpdateAndroid.apk";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);        
        super.loadUrl("file:///android_asset/www/index.html");
        updateVersion();//啓動時就檢查 或者 在菜單中調用
       

    }
    
    
   public void updateVersion(){
    if(getServerVer()){
           int verCode = this.getVerCode(this);
           if(newVerCode>verCode){
               doNewVersionUpdate();//更新版本
           }else{
               //alert("")
             notNewVersionUpdate();//提示已是最新版本
           }
       }
   }

      /**
         * 獲得版本號
         */
        public int getVerCode(Context context){
            int verCode = -1;
            try {
             String packName = context.getPackageName();
                verCode = context.getPackageManager().getPackageInfo(packName, 0).versionCode;
            } catch (NameNotFoundException e) {
                // TODO Auto-generated catch block
                Log.e("版本號獲取異常", e.getMessage());
            }
            return verCode;
        }

        /**
         * 獲得版本名稱
         */
        public String getVerName(Context context){
            String verName = "";
            try {
             String packName = context.getPackageName();
                verName = context.getPackageManager().getPackageInfo(packName, 0).versionName;
            } catch (NameNotFoundException e) {
                Log.e("版本名稱獲取異常", e.getMessage());
            }
            return verName;
        }
        
        /**
         * 從服務器端獲得版本號與版本名稱
         * @return
         */
        public boolean getServerVer(){
            try {
                URL url = new URL("http://192.168.0.100:88/version.js");
                HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
                httpConnection.setDoInput(true);
                httpConnection.setDoOutput(true);
                httpConnection.setRequestMethod("GET");
                httpConnection.connect();
                InputStreamReader reader = new InputStreamReader(httpConnection.getInputStream());
                BufferedReader bReader = new BufferedReader(reader);
                String json = bReader.readLine();
                JSONArray array = new JSONArray(json);
                JSONObject jsonObj = array.getJSONObject(0);
                newVerCode = Integer.parseInt(jsonObj.getString("verCode"));        
                newVerName = jsonObj.getString("verName");
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return true;//如果這裏改爲false 則不更新會退出程序
            } 
            return true;
        }
        
        /**
         * 不更新版本
         */
        public void notNewVersionUpdate(){
            int verCode = this.getVerCode(this);
            String verName = this.getVerName(this);
            StringBuffer sb = new StringBuffer();
            sb.append("當前版本:");
            sb.append(verName);
            sb.append(" Code:");
            sb.append(verCode);
            sb.append("\n已是最新版本,無需更新");
            Dialog dialog = new AlertDialog.Builder(this)
            .setTitle("軟件更新")
            .setMessage(sb.toString())
            .setPositiveButton("確定", new DialogInterface.OnClickListener() {
                
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub
                    finish();
                }
            }).create();
            dialog.show();
        }
        
        /**
         * 更新版本
         */
        public void doNewVersionUpdate(){
            int verCode = this.getVerCode(this);
            String verName = this.getVerName(this);
            StringBuffer sb = new StringBuffer();
            sb.append("當前版本:");
            sb.append(verName);
            sb.append(" Code:");
            sb.append(verCode);
            sb.append(",發現版本:");
            sb.append(newVerName);
            sb.append(" Code:");
            sb.append(newVerCode);
            sb.append(",是否更新");
            Dialog dialog = new AlertDialog.Builder(this)
            .setTitle("軟件更新")
            .setMessage(sb.toString())
            .setPositiveButton("更新", new DialogInterface.OnClickListener() {
                
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub
                    pd = new ProgressDialog(PhoneGap_jqmActivity.this);
                    pd.setTitle("正在下載");
                    pd.setMessage("請稍後。。。");
                    pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                    downFile("http://192.168.0.100:88/phoneGap_jqm.apk");
                }
            })
            .setNegativeButton("暫不更新", new DialogInterface.OnClickListener() {
                
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub
                    //finish();
                }
            }).create();
            //顯示更新框
            dialog.show();
        }
        
        /**
         * 下載apk
         */
        public void downFile(final String url){
            pd.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_SERVERAPK);
                            fileOutputStream = new FileOutputStream(file);
                            byte[] b = new byte[1024];
                            int charb = -1;
                            int count = 0;
                            while((charb = is.read(b))!=-1){
                                fileOutputStream.write(b, 0, charb);
                                count += charb;
                            }
                        }
                        fileOutputStream.flush();
                        if(fileOutputStream!=null){
                            fileOutputStream.close();
                        }
                        down();
                    }  catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }.start();
        }
        
        Handler handler = new Handler() {

            @Override
            public void handleMessage(Message msg) {

                super.handleMessage(msg);                
                pd.cancel();
                update();
            }
        };
        
        /**
         * 下載完成,通過handler將下載對話框取消
         */
        public void down(){
            new Thread(){
                public void run(){
                    Message message = handler.obtainMessage();
                    handler.sendMessage(message);
                }
            }.start();
        }
        
        /**
         * 安裝應用
         */
        public void update(){
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory(),UPDATE_SERVERAPK))
                    , "application/vnd.android.package-archive");
            startActivity(intent);
        }

}


其中 服務器上version.js 文件格式 [{"verName":"app","verCode":2}]
改動:String packName = context.getPackageName();
這裏取apk名稱
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章