Unity学习笔记

应用内APK升级安装

2019-09-27  本文已影响0人  塘朗山小钻风

游戏为保持玩家粘性升版本时最好能游戏内覆盖安装。而不要给个提示让玩家到应用中心重新下载。

覆盖安装有个好处就是可写目录中的数据还能保留。卸载再安装就没了。

public static void installApk(String localPath)

{

Activity thisActivity = getUnityActivity_();

File apkFile = new File(localPath);

Intent intent = new Intent(Intent.ACTION_VIEW);

intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {

Log.w(TAG, "SDK版本>=24 ,开始使用 fileProvider 进行安装");

Uri contentUri = FileProvider.getUriForFile(

thisActivity,

thisActivity.getPackageName() + ".fileprovider",

apkFile);

thisActivity.grantUriPermission(thisActivity.getPackageName(), contentUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);

intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

intent.setDataAndType(contentUri, "application/vnd.android.package-archive");

} else {

Log.w(TAG, "正常进行安装");

intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");

}

thisActivity.startActivity(intent);

android.os.Process.killProcess(android.os.Process.myPid());

}

还需好在Manifest.xml文件中配置provider

<provider android:name="android.support.v4.content.FileProvider" android:authorities="${applicationId}.fileprovider" android:exported="false" android:grantUriPermissions="true">

<meta-data

android:name="android.support.FILE_PROVIDER_PATHS"

android:readPermission="android.permission.permRead"

            android:writePermission="android.permission.permWrite"

            android:grantUriPermissions="true"

android:resource="@xml/file_paths" />

</provider>

file_paths.xml配置的是访问路径,可以如下配置:

<?xml version="1.0" encoding="utf-8"?>

<paths>

    <external-path name="external_storage_root" path="." />

    <files-path name="files-path" path="." />

    <cache-path name="cache-path" path="." />

    <external-files-path name="external_file_path" path="." />

    <external-cache-path name="external_cache_path" path="." />

    <root-path name="root-path" path="" />

</paths>

应用内下载APK可以通过WWW或UnityWebRequest(Unity官方建议用这个)来下载。

WWW downloader = new WWW(url+"?time="+System.DateTime.Now.Second);// url就是apk下载地址

var oneCentSec = new WaitForSeconds(0.1f);

while (!downloader.isDone && downloader.error == null)

{

yield return oneCentSec;

}

下载好后把APK保存在可写目录中,再调用Java层接口installApk。

但在项目运营时发现偶尔会有下载后发现是个损坏的APK,无法安装,用户体验挺差。

我的解决方案是APK分块下载。在打包出APK后执行一个分块计算MD5值的过程

split -a 2 -b 6m out_name input_apk #会生成out_nameaa out_nameab ...这样的

for part in `ls *.apk??`

do

md5val=`md5 -q $part`

#记录下来

done

把这个计算的值和末尾的aa(对应第一个6M), ab(对应第二个6M)...关联起来记录在更新服上。更新时取下来用于下载时校验。

下载时可以指定分段下载:

var dic = new Dictionary<string, string> { { "Range", "bytes=0-6M减1"} };// 这是伪代码

创建WWW对象改成这样的new WWW(url, null, dic)

下载后校验md5值。如果不等重新下载。下载完后拼接起来再安装。

实践表现非常好。

上一篇 下一篇

猜你喜欢

热点阅读