android更新應用程序

直接貼代碼:

config類:

[html]  

package com.tutor.config;  

  

import org.json.JSONArray;  

import org.json.JSONObject;  

import com.tutor.update.R;  

import android.content.Context;  

import android.content.pm.PackageInfo;  

import android.content.pm.PackageManager;  

import android.content.pm.PackageManager.NameNotFoundException;  

import android.util.Log;  

  

public class Config  

{  

  

    public String UPDATE_SERVER = "https://10.81.48.181:8080/update/";  

  

    public String UPDATE_APKNAME = "";  

  

    public String UPDATE_SAVENAME = "update.apk";  

  

    public String UPDATE_VERJSON = "ver.json";  

  

    public static int newVerCode;  

  

    public static String newVerName;  

  

    /**  

     * 獲取當前版本號  

     *   

     * @param context  

     * @return  

     */  

    public int getVerCode(Context context)  

    {  

        int verCode = -1;  

        try  

        {  

            // 獲取packagemanager的實例  

            PackageManager packageManager = context.getPackageManager();  

            // getPackageName()是你當前類的包名,0代表是獲取版本信息  

            PackageInfo packInfo =  

                    packageManager.getPackageInfo(context.getPackageName(), 0);  

            verCode = packInfo.versionCode;  

            // verCode =  

            // context.getPackageManager().getPackageInfo(  

            // "com.example.update", 0).versionCode;  

            System.out.println("nowcode—?>>>" + verCode);  

        }  

        catch (NameNotFoundException e)  

        {  

            Log.e("RG", e.getMessage());  

        }  

        return verCode;  

    }  

  

    /**  

     * 獲取版本名稱  

     *   

     * @param context  

     * @return  

     */  

    public String getVerName(Context context)  

    {  

        String verName = "";  

  

        try  

        {  

            // 獲取packagemanager的實例  

            PackageManager packageManager = context.getPackageManager();  

            // getPackageName()是你當前類的包名,0代表是獲取版本信息  

            PackageInfo packInfo =  

                    packageManager.getPackageInfo(context.getPackageName(), 0);  

            verName = packInfo.versionName;  

            // verName =  

            // context.getPackageManager().getPackageInfo(  

            // "com.example.update", 0).versionName;  

        }  

        catch (NameNotFoundException e)  

        {  

            Log.e("RG", e.getMessage());  

        }  

        return verName;  

    }  

  

    // public static String getVerName(Context context)  

    // {  

    // String verName =  

    // context.getResources().getText(R.string.app_versionName)  

    // .toString();  

    // return verName;  

    // }  

    public static String getAppName(Context context)  

    {  

        String verName =  

                context.getResources().getText(R.string.app_name).toString();  

        return verName;  

    }  

  

    /**  

     * 檢查服務器的版本  

     *   

     * @return  

     */  

    public boolean getServerVerCode()  

    {  

        try  

        {  

            String verjson =  

                    NetworkTool.getContent(UPDATE_SERVER + UPDATE_VERJSON);  

            System.out.println("verjson—>>>" + verjson);  

            JSONArray array = new JSONArray(verjson);  

            if (array.length() > 0)  

            {  

                JSONObject obj = array.getJSONObject(0);  

                try  

                {  

                    newVerCode = Integer.parseInt(obj.getString("verCode"));  

                    newVerName = obj.getString("verName");  

                    System.out.println("newVerCode—>>>" + newVerCode);  

                    System.out.println("newVerName—>>>" + newVerName);  

                }  

                catch (Exception e)  

                {  

                    newVerCode = -1;  

                    newVerName = "";  

                    return false;  

                }  

            }  

        }  

        catch (Exception e)  

        {  

            Log.e("RG", e.getMessage());  

            return false;  

        }  

        return true;  

    }  

}  

NetworkTool類:

[html]  

package com.tutor.config;  

  

import java.io.IOException;  

import java.io.InputStream;  

import java.net.HttpURLConnection;  

import java.net.MalformedURLException;  

import java.net.URL;  

  

public class NetworkTool  

{  

  

    public static String getContent(String filename)  

    {  

        URL url;  

        String str;  

        try  

        {  

            url = new URL(filename);  

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

            conn.connect();  

            int len = conn.getContentLength();  

            InputStream is = conn.getInputStream();  

            byte[] by = new byte[len];  

            is.read(by);  

            str = new String(by, "UTF-8");  

            return str;  

        }  

        catch (MalformedURLException e)  

        {  

            // TODO Auto-generated catch block  

            e.printStackTrace();  

            return "";  

        }  

        catch (IOException e)  

        {  

            // TODO Auto-generated catch block  

            e.printStackTrace();  

            return "";  

        }  

    }  

}  

UpdateApplication類:

[html] 

package com.tutor.config;  

  

  

import android.content.Context;  

  

public class UpdateApplication  

{  

  

    /**  

     * 檢查更新狀態  

     *   

     * @param context  

     * @return  

     */  

    public static boolean getUpdateInfo(Context context)  

    {  

  

        Config cof = new Config();  

        cof.getServerVerCode();  

        if (cof.getVerCode(context) < Config.newVerCode)  

        {  

            return true;  

        }  

        else  

        {  

            return false;  

        }  

  

    }  

  

    /**  

     * 馬上更新  

     *   

     * @param context  

     */  

    public static void newUpdate(Context context)  

    {  

        UpdateManager mUpdateManager = new UpdateManager(context);  

        mUpdateManager.checkUpdateInfo();  

    }  

}  

UpdateManager類:

[html]  

package com.tutor.config;  

  

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 com.tutor.update.R;  

import android.app.AlertDialog;  

import android.app.Dialog;  

import android.app.AlertDialog.Builder;  

import android.content.Context;  

import android.content.DialogInterface;  

import android.content.Intent;  

import android.content.DialogInterface.OnClickListener;  

import android.net.Uri;  

import android.os.Handler;  

import android.os.Message;  

import android.view.LayoutInflater;  

import android.view.View;  

import android.widget.ProgressBar;  

  

public class UpdateManager  

{  

  

    private Context mContext;  

  

    // 提示語  

    private String updateMsg = "有最新的軟件包哦,親快下載吧~";  

  

    // 返回的安裝包url  

    private String apkUrl = "https://10.81.48.181:8080/update/UpdateDemo.apk";  

  

    private Dialog noticeDialog;  

  

    private Dialog downloadDialog;  

  

    /* 下載包安裝路徑 */  

    private static final String savePath = "/sdcard/updatedemo/";  

  

    private static final String saveFileName = savePath  

            + "UpdateDemoRelease.apk";  

  

    /* 進度條與通知ui刷新的handler和msg常量 */  

    private ProgressBar mProgress;  

  

    private static final int DOWN_UPDATE = 1;  

  

    private static final int DOWN_OVER = 2;  

  

    private int progress;  

  

    private Thread downLoadThread;  

  

    private boolean interceptFlag = false;  

  

    private Handler mHandler = new Handler()  

    {  

  

        public void handleMessage(Message msg)  

        {  

            switch (msg.what)  

            {  

            case DOWN_UPDATE:  

                mProgress.setProgress(progress);  

                break;  

            case DOWN_OVER:  

  

                installApk();  

                break;  

            default:  

                break;  

            }  

        };  

    };  

  

    public UpdateManager(Context context)  

    {  

        this.mContext = context;  

    }  

  

    // 外部接口讓主Activity調用  

    public void checkUpdateInfo()  

    {  

        showNoticeDialog();  

    }  

  

    private void showNoticeDialog()  

    {  

        AlertDialog.Builder builder = new Builder(mContext);  

        builder.setTitle("軟件版本更新");  

        builder.setMessage(updateMsg);  

        builder.setPositiveButton("下載", new OnClickListener()  

        {  

  

            @Override  

            public void onClick(DialogInterface dialog, int which)  

            {  

                dialog.dismiss();  

                showDownloadDialog();  

            }  

        });  

        builder.setNegativeButton("以後再說", new OnClickListener()  

        {  

  

            @Override  

            public void onClick(DialogInterface dialog, int which)  

            {  

                dialog.dismiss();  

            }  

        });  

        noticeDialog = builder.create();  

        noticeDialog.show();  

    }  

  

    private void showDownloadDialog()  

    {  

        AlertDialog.Builder builder = new Builder(mContext);  

        builder.setTitle("軟件版本更新");  

  

        final LayoutInflater inflater = LayoutInflater.from(mContext);  

        View v = inflater.inflate(R.layout.progress, null);  

        mProgress = (ProgressBar) v.findViewById(R.id.progress);  

  

        builder.setView(v);  

        builder.setNegativeButton("取消", new OnClickListener()  

        {  

  

            @Override  

            public void onClick(DialogInterface dialog, int which)  

            {  

                dialog.dismiss();  

                interceptFlag = true;  

            }  

        });  

        downloadDialog = builder.create();  

        downloadDialog.show();  

  

        downloadApk();  

    }  

  

    private Runnable mdownApkRunnable = new Runnable()  

    {  

  

        @Override  

        public void run()  

        {  

            try  

            {  

                URL url = new URL(apkUrl);  

  

                HttpURLConnection conn =  

                        (HttpURLConnection) url.openConnection();  

                conn.connect();  

                int length = conn.getContentLength();  

                InputStream is = conn.getInputStream();  

  

                File file = new File(savePath);  

                if (!file.exists())  

                {  

                    file.mkdir();  

                }  

                String apkFile = saveFileName;  

                File ApkFile = new File(apkFile);  

                FileOutputStream fos = new FileOutputStream(ApkFile);  

  

                int count = 0;  

                byte buf[] = new byte[24];  

  

                do  

                {  

                    int numread = is.read(buf);  

                    count += numread;  

                    progress = (int) (((float) count / length) * 100);  

                    // 更新進度  

                    mHandler.sendEmptyMessage(DOWN_UPDATE);  

                    if (numread <= 0)  

                    {  

                        // 下載完成通知安裝  

                        mHandler.sendEmptyMessage(DOWN_OVER);  

                        break;  

                    }  

                    fos.write(buf, 0, numread);  

                } while (!interceptFlag);// 點擊取消就停止下載.  

  

                fos.close();  

                is.close();  

            }  

            catch (MalformedURLException e)  

            {  

                e.printStackTrace();  

            }  

            catch (IOException e)  

            {  

                e.printStackTrace();  

            }  

  

        }  

    };  

  

    /**  

     * 下載apk  

     *   

     * @param url  

     */  

  

    private void downloadApk()  

    {  

        downLoadThread = new Thread(mdownApkRunnable);  

        downLoadThread.start();  

    }  

  

    /**  

     * 安裝apk  

     *   

     * @param url  

     */  

    private void installApk()  

    {  

        if (downloadDialog.isShowing())  

        {  

            downloadDialog.dismiss();  

        }  

        File apkfile = new File(saveFileName);  

        if (!apkfile.exists())  

        {  

            return;  

        }  

        Intent i = new Intent(Intent.ACTION_VIEW);  

        i.setDataAndType(Uri.parse("file://" + apkfile.toString()),  

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

        mContext.startActivity(i);  

  

    }  

}  

MainAcitivity:

[html]  

package com.tutor.update;  

  

import com.tutor.config.UpdateApplication;  

import android.app.Activity;  

import android.os.Bundle;  

import android.view.View;  

import android.view.View.OnClickListener;  

import android.widget.Button;  

import android.widget.Toast;  

  

public class MainAcitivity extends Activity  

{  

  

  

    @Override  

    public void onCreate(Bundle savedInstanceState)  

    {  

        super.onCreate(savedInstanceState);  

        setContentView(R.layout.main);  

        Button bt = (Button) findViewById(R.id.button1);  

        bt.setOnClickListener(new OnClickListener()  

        {  

  

            @Override  

            public void onClick(View v)  

            {  www.aiwalls.com

                if (UpdateApplication.getUpdateInfo(MainAcitivity.this))  

                {  

                    UpdateApplication.newUpdate(MainAcitivity.this);  

                }  

                else  

                {  

                    Toast.makeText(MainAcitivity.this, "程序已經是最新狀態!謝謝使用",  

                            Toast.LENGTH_SHORT).show();  

                }  

  

            }  

        });  

    }  

}  

 

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *