unity实现应用内更新

最新公司项目需要实现游戏内更新,减少玩家跳转步数,研究了下,可以如下实现:

1.设置2个版本号,一个为建议版本,一个为强制版本,玩家客户端必须大于等于强制版本,否则更新,玩家小于建议版本的时候可以跳过不更新.

2.IOS平台无法实现应用内更新,那么就点击跳转到APPStore的本应用页面.

3.安卓下载更新的安装包,并显示下载进度.下载完成后实现自动安装覆盖!

这里我就记录下安卓部分,IOS部分其实就是一个跳转Application.OpenURL(URL)即可

首先就是使用unity 协程的方式下载APK包,并保存,我设定的保存地址为string path = "/storage/emulated/0/" +fileName;

然后下载并保存到本地后开始自动安装:

private void InstallNewApp(string path)
        {
           

#if UNITY_EDITOR || UNITY_STANDALONE || UNITY_IOS
            Debug.Log("APP下载到了:"+ path);
#elif UNITY_ANDROID
             Debug.Log("begin install");

            using (AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
            {

                using (AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject>("currentActivity"))
                {

                    jo.Call("InstallNewApp", jo, path);

                }
            }
#endif 
        }

然后就是在jar包里面实现InstallNewApp方法,不会写jar包的请看我之前的几篇文章.使用ECLIPS打开或者新建同包名的mainActivity,它继承于unity,相当于游戏的主页面,

public class MyMainActivity extends com.unity3d.player.UnityPlayerActivity
{
    @Override
	public void onCreate(Bundle saveInstanceState) {
	super.onCreate(saveInstanceState);

        
        //去除URL错误异常的警告,相当于不再检查URL权限
        if (Build.VERSION.SDK_INT >= 24) 
        { 
        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder(); StrictMode.setVmPolicy(builder.build());

	}
}

以上代码是为了针对安卓7.0后隐私检查报出URL的错误,其强调了APP的数据其他未经授权的APP不能调用.也就是URI不能传file:///出去.然后就是安装APP的代码

//安装APP
	public void InstallNewApp(Context context, String path) {
		System.out.println("准备安装APP:"+path);
				File f=new File(path);
				if(!f.exists()) {
					System.out.println("不存在:"+path);
				}
				Intent intent = new Intent();
				intent.setAction(android.content.Intent.ACTION_VIEW);
				Uri uri;
				uri=Uri.fromFile(f);
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				intent.setDataAndType(uri, "application/vnd.android.package-archive");
				context.startActivity(intent);

	}

然后就可以了!

猜你喜欢

转载自blog.csdn.net/qq_33347809/article/details/83784975