安卓端

cocos2dx/platform/android路径下

CCApplication.h:

1 virtual void openURL(const char* pszUrl);

CCApplication.cpp:

1 void CCApplication::openURL(const char*pszUrl)2 {3 JniMethodInfo minfo;4 if (JniHelper::getStaticMethodInfo(minfo, "org/cocos2dx/lib/Cocos2dxActivity", "openURL", "(Ljava/lang/String;)V"))5 {6 jstring StringArg1 = minfo.env->NewStringUTF(pszUrl);7 minfo.env->CallStaticVoidMethod(minfo.classID, minfo.methodID, StringArg1);8 minfo.env->DeleteLocalRef(StringArg1);9 minfo.env->DeleteLocalRef(minfo.classID);10 }11 }

cocos2dx/platform/android/java/src/org/cocos2dx/lib路径下

Cocos2dxActivity.java:

1 public static voidopenURL(String url)2 {3 try{4 Uri uri =Uri.parse(url);5 Intent it = newIntent(Intent.ACTION_VIEW, uri);6 sContext.startActivity(it);7 }8 catch(Exception e) {9 e.printStackTrace();10 }11 }

注意点:  1.参数url必须以http://或https://开头,不然会有android.content.ActivityNotFoundException(startWith...)

2.try catch包一下,避免直接崩出去

ios端

cocos2dx/platform/ios路径下

CCApplication.h:

1 virtual void openURL(const char* pszUrl);

CCApplication.mm:

1 void CCApplication::openURL(const char*pszUrl)2 {3 NSString *msg =[NSString stringWithCString:pszUrl encoding:NSASCIIStringEncoding];4 NSURL * nsUrl =[NSURL URLWithString:msg];5 [[UIApplication sharedApplication] openURL:nsUrl];6 }

P.S. NativeTools里有一个实现也可以直接用

要在lua层使用,所以在tools/tolua++路径下

CCApplication.pkg里添加:

1 void openURL(const char* pszUrl);

build之后会修改LuaCocos2d.cpp文件。

使用前还是点操作符先判断下:

1 local functionopenUrlWithDefaultBrowser( addr )2 if EDFLAGIOS or EDFLAGANDROID then

3 if CCApplication.openURL then

4 CCApplication:sharedApplication():openURL("http://www.baidu.com")5 end

6 end

7 end

8 ed.openUrlWithDefaultBrowser = openUrlWithDefaultBrowser

Reference:

https://github.com/cocos2d/cocos2d-x/pull/1940/files

Logo

开源鸿蒙跨平台开发社区汇聚开发者与厂商,共建“一次开发,多端部署”的开源生态,致力于降低跨端开发门槛,推动万物智联创新。

更多推荐