android 更新版本案例

思路

在app启动时候去请求服务器上的app版本号,看是否大于本地版本号,本地版本号使用 SharedPreferences 方式保,当服务器版本号大于本地版本号就进行下载更新操作。

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()
       {
       
           int version = VersionUtils.getLocalVersion(mContext);

       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(); } }).show(); 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(); } }

2、VersionUtils

public class VersionUtils {


    public static int getLocalVersion(Context ctx) {
        int localVersion = 0;
        try {
            PackageInfo packageInfo = ctx.getApplicationContext()
                    .getPackageManager()
                    .getPackageInfo(ctx.getPackageName(), 0);
            localVersion = packageInfo.versionCode;
            Log.d("TAG", "当前版本号:" + localVersion);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return localVersion;
    }



    /**
     * 获取本地软件版本号名称
     */
    public static String getLocalVersionName(Context ctx) {
        String localVersion = "";
        try {
            PackageInfo packageInfo = ctx.getApplicationContext()
                    .getPackageManager()
                    .getPackageInfo(ctx.getPackageName(), 0);
            localVersion = packageInfo.versionName;
            Log.d("TAG", "当前版本名称:" + localVersion);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return localVersion;
    }


}

 

 

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、设置版本号

manifest.xml文件中声明了versionCode和versionName,然后获取的时候发现本地versionCode一直是1,不管怎么改都没有用。

 

解决方法:

 在AndroidStudio中版本号的声明是在 Module 的build.gradle文件中。在这边修改版本信息即可。

 

 

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

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

7、案例下载

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

VersionUtils.getLocalVersion(mContext)
posted @ 2019-08-30 16:57  好学Ace  阅读(322)  评论(0编辑  收藏  举报