Developing Android apps in C/D + +

Source: Internet
Author: User

In some cases, such as the original and many C + + code, you might want to write an Android application in C + +. In this case, the NDK is generally used. But since Android provides the Java interface directly, Therefore, it is not possible to directly invoke various objects or parts of Android. How do I develop an Android app directly from C + +? You can use CLE and wrapandroid projects as middleware. The CLE project provides a common interface for multiple languages, which includes support for C + + +.


This article briefly describes how to write GUI applications using CLE and Wrapandroid. CLE can be used as a universal platform for multiple languages, supports Java, Python,c/c++,lua, etc., and can be extended to many other languages, as well as custom languages. In CLE, the object acts as a 1 basic operation element. Objects provide a unified interface through which you can invoke the object's functions, overload the object's functions, and capture the object's events.
Wrapandroid encapsulates the Android class as a CLE object, allowing programmers to use Android classes in C + +.    Generally there are several steps: 1.    Use the CLE interface function Mallocobjectl to create an instance object 2 of the Android class.   Use the Scriptcall interface function to call Method 3 of the object.    Functions that use Createovlfunction to overload an object 4. Event handlers for registering objects with Regeventfunction
Step 1: Prepare the Environment a:cle can be installed automatically when the application starts, only need to include Starcore_android_r6.jar in the project, the file in the Starcore_devfiles_r6.zip compressed package, can be from the link:/http Code.google.com/p/cle-for-android download.

B:wrapandroid is a jar library that can be downloaded from Http:/code.google.com/p/wrapandroid-for-multilaguage/download/wrapandroid_devfiles_0_8_5.rar.
Step 2: Start programming
Development tools use Eclipse and NDK. See the related documentation for both how to install and use.
A. Open eclipse, create a new project, named "Introduction"

B. CLE can be downloaded from the network when the app is launched, and the following licenses need to be added to the project:

<uses-permission android:name= "Android.permission.INTERNET"/> <uses-permission android:name= " Android.permission.WRITE_EXTERNAL_STORAGE "></uses-permission>

C. Copy the Java library files Starcore_android_r6.jar and Wrapandroid.jar to the project catalog and add them to the project:



D. Edit Introductionactivity.java, modify as follows, load shared library
Import com.srplab.wrapandroid.*;
public class Introductionactivity extends Wrapandroidactivity {/** Called when the activity is first created. */@O        Verride public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.main);    Staractivity._call ("Dofile", "" ","/data/data/"+getpackagename () +"/lib/libcode.so "); }}
E CLE can also be packaged in a project, where the CLE shared library file needs to be placed in the project directory, as follows:

Also, set the download flag to False
public class Introductionactivity extends Wrapandroidactivity {/** Called when the activity is first created. */@O        Verride public void OnCreate (Bundle savedinstancestate) {Downloadfromnetflag = false;        Super.oncreate (savedinstancestate);        Setcontentview (R.layout.main);    Staractivity._call ("Dofile", "" ","/data/data/"+getpackagename () +"/lib/libcode.so "); }}
F. Edit the layout file: Main.xml.
<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "android:id=" @+id/widget73 "android:layout_width=" fill_parent "android:layout_height=" Fill_parent "and roid:orientation= "Vertical" >
<textview android:id= "@+id/widget45" android:layout_width= "fill_parent" android:layout_height= "Wra P_content "android:text=" @string/hello "/> <button android:id=" @+id/widget74 "android:layou T_width= "220DP" android:layout_height= "48DP" android:text= "Thank for your use" android:typeface= "seri F "android:textstyle=" bold "android:textcolor=" #ffff0000 "android:layout_x=" 284DP "Android:lay Out_y= "220DP" android:textsize= "16DP"/> </LinearLayout>
G. Under the Engineering directory, create a JNI directory and copy the Wrap Android and CLE header files to the directory. Create a new file code.cpp. and android.mk, edit android.mk:
Local_path: = $ (call My-dir) include $ (clear_vars)
# Here we give our module name and SourceFile (s) local_cflags + =-wno-write-strings-denv_androidlocal_cppflags + =-wno-wri Te-strings-fexceptions-denv_androidlocal_ldflags + =-wno-write-strings-denv_android
Local_c_includes + = Cle_files/include
#--------Source Filemodule_cxxsrcs: = Code.cpp srpwrapandroidengine_uuiddef.cpp
Local_src_files: = ${module_cxxsrcs}local_ldlibs: = CLE_FILES/LIBS/ARMEABI/LIBSTARLIB.A
Local_module: = Code
Include $ (build_shared_library)

#------------------------include $ (clear_vars)
Local_src_files: = cle_files/so/armeabi/libstarcore.solocal_module: = Starcore
Include $ (prebuilt_shared_library)
#------------------------include $ (clear_vars)
Local_src_files: = cle_files/so/armeabi/libstar_java.solocal_module: = Star_java
Include $ (prebuilt_shared_library)
Step 3. Code.cpp uses native code to write Android apps that need to be compiled into a shared library. Shared library output Two interface functions: Vs_bool Starcoreservice_init (class Classofstarcore *starcore) void Starcoreservice_term (class Classofstarcore *starcore)
The first function is called when the shared library is loaded and can be initialized, and the second function is called when the shared library is unloaded.
The code is as follows://--wrap Android Header file#include "Srpwrapandroidengine_vsclass.h"
//--The Service interface, all other functions are called through the interface.Static class Classofsrpinterface *srpinterface;//--android Activity object, created by Java code.static void *staractivity;
the event function for the//--button. The processing prototypes for the event functions are the same.Static Vs_int32 Mybutton_onclick (Vs_ulong functionchoice,void *eventpara) {//--When an event is triggered, some information is displayed.//--Create a Toast object. void *toast = Srpinterface->mallocobjectl (&vsobjid_toastclass,0,null);//--Call Toast's function "Maketext", (SI) is the type of input parameter, detailed explanation needs to refer to CLE documentation.Srpinterface-Scriptcall (Toast,null, "Maketext", "(SI)", "button is click", 0);//--Call Toast's function "show"Srpinterface-Scriptcall (Toast,null, "Show", "()"); return 0;}
Static Vs_int32 Mybutton1_onclick (Vs_ulong functionchoice,void *eventpara) {void *toast = Srpinterface->mallocobjec    TL (&vsobjid_toastclass,0,null);    Srpinterface-Scriptcall (Toast,null, "Maketext", "(SI)", "button is click", 0);        Srpinterface-Scriptcall (Toast,null, "Show", "()"); return 0;}

//--initialization functions for shared librariesVs_bool Starcoreservice_init (class Classofstarcore *starcore) {class Classofbasicsrpinterface *BasicSRPInterface;//--getting the basic service interfaceBasicsrpinterface = Starcore->getbasicinterface ();//---Get the current service interface, the service is created by Java codeSrpinterface = Basicsrpinterface->getsrpinterface (Basicsrpinterface->queryactiveservice (NULL), "", ""); void *activityclass;//---Get the encapsulated acvitity classActivityclass = Srpinterface, Getobjectex (NULL, "Activityclass");//--invokes the GetCurrent function to get the current activity, created by Java code. () O indicates that the return value is a CLE objectStaractivity = (void *) Srpinterface, Scriptcall (Activityclass,null, "GetCurrent", "() O");//--Print Some information and the printed information is displayed in Logcat.Srpinterface, Print ("Get Main Activity =%s", Srpinterface-GetName (staractivity));//--invokes the activity's function getresource gets the ID of the resource defined in the layout. The input parameter is a string, the output is an integer, and the token is (s) I.int widget45 = Srpinterface, Scriptcall (Staractivity,null, "GetResource", "(s) i", "id/widget45");//--calls the Findviewbyid function to get the TextView. The function is slightly different from the Android function prototype, and the name of the class added in the input parameter. void *mytext = (void *) Srpinterface-Scriptcall (Staractivity,null, "Findviewbyid", "(SI) o", "Textviewclass", WIDGET45);//--calls TextView's function SetText. Srpinterface-Scriptcall (Mytext,null, "SetText", "(s)", "Textviewclass", "from layout");
int widget74 = Srpinterface, Scriptcall (Staractivity,null, "GetResource", "(s) i", "id/widget74");//--Call Findviewbyid Get button Objectvoid *mybutton = (void *) Srpinterface-Scriptcall (Staractivity,null, "Findviewbyid", "(SI) o", "Buttonclass", WIDGET74);//--invokes the SetText of the button object.Srpinterface-Scriptcall (Mybutton,null, "SetText", "(s)", "click Me");//--The function Setonclicklistener that invokes the button object.Srpinterface-Scriptcall (Mybutton,null, "Setonclicklistener", "()");//--handling functions for registering eventsSrpinterface-Regeventfunction (Mybutton,&vsouteventid_viewclass_onclick,mybutton, (void *) MyButton_            onclick,0); int widget73 = Srpinterface, Scriptcall (Staractivity,null, "GetResource", "(s) i", "id/widget73");//--calls Findviewbyid to get linearlayout.void *mylinearlayout = (void *) Srpinterface-Scriptcall (Staractivity,null, "Findviewbyid", "(SI) o", " Linearlayoutclass ", widget73);//--dynamically creates a button object, which is a child of LinearLayoutvoid *mydynabutton = Srpinterface->mallocobject (mylinearlayout,vsattrindex_viewgroupclass_viewqueue,&        Vsobjid_buttonclass,0,null);        Srpinterface-Scriptcall (Mydynabutton,null, "SetText", "(s)", "created dynamically");        Srpinterface-Scriptcall (Mydynabutton,null, "Setonclicklistener", "()"); Srpinterface-Regeventfunction (Mydynabutton,&vsouteventid_viewclass_onclick,mydynabutton, (void *) mybutton1_onclick,0);//--Setting Layout parametersSrpinterface-Scriptcall (Mydynabutton,null, "Setlinearlayoutparams", "(ii)", 100,50);
return vs_true;}
void Starcoreservice_term (class Classofstarcore *starcore) {srpinterface-so Release (); return;}

Step 4. Compiling as a shared library using the NDK

Run results



Example Download:

Http://wrapandroid-for-multilanguage.googlecode.com/svn/wiki/examples/c_introduction.zip

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.