玩家一启动游戏时,将客户端资源的版本与服务器进行比对,如果客户端版本低于服务端版本,则下载最新的资源,并将客户端的资源版本更新至服务端的版本。由于我们没有对打包出来的APK中的资源有写的权限,所以我们需要将下载下来的资源放在一个可以读写的路径中,并添加这个路径至搜索路径,且优先级要高于默认的搜索路径。
在3.10 官方例子中,cocos使用了AssetsManagerEx 来代替原先的AssetsManager来实现热更新。 使用AssetsManagerEx只需配置一个Manifest文件即可。
Manifest文件中主要包含:下载资源包路径、远程Manifest配置文件路径、远程版本号路径,当前版本号。
以下是Manifest文件的格式
{
"packageUrl" : "http://180.150.177.134/download/Parkour/",
"remoteManifestUrl" : "http://180.150.177.134/download/Parkour/Manifest/project.manifest",
"remoteVersionUrl" : "http://180.150.177.134/download/Parkour/version.manifest",
"version" : "1.0.0",
"engineVersion" : "3.0 beta",
"assets" : {
"Images/background.png" : {
"md5" : "..."
}
},
"searchPaths" : [
]
}
好了,废话了一大堆,接下来让我们来看代码的实现。
我们只需要一个Update来就可以实现了
Update.h如下
#ifndef __Update_H__
#define __Update_H__
#include "cocos2d.h"
#include "cocos-ext.h"
class Update : public cocos2d::Scene
{
public:
static Update* create(int testIndex); //根据下标设置不同的配置文件与存储路径
Update(int testIndex);
void startDownloadCallback(cocos2d::Ref* sender); // 按下开始下载时的操作
virtual bool init() override;
private:
int _testIndex;
cocos2d::Layer* _loadLayer;
cocos2d::Menu* _downloadMenu;
cocos2d::extension::AssetsManagerEx* _am;
cocos2d::Label* _progress;
cocos2d::extension::EventListenerAssetsManagerEx* _amListener;
void onLoadEnd(); // 下载结束后
};
#endif
Update.cpp如下
#include "Update.h"
USING_NS_CC;
USING_NS_CC_EXT;
const char* sceneManifests[] = { "AMTestScene1/project.manifest", "AMTestScene2/project.manifest", "AMTestScene3/project.manifest" };
const char* storagePaths[] = { "CppTests/AssetsManagerExTest/scene1/", "CppTests/AssetsManagerExTest/scene2/", "CppTests/AssetsManagerExTest/scene3" };
const char* backgroundPaths[] = { "Images/assetMgrBackground1.jpg", "Images/assetMgrBackground2.png", "Images/assetMgrBackground3.png" };
Update* Update::create(int testIndex){
auto scene = new (std::nothrow) Update(testIndex);
if (scene && scene->init())
{
scene->autorelease();
}
else
{
delete scene;
scene = nullptr;
}
return scene;
}
Update::Update(int testIndex)
: _testIndex(testIndex)
, _loadLayer(nullptr)
, _downloadMenu(nullptr)
, _progress(nullptr)
{
}
bool Update::init()
{
if (!Scene::init())
{
return false;
}
Size visibleSize = Director::getInstance()->getVisibleSize();
// 创建按钮组件
auto downloadLabel = Label::createWithTTF("Start Download", "fonts/arial.ttf", 16);
auto downloadItem = MenuItemLabel::create(downloadLabel, CC_CALLBACK_1(Update::startDownloadCallback, this));
downloadItem->setPosition(Vec2(visibleSize.width / 2, 100));
_downloadMenu = Menu::create(downloadItem, nullptr);
_downloadMenu->setPosition(Vec2::ZERO);
this->addChild(_downloadMenu, 1);
_loadLayer = Layer::create();
addChild(_loadLayer);
auto sprite = Sprite::create("Images/Icon.png");
_loadLayer->addChild(sprite);
sprite->setPosition(visibleSize.width / 2, visibleSize.height / 2);
TTFConfig config("fonts/tahoma.ttf", 30);
_progress = Label::createWithTTF(config, "0%", TextHAlignment::CENTER);
_progress->setPosition(Vec2(visibleSize.width / 2, (visibleSize.height / 2) + 50));
_loadLayer->addChild(_progress);
// 根据资源配置文件与存储路径,创建AssetsManagerEx
std::string manifestPath = sceneManifests[_testIndex], storagePath = FileUtils::getInstance()->getWritablePath() + storagePaths[_testIndex];
CCLOG("Storage path for this test : %s", storagePath.c_str());
_am = AssetsManagerEx::create(manifestPath, storagePath);
_am->retain();
return true;
}
void Update::onLoadEnd()
{
removeChild(_loadLayer, true);
_loadLayer = nullptr;
}
// 开始下载资源
void Update::startDownloadCallback(Ref* sender)
{
removeChild(_downloadMenu);
_downloadMenu = nullptr;
if (!_am->getLocalManifest()->isLoaded())
{
CCLOG("Fail to update assets, step skipped.");
onLoadEnd();
}
else
{
int testIndex = _testIndex;
_amListener = cocos2d::extension::EventListenerAssetsManagerEx::create(_am, [testIndex, this](EventAssetsManagerEx* event){
static int failCount = 0;
switch (event->getEventCode())
{
case EventAssetsManagerEx::EventCode::ERROR_NO_LOCAL_MANIFEST:
{
CCLOG("No local manifest file found, skip assets update.");
this->onLoadEnd();
}
break;
case EventAssetsManagerEx::EventCode::UPDATE_PROGRESSION:
{
std::string assetId = event->getAssetId();
float percent = event->getPercent();
std::string str;
if (assetId == AssetsManagerEx::VERSION_ID)
{
str = StringUtils::format("Version file: %.2f", percent) + "%";
}
else if (assetId == AssetsManagerEx::MANIFEST_ID)
{
str = StringUtils::format("Manifest file: %.2f", percent) + "%";
}
else
{
str = StringUtils::format("%.2f", percent) + "%";
CCLOG("%.2f Percent", percent);
}
if (this->_progress != nullptr)
this->_progress->setString(str);
}
break;
case EventAssetsManagerEx::EventCode::ERROR_DOWNLOAD_MANIFEST:
case EventAssetsManagerEx::EventCode::ERROR_PARSE_MANIFEST:
{
CCLOG("Fail to download manifest file, update skipped.");
this->onLoadEnd();
}
break;
case EventAssetsManagerEx::EventCode::ALREADY_UP_TO_DATE:
case EventAssetsManagerEx::EventCode::UPDATE_FINISHED:
{
CCLOG("Update finished. %s", event->getMessage().c_str());
this->onLoadEnd();
}
break;
case EventAssetsManagerEx::EventCode::UPDATE_FAILED:
{
CCLOG("Update failed. %s", event->getMessage().c_str());
failCount++;
if (failCount < 5)
{
_am->downloadFailedAssets();
}
else
{
CCLOG("Reach maximum fail count, exit update process");
failCount = 0;
this->onLoadEnd();
}
}
break;
case EventAssetsManagerEx::EventCode::ERROR_UPDATING:
{
CCLOG("Asset %s : %s", event->getAssetId().c_str(), event->getMessage().c_str());
}
break;
case EventAssetsManagerEx::EventCode::ERROR_DECOMPRESS:
{
CCLOG("%s", event->getMessage().c_str());
}
break;
default:
break;
}
});
Director::getInstance()->getEventDispatcher()->addEventListenerWithFixedPriority(_amListener, 1);
_am->update();
}
}
以上就是Update类的所有代码,Update类主要方法只有3个,6个变量。
方法:
startDownloadCallback() 按下开始下载时的操作。
init() 初始化。
onLoadEnd() 下载结束后。
变量:
_testIndex 配置文件与存储路径的下标。
_loadLayer 展示层。
_downloadMenu menu控件。
_am AssetsManagerEx对象。
_progress 显示进度的Label。
_amListener EventListenerAssetsManagerEx对象(创建下载线程在这里面进行)。
实践证明,改热更新只能下载少量的资源,一旦要更新的资源比较大,则很大几率会出现下载超时,导致下载失败。