Android 35: Learn about native activity

Source: Internet
Author: User

The meaning of 1.native activity

Many people think that Android's fwk support is good enough, since Google does not recommend the NDK development why and loosen the NDK restrictions and launch can not Java development Android app? My understanding is that different technology implementations will have a suitable scenario.
The NDK's scenario is officially given three points: 1. App porting between platforms 2. Reusing an existing library 3. For applications where the software performance requirements are high, such as games. Then native activity is well suited for the game field, such as COCOS-2DX's use of it.

2. Preliminary knowledge of native activity

With the Nativeactivity class provided by the SDK, we can create full local activity without having to write Java code.
It is important to note that even applications that are not written in Java are still running (running) in their own virtual machines and are not affected by the isolation of other applications. You can invoke the API of the FWK layer by JNI, some operations like sensor, input event can call the local interface (native interfaces) directly (Linc Note: This is efficient).

There are two ways to achieve native activity.
1) native_activity.h
2) Android_native_app_glue
This implementation is used in the NDK example because the second method enables another thread to handle callbacks and input events.

3.NDK Self-bringing example

This program mainly demonstrates drawing different colors across the screen based on the sensor's detection results.
Androidmanifest.xml
In order to use native activity normally, we need to set the API level at 9 and above.

<uses-sdk android:minSdkVersion="9" />

Since we only use native code, set Android:hascode to False.

<application android:label="@string/app_name" android:hasCode="false">

Declaring the Nativeactivity class

        <activity android:name="android.app.NativeActivity"android:label= "@string/app_name" android:configchanges="Orientation|keyboardhidden">                                            <!--tell nativeactivity the name of or , so-and            <meta-data android:name="Android.app.lib_name"android:value= "native-activity" />                                <intent-filter>                <action android:name="Android.intent.action.MAIN" />                <category android:name="Android.intent.category.LAUNCHER" />            </intent-filter>        </activity>

Note that Lib_name (native-activity) in Meta-data is the same as Local_module in Android.mk.

android.mk
Highlight the module name and source file as follows:

LOCAL_MODULE    := native-activityLOCAL_SRC_FILES := main.c

dependencies of external libraries
Examples include the following external libraries, log, Android (standard Android support API for NDK), EGL (Graphics API), and OpenGL ES (OpenGL for Android, dependent on EGL)
The writing Convention for the above library prefix is-L, as follows:

LOCAL_LDLIBS    :=-llog-landroid-lEGL-lGLESv1_CM

Attention:
The actual library file name convention is a prefix of lib with a suffix of. So. For example, the log library filename is actually liblog.so.
The actual location of these libraries:

<ndk>/platforms/android-<sdk_version>/arch-<abi>/usr/lib /

such as liblog.so:

$ locate Liblog.So/opt/android-NDK-r10b/platforms/android- A/arch-arm/usr/lib/liblog.So/opt/android-NDK-r10b/platforms/android- A/arch-mips/usr/lib/liblog.So/opt/android-NDK-r10b/platforms/android- A/arch-x86/usr/lib/liblog.So/opt/android-NDK-r10b/platforms/android- -/arch-arm/usr/lib/liblog.So...

Static Library
This example uses Android_native_app_glue to manage nativeactivity life cycle events:

LOCAL_STATIC_LIBRARIES := android_native_app_glue

We need to tell the compilation system to build the static library, with the following statement:

$(call import-module,android/native_app_glue)

Source Code
The main source code files are only one, main.c.
The introduced header files correspond to those mentioned in Android.mk, as follows:

#include <EGL/egl.h>#include <GLES/gl.h>#include <android/sensor.h>#include <android/log.h>#include <android_native_app_glue>

The entrance to the program is Android_main, which calls in to the Android_native_app_glue and passes in a predefined state structure to manage nativeactivity callbacks.

void android_main(struct android_app* state)

Definition of structural Android_app see/sources/android/native_app_glue/android_native_app_glue.h

The program then processes the event queue through the glue library, referring to the following code:

    struct engine engine;    // Make sure glue isn‘t stripped.    app_dummy();    memset(&0, sizeof(engine));    state->=&engine;    state->= engine_handle_cmd;    state->= engine_handle_input;    engine.= state;

Prepare the sensor.

    // Prepare to monitor accelerometer    engine.sensorManager = ASensorManager_getInstance();    engine.accelerometerSensor = ASensorManager_getDefaultSensor(engine.sensorManager,            ASENSOR_TYPE_ACCELEROMETER);    engine.sensorEventQueue = ASensorManager_createEventQueue(engine.sensorManager,            state->looper, LOOPER_ID_USER, NULL, NULL);

Handling Message Loops

 while(1) {//Read all pending events.        intIdentintEvents struct android_poll_source*Source;//If not animating, we'll block forever waiting for events.        //If animating, we loop until all events is read, then continue        //To draw the next frame of animation.         while(Ident=alooper_pollall (engine.animating?0: -1, Null,&events, (void**) &Source)) >=0) {//Process this event.            if(Source! = NULL) {Source->process (state,Source); }//If a sensor has data, process it now.            if(ident = = Looper_id_user) {if(Engine.accelerometersensor! = NULL) {asensoreventEvent; while(Asensoreventqueue_getevents (Engine.sensoreventqueue, &Event,1) >0) {Logi ("accelerometer:x=%f y=%f z=%f",Event. acceleration.x,Event. ACCELERATION.Y,Event. acceleration.z); }                }            }//Check if we are exiting.        if(state->destroyrequested! =0) {Engine_term_display (&engine);return; }    }

When the queue is empty, the OpenGL draw screen is called

        if (engine.animating) {            //next animation frame.            engine.state.angle += .01f;            if (engine.state1) {                engine.state0;            }            // Drawing is throttled to the screen update rate, so there            nodo timing here.            engine_draw_frame(&engine);        }

compiling
First compile the so file through the NDK and execute the Ndk-build directly in the root directory:

$ ndk-build[armeabi-v7a] Compile thumb  : native-activity <= main.c[armeabi-v7a] Compile thumb  : android_native_app_glue <= android_native_app_glue.c[armeabi-v7a] StaticLibrary  : libandroid_native_app_glue.a[armeabi-v7a] SharedLibrary  : libnative-activity.so[armeabi-v7a] Install        : libnative-activity.so => libs/armeabi-v7a/libnative-activity.so

The above only extracts armeabi-v7a a platform compile log, because in APPLICATION.MK does not specify a specific platform, the compilation system will compile other Armeabi, x86 and MIPS platform so.

And then compile the APK
I tried to import the project into as and found that the Gradle compiled environment could not be configured and could not be compiled.
Then I use ant to compile, and refer to the following steps:

‘NativeActivity‘.If you wish to change it, edit the first line of build.xml.Added file ./build.xmlAdded file ./proguard-project.txt$ ant debug...[echo] Debug Package: /opt/android-ndk-r10b/samples/native-activity/bin/NativeActivity-debug.apk...3 seconds

finally
Install and run it!

adb install /opt/android-ndk-r10b/samples/native-activity/bin/NativeActivity-debug.apk

Reference:
http://blog.csdn.net/lincyang/article/details/40950153

Android 35: Learn about native activity

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.