安卓端
cocos2dx/platform/android路径下
CCApplication.h:
virtual void openURL(const char* pszUrl);
CCApplication.cpp:
void CCApplication::openURL(const char* pszUrl)
{
JniMethodInfo minfo;
if (JniHelper::getStaticMethodInfo(minfo, "org/cocos2dx/lib/Cocos2dxActivity", "openURL", "(Ljava/lang/String;)V"))
{
jstring StringArg1 = minfo.env->NewStringUTF(pszUrl);
minfo.env->CallStaticVoidMethod(minfo.classID, minfo.methodID, StringArg1);
minfo.env->DeleteLocalRef(StringArg1);
minfo.env->DeleteLocalRef(minfo.classID);
}
}
cocos2dx/platform/android/java/src/org/cocos2dx/lib路径下
Cocos2dxActivity.java:
public static void openURL(String url)
{
try {
Uri uri = Uri.parse(url);
Intent it = new Intent(Intent.ACTION_VIEW, uri);
sContext.startActivity(it);
}
catch(Exception e) {
e.printStackTrace();
}
}
注意点: 1.参数url必须以http://或https://开头,不然会有android.content.ActivityNotFoundException(startWith...)
2.try catch包一下,避免直接崩出去
ios端
cocos2dx/platform/ios路径下
CCApplication.h:
virtual void openURL(const char* pszUrl);
CCApplication.mm:
void CCApplication::openURL(const char* pszUrl)
{
NSString *msg = [NSString stringWithCString:pszUrl encoding:NSASCIIStringEncoding];
NSURL * nsUrl = [NSURL URLWithString:msg];
[[UIApplication sharedApplication] openURL:nsUrl];
}
P.S. NativeTools里有一个实现也可以直接用
要在lua层使用,所以在tools/tolua++路径下
CCApplication.pkg里添加:
void openURL(const char* pszUrl);
build之后会修改LuaCocos2d.cpp文件。
使用前还是点操作符先判断下:
local function openUrlWithDefaultBrowser( addr )
if EDFLAGIOS or EDFLAGANDROID then
if CCApplication.openURL then
CCApplication:sharedApplication():openURL("http://www.baidu.com")
end
end
end
ed.openUrlWithDefaultBrowser = openUrlWithDefaultBrowser
Reference:
https://github.com/cocos2d/cocos2d-x/pull/1940/files