android 更新版本

1、UpdateManager

package com.rfid.util;

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


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

import com.UHF.scanlable.R;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;



import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;

public class UpdateManager {
    
       OkHttpClient okHttpClient = new OkHttpClient();
       private Context mContext;
       private SharedPreferences preferences;
       private int version;
       private String apkName;
       private String apkUrl;
       
       private static final String URL ="http://localhost:8080/apkUpdateVersion/updateVersion.json";
       private static final String savePath = "/sdcard/updateAPK/";
       private String saveFileName = savePath;
       
       private ProgressBar mProgress;
       private static final int DOWNLOADING = 1;
       private static final int DOWNLOADED = 2;
       private static final int DOWNLOAD_FAILED = 3;
       private int progress;
       private boolean cancelFlag = false;
       
       private String updateDescription = "更新描述";
       private boolean forceUpdate = true; 
       
       
       private AlertDialog alertDialog1, alertDialog2;
       
       public UpdateManager(Context context) {
            this.mContext = context;
       }
       
       public void checkUpdate(){
           final int localVersion = getLocalVersion();
           Request request = new Request.Builder()
                    .url(URL).build();    
            Call call = okHttpClient.newCall(request);
            call.enqueue(new com.squareup.okhttp.Callback() {
                
                @Override
                public void onResponse(Response response) throws IOException {
                    
                    String json = response.body().string();
                    try {
                        JSONObject jsonObject = new JSONObject(json);
                        version = jsonObject.getInt("version");
                        apkName = jsonObject.getString("apkName");
                        apkUrl = jsonObject.getString("apkUrl");
                        
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                if(version > localVersion){
                                     showNoticeDialog(version, localVersion);
//                                     Message msg = new Message();
//                                     msg.what = 1;
//                                     mHandler.sendMessage(msg);
                                }
                                
                            }
                        }).start();
                    } catch (JSONException e) {
                        e.printStackTrace();

                    }
                }
                
                @Override
                public void onFailure(com.squareup.okhttp.Request request,
                        IOException ioexception) {
                     
                    
                }
            });
            
       }
       
       //获取本地版本
       private int getLocalVersion()
       {
           preferences = mContext.getSharedPreferences(VersionService.VERSION_KEY, mContext.MODE_ENABLE_WRITE_AHEAD_LOGGING | mContext.MODE_MULTI_PROCESS);
       
           VersionService verService = new VersionService(preferences);
           int version = verService.getVersion();
           
           return version;
       }
       
       public void showNoticeDialog(double serverVersion,double clientVersion) {
           if (serverVersion <= clientVersion)
                return;
           AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
           dialog.setTitle("发现新版本 :" + serverVersion);
           dialog.setMessage(updateDescription);
           
           dialog.setPositiveButton("现在更新", new OnClickListener() {
            
                @Override
                public void onClick(DialogInterface arg0, int arg1) {
                    arg0.dismiss();
                    showDownloadDialog();
                }
           });
           
           if(forceUpdate==false){
               dialog.setNegativeButton("待会更新", new OnClickListener() {
                
                @Override
                public void onClick(DialogInterface arg0, int arg1) {
                    arg0.dismiss();
                    
                }
            });
                 
           }
       }
       
       public void showDownloadDialog(){
           
           AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
           dialog.setTitle("正在更新");
           
           final LayoutInflater inflater = LayoutInflater.from(mContext);
    
           View v = inflater.inflate(R.layout.update_progress, null);
           mProgress = (ProgressBar) v.findViewById(R.id.update_progressBar);
           dialog.setView(v);
           
           if(forceUpdate==false){
               dialog.setNegativeButton("待会更新", new OnClickListener() {
                    
                    @Override
                    public void onClick(DialogInterface arg0, int arg1) {
                        arg0.dismiss();
                        cancelFlag = false;
                    }
                });
                
           }
           
           alertDialog2  = dialog.create();
           alertDialog2.setCancelable(false);
           alertDialog2.show();
           
           //下载apk
           downloadAPK();
           
       }
       
       //下载apk
       public void downloadAPK(){
           
           new Thread(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();
                    }
                    //修改保存apk名称 apk_v1.apk
                    saveFileName = savePath + apkName+"_V"+ version+".apk";
                    String apkFile = saveFileName;
                    File ApkFile = new File(apkFile);
                    FileOutputStream fos = new FileOutputStream(ApkFile);
                     
                    int count = 0;
                    byte buf[] = new byte[1024];
                    
                    do{
                        int numread = is.read(buf);
                        count += numread;
                        
                        progress = (int)(((float)count / length) * 100);
                        mHandler.sendEmptyMessage(DOWNLOADING);
                        
                        if(numread <= 0){
                            mHandler.sendEmptyMessage(DOWNLOADED);
                            break;
                        }
                        fos.write(buf, 0, numread);
                    }while(!cancelFlag);
                    
                    fos.close();
                    is.close();
                        
                } catch (Exception e) {
                    mHandler.sendEmptyMessage(DOWNLOAD_FAILED);
                    e.printStackTrace();
                }
                
            }
          }).start(); 
       }
       
       private Handler mHandler = new Handler(){
           
           @Override
           public void handleMessage(Message msg){
               
               switch (msg.what){
                   case DOWNLOADING:
                       mProgress.setProgress(progress);
                       break;
                   case DOWNLOADED:
                       if (alertDialog2 != null)
                           alertDialog2.dismiss();
                       //安装apk
                       installAPK();
                       break;
                   case DOWNLOAD_FAILED:
                       Toast.makeText(mContext, "网络断开,请稍候再试", Toast.LENGTH_LONG).show();
                       break;
                   default:
                       break;
               }
           }
           
       };
       
       
       public void installAPK(){
           File apkFile = new File(saveFileName);
           if (!apkFile.exists()) {
               return;
           }
           
           Intent intent = new Intent(Intent.ACTION_VIEW);
           intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
           intent.setDataAndType(Uri.parse("file://" + apkFile.toString()), "application/vnd.android.package-archive");
           mContext.startActivity(intent);
           
           //将服务版本保存到客户端
           saveSeverVersion();
       } 
       
       public void saveSeverVersion(){
           VersionService verService = new VersionService(preferences);
           verService.save(version, apkName);
       }

}

2、VersionService

package com.rfid.util;

import android.content.SharedPreferences;


public class VersionService {
    
    public final static String VERSION_KEY = "VERSION_KEY";
    public final static String APK_NAME = "APK_NAME";
    
    private SharedPreferences preferences;
    
    public VersionService(SharedPreferences preferences){
        this.preferences = preferences;
    }
    
    public int getVersion(){
         SharedPreferences.Editor editor = preferences.edit();
         int version = preferences.getInt(VERSION_KEY,1);
         return version;
    }
    
    public String getApkName(){
         SharedPreferences.Editor editor = preferences.edit();
         String apkName = preferences.getString(APK_NAME,"UHF_5100.apk");
         return apkName;
    }
    
    public boolean save(int version,String apkName){
         SharedPreferences.Editor editor = preferences.edit();
         preferences.getInt(VERSION_KEY,version);
         preferences.getString(APK_NAME,apkName);
         return editor.commit();
    }
}

3、update_progress.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

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

4、MainActivity调用方式

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);
        
        UpdateManager manager = new UpdateManager(MainActivity.this);
        // 检查软件更新
        manager.checkUpdate();
}

5、eclipse-android 开发工具 下载okhttp jar 包:

链接:https://pan.baidu.com/s/1qF-A93AuZf9weWsWQcyWrw 密码:19re

6、案例下载

 http://files.cnblogs.com/coolszy/UpdateSoftDemo.rar

猜你喜欢

转载自www.cnblogs.com/zoro-zero/p/11435947.html