第十六节(增量更新)

一点问题

6.0以上读写权限需要动态申请,但是AndroidManifest.xml文件中也必须写,要不然申请权限会报错。

增量更新

一般我们增量更新的使用方法是:

1.服务器生成差分包
2.客户端下载差分包
3.客户端进行差分包与旧版apk合并
4.提醒用户安装合并完成的新版apk

旧版apk路径:

image.png

开始写代码:

1.Binary diff/patch utility

http://www.daemonology.net/bsdiff/
点击here开始下载bsdiff-4.3.tar.gz

image.png

解压:

image.png

由于只在手机端做合并,所以拷贝bspatch.c到androidstudio的cpp目录下

2.下载bzip2

http://www.bzip.org/downloads.html
下载bzip2-1.0.6.tar.gz,解压:

image.png

有很多......,我们拷贝其中以.c和.h结尾的文件到cpp文件下

3.

拷贝完成后,大概是这个样子,拷贝完成后只发现了一个错

将#include <bzlib.h>改为#include "bzlib.h"就可以了
image.png
4.修改CMakeList.txt


cmake_minimum_required(VERSION 3.4.1)



#添加多个目录的思路 指定一个变量 添加的时候使用变量值(my_c_path)
file(GLOB my_c_path src/main/cpp/*.c)

add_library( # Sets the name of the library.
             patch-lib

             # Sets the library as a shared library.
             SHARED

             # Provides a relative path to your source file(s).
             ${my_c_path}
             )



find_library( # Sets the name of the path variable.
              log-lib

              # Specifies the name of the NDK library that
              # you want CMake to locate.
              log )



target_link_libraries( # Specifies the target library.
                       patch-lib

                       # Links the target library to the log library
                       # included in the NDK.
                       ${log-lib} )

我们将生成的so文件的名字改名为patch-lib,并将所有的.c文件都添加进来。

5.

将所有.c文件中的main函数的名字全部改掉,包括bspatch.c中的,
在MainActivity中写个native方法直接调用bspatch.c中修改后的main方法。
在MainActivity中添加本地方法:

 public native int patch(String oldPath,String newPath,String diffPath);

在bspatch.c中填写对应的jni方法:

JNIEXPORT jint JNICALL
Java_com_example_huozhenpeng_diffandpatch_MainActivity_patch(JNIEnv *env, jobject instance,
                                                             jstring oldPath_, jstring newPath_,
                                                             jstring diffPath_) {
    int ret=-1;
    const char *oldPath = (*env)->GetStringUTFChars(env, oldPath_, 0);
    const char *newPath = (*env)->GetStringUTFChars(env, newPath_, 0);
    const char *diffPath = (*env)->GetStringUTFChars(env, diffPath_, 0);

    int argc = 4;
    char *argv[4];

    argv[0] = "miduoPatch";
    argv[1] = oldPath;
    argv[2] = newPath;
    argv[3] = diffPath;

    //如果成功ret等于0
    ret = bspatch_main(argc,argv);


    (*env)->ReleaseStringUTFChars(env, oldPath_, oldPath);
    (*env)->ReleaseStringUTFChars(env, newPath_, newPath);
    (*env)->ReleaseStringUTFChars(env, diffPath_, diffPath);
    return ret;
}
6.
package com.example.huozhenpeng.diffandpatch;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.EventLog;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    private TextView tv_patch;
    private TextView tv_show;
    private TextView tv_getpermission;

    static {
        System.loadLibrary("patch-lib");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv_show = (TextView) findViewById(R.id.sample_text);
        tv_show.setText("旧版本版本应用");
        tv_patch= (TextView) findViewById(R.id.tv_patch);
        tv_patch.setOnClickListener(this);
        tv_getpermission= (TextView) findViewById(R.id.tv_getpermission);
        tv_getpermission.setOnClickListener(this);


    }


    public  int getVersionCode (Context context, String packageName) {
        PackageManager pm = context.getPackageManager();
        try {
            PackageInfo info = pm.getPackageInfo(packageName, 0);
            return info.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 获取已安装apk文件的原apk文件
     * 如:/data/app/_.apk
     *
     * @param context
     * @param packageName
     * @return
     */
    public static String getSourceApkPath(Context context, String packageName) {
        if (TextUtils.isEmpty(packageName))
            return null;

        try {
            ApplicationInfo appInfo = context.getPackageManager()
                    .getApplicationInfo(packageName, 0);
            return appInfo.sourceDir;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    private Handler handler=new Handler()
    {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what)
            {
                case 0x01:
                    Toast.makeText(MainActivity.this,"合并完成",Toast.LENGTH_LONG).show();
                    installApk(MainActivity.this,newPath);
                    break;
                case 0x02:
                    Toast.makeText(MainActivity.this,"合并失败",Toast.LENGTH_LONG).show();
                    break;
            }
        }
    };

    /**
     * A native method that is implemented by the 'native-lib' native library,
     * which is packaged with this application.
     */
    public native int patch(String oldPath,String newPath,String diffPath);

    private String oldPath;
    private String newPath;
    private String diffPath;
    @Override
    public void onClick(View v) {

        switch (v.getId())
        {
            case R.id.tv_getpermission:
                getPermission();
                break;
            case R.id.tv_patch:
                if(getVersionCode(MainActivity.this,getPackageName().toString())==2)
                {
                    Toast.makeText(MainActivity.this,"已经是最新版",Toast.LENGTH_LONG).show();
                }
                else
                {
                    //获取差分包,合并差分包,我们把差分包放在sd卡下面
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            oldPath=getSourceApkPath(MainActivity.this,getPackageName().toString());
                            newPath= Environment.getExternalStorageDirectory()+ File.separator+"patch.apk";
                            diffPath=Environment.getExternalStorageDirectory()+ File.separator+"diff.patch";
                            int result=patch(oldPath,newPath,diffPath);
                            if(result==0)
                            {
                                handler.sendEmptyMessage(0x01);

                            }
                            else
                            {
                                handler.sendEmptyMessage(0x02);
                            }

                        }
                    }).start();
                }
                break;

        }
    }

    /**
     * 安装Apk
     *
     * @param context
     * @param apkPath
     */
    public static void installApk(Context context, String apkPath) {

        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.parse("file://" + apkPath),
                "application/vnd.android.package-archive");

        context.startActivity(intent);
    }

    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };
    public void getPermission() {
        int permission = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (permission != PackageManager.PERMISSION_GRANTED) {
            // We don't have permission so prompt the user
            ActivityCompat.requestPermissions(
                    this,
                    PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE
            );
        }
    }
}

测试结果

1.将build.gradle中的versionCode改为2,tv_show设置为“新版本版本应用”appnew.apk。
2.将build.gradle中的versionCode改为1,tv_show设置为“旧版本版本应用”appold.apk。
3.同上节,生成差分文件diff.patch
4.将diff.patch文件放入sd卡

image.png

5.将旧版本应用appold.apk安装到手机上(记住先获取读写权限)

image.png

6.点击合并差分包

可以查看合并后的新包


image.png

合并完成后自动安装:

image.png
image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,122评论 6 505
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,070评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,491评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,636评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,676评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,541评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,292评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,211评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,655评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,846评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,965评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,684评论 5 347
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,295评论 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,894评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,012评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,126评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,914评论 2 355

推荐阅读更多精彩内容