cocos2dx 實(shí)現(xiàn)obb包讀取 quick2.2.6


實(shí)現(xiàn)方式:

  1. 這個(gè)方案沒有采用google 的jobb 方式打包obb而是通過zip包的方式進(jìn)行打包obb
  2. 在android部分獲取Sound, Music,Video 時(shí)是通過 AssetFileDescriptor 進(jìn)行讀取的所以 通過設(shè)置 android 中的反射 addAssetPath 進(jìn)行添加路徑 下面代碼會(huì)有用到注意查看
  3. cocos 方面修改部分c++ 代碼讓cocos能夠讀取到obb包中的內(nèi)容
  4. obb包直接通過winrar 進(jìn)行打包 這里注意 壓縮時(shí)選擇zip格式,壓縮方式選擇->存儲(chǔ)
    5.https://pan.baidu.com/s/1i507k5f zip讀取類 google 官方庫(kù)

obb打包方式

打包完畢文件后綴名 zip 修改obb (obb 命名方式 mian.versionCode.packageName.obb 注意:assets目錄為根目錄)


以下為代碼實(shí)現(xiàn) 不要直接復(fù)制只是把需要修改的地方進(jìn)行說明 根據(jù)自己情況進(jìn)行修改

當(dāng)前使用版本為2.x

3.x版本的應(yīng)該大同小異自己修改下對(duì)應(yīng)的地方就行了

1.獲取obb包路徑在項(xiàng)目的 MainActivity.java(這個(gè)文件可能名字不一樣 繼承于 Cocos2dxActivity)


public static String FATE_OBB_PATH= "";
public void onCreate(Bundle savedInstanceState) {
    //獲取obb 路徑
    FATE_OBB_PATH =getVirtualObbFileFullpath() ;//這句需要放在super.onCreate上面
    super.onCreate(savedInstanceState);
    ...
}

public String getObbFileName() {  
    PackageInfo info = null;  
    try {
        info = super.getPackageManager().getPackageInfo(super.getPackageName(), 0);
        String fileName = "main." + info.versionCode + "." + getPackageName() + ".obb";
        
        return fileName;
} catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }
    return "";
}
public String getVirtualObbFileFullpath(){
    File sdcardDir = Environment.getExternalStorageDirectory();
    String _path = getObbDir().getPath() + "/" + getObbFileName();
    Log.e("===_path===", _path);
    return _path;
}

2. Cocos2dxHelper 代碼修改


    public static ZipResourceFile obbzip = null;

    public static void init(final Context pContext, final Cocos2dxHelperListener pCocos2dxHelperListener) {
        ...
        // begin--------------------添加代碼----------------------------
        //檢查obb文件是否存在
        if(fileIsExists(MainActivity.FATE_OBB_PATH)){
            //存在添加obb路徑到cocos中 注意 nativeSetObbPath 方法是需要新添加的 下方會(huì)介紹
            Cocos2dxHelper.nativeSetObbPath(MainActivity.FATE_OBB_PATH);
        }
        // end--------------------添加代碼----------------------------

        Cocos2dxHelper.nativeSetApkPath(applicationInfo.sourceDir);
        Cocos2dxHelper.sCocos2dxAccelerometer = new Cocos2dxAccelerometer(pContext);
        Cocos2dxHelper.sCocos2dMusic = new Cocos2dxMusic(pContext);
        int simultaneousStreams = Cocos2dxSound.MAX_SIMULTANEOUS_STREAMS_DEFAULT;
        if (Cocos2dxHelper.getDeviceModel().indexOf("GT-I9100") != -1) {
            simultaneousStreams = Cocos2dxSound.MAX_SIMULTANEOUS_STREAMS_I9100;
        }
        Cocos2dxHelper.sCocos2dSound = new Cocos2dxSound(pContext, simultaneousStreams);
        Cocos2dxHelper.sAssetManager = pContext.getAssets();
        //設(shè)置壓縮包
        PackageInfo info = null;
        try {
            info = pContext.getPackageManager().getPackageInfo(pContext.getPackageName(), 0);
            Cocos2dxHelper.obbzip = APKExpansionSupport.getAPKExpansionZipFile(pContext,info.versionCode,0);
        } catch (PackageManager.NameNotFoundException e1) {
            e1.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        // end--------------------添加代碼----------------------------
        PSNetwork.init(pContext);
        Cocos2dxBitmap.setContext(pContext);
        Cocos2dxETCLoader.setContext(pContext);
    }
    //檢查obb文件是否存在
    public static boolean fileIsExists(String strFile)
    {
        try
        {
            File f=new File(strFile);
            if(!f.exists())
            {
                return false;
            }

        }
        catch (Exception e)
        {
            return false;
        }

        return true;
    }

    private static native void nativeSetApkPath(final String pApkPath);
    //nativeSetObbPath 設(shè)置obb路徑方法
    private static native void nativeSetObbPath(final String pObbPath);

3. 修改 Cocos2dxMusic.java 和 Cocos2dxSound.java 將獲得AssetFileDescriptor的地方加入obb包查找


//Cocos2dxMusic.java
final AssetFileDescriptor assetFileDescritor =  Cocos2dxHelper.obbzip.getAssetFileDescriptor("assets/"+pPath);
if(assetFileDescritor == null) {
    final AssetFileDescriptor assetFileDescritor1 = this.mContext.getAssets().openFd(pPath);
    mediaPlayer.setDataSource(assetFileDescritor1.getFileDescriptor(), assetFileDescritor1.getStartOffset(), assetFileDescritor1.getLength());
}else{
    mediaPlayer.setDataSource(assetFileDescritor.getFileDescriptor(), assetFileDescritor.getStartOffset(), assetFileDescritor.getLength());
}
//Cocos2dxSound.java
final AssetFileDescriptor assetFileDescritor =  Cocos2dxHelper.obbzip.getAssetFileDescriptor("assets/"+pPath);
if(assetFileDescritor == null) {
    final AssetFileDescriptor assetFileDescritor1 = this.mContext.getAssets().openFd(pPath);
    soundID = this.mSoundPool.load(assetFileDescritor1, 0);
}else{
    soundID = this.mSoundPool.load(assetFileDescritor, 0);

}

4. 修改 Java_org_cocos2dx_lib_Cocos2dxHelper.cpp


string g_apkPath;
//添加obb path
string g_obbPath;
//添加設(shè)置obbpath 方法
 JNIEXPORT void JNICALL Java_org_cocos2dx_lib_Cocos2dxHelper_nativeSetObbPath(JNIEnv*  env, jobject thiz, jstring obbPath) {
    g_obbPath = JniHelper::jstring2string(obbPath);
}
//添加獲取obbpath 方法
const char * getObbPath() {
    return g_obbPath.c_str();
}

5.修改 CCFileUtilsAndroid.h


//添加方法
extern const char * getObbPath();

6.修改 CCFileUtilsAndroid.cpp


static ZipFile *s_pZipFile = NULL;
//在 s_pZipFile 下添加一個(gè) obb zip包解析
static ZipFile *s_pZipFileobb = NULL;

//在sharedFileUtils() 中創(chuàng)建obb的zip
CCFileUtils* CCFileUtils::sharedFileUtils()
{
    if (s_sharedFileUtils == NULL)
    {
        s_sharedFileUtils = new CCFileUtilsAndroid();
        s_sharedFileUtils->init();
        std::string resourcePath = getApkPath();
        s_pZipFile = new ZipFile(resourcePath, "assets/");
        // begin ------------------代碼添加
        //獲取obb路徑
        std::string resourcePath_Obb = getObbPath();
        //  創(chuàng)建obbzip
        s_pZipFileobb = new ZipFile(resourcePath_Obb,"assets/");
        // end --------------------代碼添加

    }
    return s_sharedFileUtils;
}
CCFileUtilsAndroid::~CCFileUtilsAndroid()
{
    CC_SAFE_DELETE(s_pZipFile);
    //銷毀
    CC_SAFE_DELETE(s_pZipFileobb);
}

//文件檢查中的修改
bool CCFileUtilsAndroid::isFileExist(const std::string& strFilePath)
{
    if (0 == strFilePath.length())
    {
        return false;
    }

    bool bFound = false;
    
    // Check whether file exists in apk.
    if (strFilePath[0] != '/')
    {
        std::string strPath = strFilePath;
        if (strPath.find(m_strDefaultResRootPath) != 0)
        {// Didn't find "assets/" at the beginning of the path, adding it.
            strPath.insert(0, m_strDefaultResRootPath);
        }
        if (s_pZipFile->fileExists(strPath))
        {
            bFound = true;
        } 
        // begin -------------代碼添加
        if(!bFound){
           
            if (s_pZipFileobb->fileExists(strPath))
            {
                
                bFound = true;
            } 
        }
        // end -----------------代碼添加
    }
    else
    {
        FILE *fp = fopen(strFilePath.c_str(), "r");
        if(fp)
        {
            bFound = true;
            fclose(fp);
        }
    }
    return bFound;
}


//文件獲取方法中的代碼修改
unsigned char* CCFileUtilsAndroid::doGetFileData(const char* pszFileName, const char* pszMode, unsigned long * pSize, bool forAsync)
{
    unsigned char * pData = 0;
    
    if ((! pszFileName) || (! pszMode) || 0 == strlen(pszFileName))
    {
        return 0;
    }
    
    string fullPath = fullPathForFilename(pszFileName);
    
    if (fullPath[0] != '/')
    {
        if (forAsync)
        {
            pData = s_pZipFile->getFileData(fullPath.c_str(), pSize, s_pZipFile->_dataThread);
            // begin -------------代碼添加
            if (! pData)
            {
                pData = s_pZipFileobb->getFileData(fullPath.c_str(), pSize, s_pZipFile->_dataThread);
            }
            //end -------------代碼添加
        }
        else
        {
            pData = s_pZipFile->getFileData(fullPath.c_str(), pSize);
            // begin -------------代碼添加
            if (! pData)
            {
                pData = s_pZipFileobb->getFileData(fullPath.c_str(), pSize);
            }
            //end -------------代碼添加
        }
    }
    else
    {
        do
        {
            // read rrom other path than user set it
            //CCLOG("GETTING FILE ABSOLUTE DATA: %s", pszFileName);
            FILE *fp = fopen(fullPath.c_str(), pszMode);
            CC_BREAK_IF(!fp);
            
            unsigned long size;
            fseek(fp,0,SEEK_END);
            size = ftell(fp);
            fseek(fp,0,SEEK_SET);
            pData = new unsigned char[size];
            size = fread(pData,sizeof(unsigned char), size,fp);
            fclose(fp);
            
            if (pSize)
            {
                *pSize = size;
            }
        } while (0);
    }
    
    if (! pData)
    {
        std::string msg = "Get data from file(";
        msg.append(pszFileName).append(") failed!");
        CCLOG("%s", msg.c_str());
    }
    
    return pData;
}

測(cè)試:

  1. Root手機(jī)
  2. 安裝 re文件管理器
  3. re文件管理器
  4. 掛載為可讀寫
  5. 掛載為可讀寫
  6. 上傳obb包
    1. 檢查是否有 對(duì)應(yīng)目錄 /storage/emulated/0/Android/obb/com.k0204.game/ 如果沒有自己創(chuàng)建一下
    2. adb push E:\main.5.com.k0204.game.obb /storage/emulated/0/Android/obb/com.k0204.game/
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容