cocos2dx調用瀏覽器打開網址


安卓端
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 void openURL(String url)
 2 {
 3     try {
 4         Uri uri = Uri.parse(url);
 5         Intent it = new Intent(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 function openUrlWithDefaultBrowser( 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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM