COCOS2D-X3.3RC0 loading Android WebView

Source: Internet
Author: User

Code section excerpt from http://www.fusijie.com/blog/2013/12/26/play-cocos2dx-33/

COCOS2D-X3.3RC0 is embedded in the Android WebView space via JNI and displays the Web page in Cocos2d-x. directly on the code.

1. Java Layer Code

Use ADT to open the Appactivity.java under the Org.cocos2dx.cpp directory in the proj.android Project catalog src directory. Add the following code:

Appactivity.java/****************************************************************************copyright (c) 2008-2010 Ricardo Quesadacopyright (c) 2010-2012 Cocos2d-x.orgcopyright (c) Zynga Inc.copyright (c) 2013-2014 Ch Ukong Technologies Inc. http://www.cocos2d-x.orgPermission is hereby granted, free of charge, to any person obtaining a CO Pyof This software and associated documentation files (the "Software"), to dealin the software without restriction, includ ing without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Ftware, and to permit persons to whom the software isfurnished to doing so, subject to the following conditions:the above cop Yright Notice and this permission notice shall be included inall copies or substantial portions of the software.the Softwa RE is provided ' as is ', without WARRANTY of any KIND, EXPRESS orimplied, including and not LIMITED to the warranties of ME Rchantability,fitness for A ParticulaR PURPOSE and Noninfringement.  In NO EVENT shall theauthors or COPYRIGHT holders is liable for any CLAIM, damages OR otherliability, WHETHER in an ACTION  of contract, TORT or OTHERWISE, arising from,out of or in CONNECTION with the software or the use or other dealings inthe Software.****************************************************************************/package Org.cocos2dx.cpp; Import Org.cocos2dx.lib.cocos2dxactivity;import Android.os.bundle;import Android.view.gravity;import Android.view.keyevent;import Android.view.view;import Android.view.view.onclicklistener;import Android.webkit.webview;import Android.webkit.webviewclient;import Android.widget.button;import Android.widget.framelayout;import Android.widget.imageview;import Android.widget.linearlayout;import Com.pactera.webview.r;public class Appactivity extends cocos2dxactivity {static appactivity test = null;// appactivity instance WebView m_webview;//webview control ImageView m_imageview;//imageview control Framelayout m_weblayout;// Framelayout clothBureau linearlayout m_toplayout;//linearlayout Layout button m_backbutton;//return close button @overrideprotected void OnCreate (Bundle Savedinstancestate) {//TODO auto-generated method Stubsuper.oncreate (savedinstancestate); test = This;m_weblayout = new Framelayout (this);//new layout Framelayout.layoutparams LYTP = new Framelayout.layoutparams (640,1000);//Layout size lytp.gravity = gravity.center;//layout of Typeaddcontentview (M_weblayout, LYTP);//join contentview}//initialize activitypublic static AppActivity GetInstance () {return test;} Show webviewpublic void Openwebview () {This.runonuithread (new Runnable () {///on Main Line bunch load control @overridepublic void Run () {//TODO Auto-generated method stub//Initialization Webviewm_webview = new WebView (test);//Set WebView can execute JS script m_webview.getsettings (). Setjavascriptenabled (TRUE);//Set the Zoom tool M_webview.getsettings (). Setsupportzoom (True); M_webview.getsettings (). Setbuiltinzoomcontrols (TRUE);//Load Urlm_webview.loadurl ("http://www.baidu.com/");//Make the page focus M_webview.requestfocus ()//If there is a link in the page that causes the link to respond to m_webview.setwebviewclient in the current browser (new WebviewclieNT () {@Overridepublic Boolean shouldoverrideurlloading (WebView view,string URL) {//TODO auto-generated method Stubif ( Url.indexof ("Tel:") <0) {view.loadurl (URL);} return true;}); /Background M_imageview = new ImageView (test); M_imageview.setimageresource (r.drawable.bg); M_imageview.setscaletype ( ImageView.ScaleType.FIT_XY);//Initialize linear layout, add button webview control m_toplayout = new LinearLayout (test); m_ Toplayout.setorientation (linearlayout.vertical);//Initialize the return button M_backbutton = New button (test); m_ Backbutton.setbackgroundresource (R.drawable.back); Linearlayout.layoutparams lypt = new Linearlayout.layoutparams (LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT); lypt.gravity = gravity.right;//Set Layout type M_backbutton.setlayoutparams (lypt) ///Set button relative layout position, right M_backbutton.setonclicklistener (new Onclicklistener () {@Override//button Click Response Event, delete webviewpublic void OnClick (View arg0) {//TODO auto-generated method Stubremovewebview ();//Definition}}); M_weblayout.addview (M_imageview);// Add image to the main layout M_toplayout.addview (M_bacKbutton);//The Linear layout M_toplayout.addview (M_webview) to which the return button is added;//Add M_webview to the linear layout m_weblayout.addview (m_toplayout);// To add a linear layout to the main layout});} public void Removewebview () {//delete M_imageviewm_weblayout.removeview (M_imageview); M_imageview.destroydrawingcache () ;//delete M_toplayoutm_weblayout.removeview (m_toplayout); M_toplayout.destroydrawingcache ();//Delete m_webviewm_ Toplayout.removeview (M_webview); M_webview.destroy ();//delete M_backbuttonm_toplayout.removeview (M_backButton); m_ Backbutton.destroydrawingcache ();} public boolean onKeyDown (int keycoder,keyevent event) {//If the page can go back, the Web page backs up, otherwise delete webviewif (M_webview.cangoback () & & keycoder = = Keyevent.keycode_back) {m_webview.goback ();} Else{removewebview ();} return false;}}

2. JNI Layer CodeCreate a new Cocos2d-x-based class test under the Jni/hellocpp directory and add the following code:

Test.h#ifndef test_h_#define Test_h_extern "C" {void Showweb ();}/* Namespace cocos2d */#endif//Test_h_ */


/* * test.cpp * *  Created on:2014-11-5 * author:chen * *      #include "test.h" #include "cocos2d.h" #include "platform/a Ndroid/jni/jnihelper.h "#include <jni.h> #define Class_nameroot" org/cocos2dx/cpp/appactivity "USING_NS_CC; extern "C" {void Showweb () {Jnimethodinfo t;//determines whether a showtipdialog function exists in the Class_name class and is called if it exists. if (Jnihelper::getstaticmethodinfo (T,class_nameroot, "getinstance", "() lorg/cocos2dx/cpp/appactivity;")) {jobject jobj;//storage object jobj = T.env->callstaticobjectmethod (t.classid,t.methodid); bool Ishave = JniHelper:: Getmethodinfo (T,class_nameroot, "Openwebview", "() V"), if (Ishave) {T.env->callvoidmethod (Jobj,t.methodid);}}}
3. C + + Layer codeAdd the following code to the header file in HelloWorldScene.cpp in the classes directory
#if (Cc_target_platform = = cc_platform_android) #include ". /proj.android/jni/hellocpp/test.h "#endif
InAdd the following code to the Menuclosecallback:

void Helloworld::menuclosecallback (ref* psender) {#if (Cc_target_platform = = cc_platform_android) ShowWeb (); #endif}

At this point, you can implement the Click button to load the Android WebView control. However, there is still some work to be done, that is, the Mk file,

in the local_src_files Add the newly created Test.cpp file. as follows:

Local_path: = $ (call My-dir) include $ (clear_vars) $ (call import-add-path,$ (Local_path)/. /.. /COCOS2D) $ (call import-add-path,$ (Local_path)/... /.. /cocos2d/external) $ (call import-add-path,$ (Local_path)/... /.. /cocos2d/cocos) Local_module: = cocos2dcpp_sharedlocal_module_filename: = libcocos2dcpplocal_src_files: = hellocpp/ Main.cpp    hellocpp/test.cpp                    . /.. /classes/appdelegate.cpp.                    /.. /classes/helloworldscene.cpplocal_c_includes: = $ (Local_path)/. /.. /classeslocal_static_libraries: = Cocos2dx_staticinclude $ (build_shared_library) $ (call Import-module,.)
Some projects may need to add permissions to the network in Androidmanifest, as follows:
<uses-permission android:name= "Android.permission.INTERNET"/>

4. Compile and run

COCOS2D-X3.3RC0 loading Android WebView

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.