Phonegap 版本minSdkVersion为8的时候的自动更新与升级

清单文件中:

<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="8"/>
清单文件

在主窗口MainActivity中

package fx.qj.xinjiangqj;

import android.os.Bundle;





import android.view.KeyEvent;

import android.view.Menu; 

import android.view.MenuItem;

import android.widget.Toast;



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.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;

import org.apache.cordova.*;





public class MainActivity extends DroidGap {

     private long exitTime = 0;

     String newVerName = "";//新版本名称

     int newVerCode = -1;//新版本号

     ProgressDialog pd = null;

     String UPDATE_SERVERAPK = "xx.apk";

    @Override

    public void onCreate(Bundle savedInstanceState) {

          super.onCreate(savedInstanceState);

          super.init();

          android.webkit.WebSettings settings = super.appView.getSettings();

          String appCachePath = this.getCacheDir().getAbsolutePath();

          settings.setAppCachePath(appCachePath);

          settings.setAllowFileAccess(true);

          settings.setAppCacheEnabled(true);

          super.setIntegerProperty("splashscreen",R.drawable.startup_bg1);

          super.loadUrl("file:///android_asset/www/index.html",5000);

          updateVersion();

    }



    @Override

    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.

        getMenuInflater().inflate(R.menu.main, menu);

        return true;

    }

    @Override

    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {

            exit();

            return false;

        }

        return super.onKeyDown(keyCode, event);

    }



    public void exit() {

        if ((System.currentTimeMillis() - exitTime) > 2000) {

            Toast.makeText(getApplicationContext(), "再按一次退出程序",

                    Toast.LENGTH_SHORT).show();

            exitTime = System.currentTimeMillis();

        } else {

            finish();

            System.exit(0);

        }

    }

    

    public void updateVersion(){      

        if(getServerVer()){

               int verCode = this.getVerCode(this);

               System.out.println(newVerCode);

               if(newVerCode>verCode){

                   doNewVersionUpdate();//更新版本

               }else{

                  //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;

            }

            

           

            public boolean getServerVer(){

                try {

                    String path=getResources().getString(R.string.url_server); 

                    URL url = new URL(path);

                    HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();

                    //httpConnection.setDoInput(true);

                    //httpConnection.setDoOutput(true);

                    //httpConnection.setRequestProperty("Content-type", "application/x-java-serialized-object");

                    httpConnection.setRequestMethod("GET");

                    httpConnection.connect();

                    InputStream inputStream = httpConnection.getInputStream();  

                    InputStreamReader reader = new InputStreamReader(inputStream);

                    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(MainActivity.this);

                        pd.setTitle("正在下载");

                        pd.setMessage("请稍后。。。");

                        pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);

                        String apkpath=getResources().getString(R.string.url_apk); 

                        downFile(apkpath);

                    }

                })

                .setNegativeButton("暂不更新", new DialogInterface.OnClickListener() {

                    

                    @Override

                    public void onClick(DialogInterface dialog, int which) {

                        // TODO Auto-generated method stub

                        //finish();

                    }

                }).create();

                //显示更新框

                dialog.show();

            }

            

           

            public void downFile(final String url){

                pd.show();

                new Thread(){

                    public void run(){

                        HttpClient client = new DefaultHttpClient();

                        HttpGet get = new HttpGet(url);

                        HttpResponse response;

                        System.out.println(url);

                        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();

                }

            };

            

           

            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.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory(),UPDATE_SERVERAPK))

                        , "application/vnd.android.package-archive");

                startActivity(intent);

            }

}
View Code

在服务器上的js文件

[{"verName":"xinjiangQJ","verCode":2}]
View Code

 

 

参考资料: http://blog.sina.com.cn/s/blog_5419658701014wg0.html

 

未测试的资料,使用xml存储数据:

http://blog.csdn.net/coolszy/article/details/7518345

http://blog.csdn.net/furongkang/article/details/6886526

你可能感兴趣的:(PhoneGap)