其他分享
首页 > 其他分享> > Android 工程打包资源文件-OBB文件设置

Android 工程打包资源文件-OBB文件设置

作者:互联网

Android 工程打包资源文件-OBB文件设置

设备/引擎:Mac(11.6)/cocos

开发工具:Android studio(4.1.2)

开发语言:java

开发需求:对工程的资源文件进行打包处理

当工程中的资源文件大于100m时,就不能直接将资源文件,而需要将资源文件打包成OBB文件再进行上传。话不多说,具体步骤如下:

1.在工程的.java中添加以下代码:

public static String FATE_OBB_PATH= "";
public void onCreate(Bundle savedInstanceState) {
    //获取obb 路径
    FATE_OBB_PATH =getVirtualObbFileFullpath() ;//这句需要放在super.onCreate上面
    super.onCreate(savedInstanceState);
    ...
}
//获取访问权限
private void requestPermission(){
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
        if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE)){
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 0);
       }else {
            ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 0);
       }
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    switch (requestCode){
        case 0:
        {
            if (grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                Log.i(TAG,"onRequestPermissionsResult granted");
           }else {
                Log.i(TAG,"onRequestPermissionsResult denied");
           }
        }
            break;
   }
}

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(){
       if (Environment.getExternalStorageState()
                .equals(Environment.MEDIA_MOUNTED)) {
            File sdcardDir = Environment.getExternalStorageDirectory();
           String _path = getObbDir().getAbsolutePath() + "/" + getObbFileName();
//        String _path = sdcardDir+"/Android/obb/"+getPackageName()+"/"+ getObbFileName();
           Log.e("===_path===", _path);
           File f=new File(getObbDir().getAbsolutePath() + "/");
//          File f=new File(strFile);
           if(!f.exists())
//          if(!f.canRead())
           {
               boolean isMkdir = f.mkdir();
                if (isMkdir){
                   return _path;
               }else {
                   return null;
               }
//             return false;
           }

           return _path;
       }else {
           return null;
       }
    }

2.在Cocos2dxHelper.java中修改代码如下:

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 方法是需要新添加的 下方会介绍
            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();
        //设置压缩包
        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--------------------添加代码----------------------------
       
        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 设置obb路径方法
    private static native void nativeSetObbPath(final String pObbPath);

3.在Cocos2dxMusic.java和Cocos2dxSound.java代码修改,用来查找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;
//添加设置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 下添加一个 obb zip包解析
static ZipFile *s_pZipFileobb = NULL;

//在sharedFileUtils() 中创建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();
        //  创建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;
}

7.在Cocos2dxActivity中修改代码,目的是只有用户点击允许访问存储后才会进入游戏:
(1):在onCreate()中的代码:

		super.onCreate(savedInstanceState);
		instance = this;
    	this.mHandler = new Cocos2dxHandler(this);
    	this.init();

修改为:

		super.onCreate(savedInstanceState);
		sContext = this;
		instance = this;
    	this.mHandler = new Cocos2dxHandler(this);

		if (ContextCompat.checkSelfPermission(JoyPreschool.getContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
		}else {
			this.init();
			Cocos2dxHelper.init(this, this);
		}

(2):在onResume()、onPause()中的代码:

		super.onResume();
		Cocos2dxHelper.onResume();
		this.mGLSurfaceView.onResume();
		super.onPause();
		Cocos2dxHelper.onPause();
		this.mGLSurfaceView.onPause();

修改为:

		super.onResume();
		Cocos2dxHelper.onResume();
		if (this.mGLSurfaceView != null){
			this.mGLSurfaceView.onResume();
		}
		super.onPause();
		Cocos2dxHelper.onPause();
		if (this.mGLSurfaceView != null){
			this.mGLSurfaceView.onPause();
		}

8.在AndroidMenifest.xml中添加权限:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

9.用WinRAR将工程的资源文件-assets文件夹压缩,压缩方式为存储(Store),压缩文件格式为zip;

10.将压缩后的文件重新命名,obb文件名为main.版本号.包名.obb,例如版本号为10,包名为com.jpt.game,文件名为main.10.com.jpt.game.obb;

至此有关打包OBB文件的设置全部完成。

希望能给大家带来帮助!!!有什么问题可以评论私信咨询了解~

标签:文件,return,Cocos2dxHelper,OBB,obb,添加,new,Android,String
来源: https://blog.csdn.net/weixin_44309889/article/details/121922471