Android中实现app版本更新

1,获取本地程序apk版本,并开启服务(下面这段代码一般在主Activity中的onCreate()方法中执行的,并开启后台服务下载新版本的apk)

//获取apk包文件的管理者对象
PackageManager manager = getPackageManager();
String apkVersion = ""try{
      PackageInfo packageInfo = manager.getPackageInfo(getPackagename,PackageManager.GET_ACTIVITIES);
     //获取到当前apk版本
     apkVersion=packageInfo.versionName;
    } catch (NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
    }

//开始服务的跳转,到service类    
Intent intent=new Intent(this,UpdateApkService.class);
intent.putExtra("apkVersion", apkVersion);
startService(intent);    

2,在服务UpdataApkService.java文件中的代码如下:

package com.example.queryencyclopediademo01.service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.IntentService;
import android.content.Intent;
import android.os.Environment;
import android.os.Looper;
import android.widget.Toast;

import com.example.queryencyclopediademo01.common.CBKApi;
import com.example.queryencyclopediademo01.domain.Apk;
import com.example.queryencyclopediademo01.utils.HttpUtils;
/**
 * 自定义更新Apk的服务类
 * @author dell
 *
 */
public class UpdateApkService extends IntentService {

    public UpdateApkService() {
        super("");
        // TODO Auto-generated constructor stub
    }

    /**
     *  声明Apk对象
     */
    private Apk apk;
    
    

    @Override
    protected void onHandleIntent(Intent intent) {
        System.out.println("onHandleIntent中线程的名称:"+Thread.currentThread().getName());
        String apkVersion=intent.getStringExtra("apkVersion");
        System.out.println("当前应用程序的版本名称:"+apkVersion);
        
        try {
            byte[] buffer=HttpUtils.getNetBytes(CBKApi.UPDATE_APK_PATH);
            if(buffer!=null){
                JSONObject jsonObject=new JSONObject(new String(buffer));
                this.apk=Apk.jsonParseApk(jsonObject);
                
                this.downLoadApk(apkVersion);
            }else{
                System.out.println("====获取最新APK文件失败!===");
                //Toast.makeText(this, "获取最新APK文件失败!", Toast.LENGTH_LONG).show();
            }
            
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
    }


    /**
     * 下载最新apk,尽量不要在3G网络下使用,会浪费用户很多流量
     * @param apkVersion
     */
    private void downLoadApk(String apkVersion) {
        //如果网上最新版本和当前运行版本不相同,则下载
        if(!this.apk.getVersion().equals(apkVersion)){
            HttpClient httpClient=new DefaultHttpClient();
            HttpGet httpGet=new HttpGet(apk.getUrl());
            HttpResponse httpResponse=null;
            InputStream inputStream=null;
            
            File file=new File(Environment.getExternalStorageDirectory().getAbsolutePath()+File.separator+"new.apk");
            OutputStream outputStream=null;
            byte[] buffer=new byte[1024];
            int len=0;
            
            try {
                httpResponse=httpClient.execute(httpGet);
                if(httpResponse.getStatusLine().getStatusCode()==200){
                    inputStream=httpResponse.getEntity().getContent();
                    outputStream=new FileOutputStream(file);
                    while((len=inputStream.read(buffer))!=-1){
                        outputStream.write(buffer, 0, len);
                    }
                    
                    outputStream.flush();
                    Toast.makeText(getApplicationContext(), "最新APK下载成功!", Toast.LENGTH_LONG).show();
                    System.out.println("最新APK下载成功!");
                    
                }
            } catch (Exception e) {
                Toast.makeText(getApplicationContext(), "最新APK下载失败!", Toast.LENGTH_LONG).show();
                e.printStackTrace();
            }finally{
                httpClient.getConnectionManager().shutdown();
                try {
                    inputStream.close();
                    outputStream.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        
    }

}

Apk.java中的jsonParseApk()方法中的代码,将更新版本的url中的json数据存入到Apk对象中

public static Apk jsonParseApk(JSONObject jsonObject){
        JSONObject jsonObjectApk=jsonObject.optJSONObject("info");
        String version=jsonObjectApk.optString("version");
        String url=jsonObject.optString("url");
        String createTime=jsonObject.optString("createTime");
        
        return new Apk(version,url,createTime);
    }

对上面的代码进行思路上的说明:首先创建一个IntentService类的子类,在onHandleIntent()方法中(这个方法是在子线程中进行的,所以可以进行耗时操作),

通过intent.getStringExtra(“XXX”)方法,获取到从Activity中传递过来的当前apk的版本,再通过网络请求获取服务器上该apk的最新版本,this.apk=

Apk.jsonParseApk(jsonObject); ,在downLoadApk()方法中进行比较,当服务器上的版本和本地版本不相同时,则开始下载新版本的apk。

原文地址:https://www.cnblogs.com/wjtaigwh/p/4918333.html