0%

Android Native开发

Android Native开发

Android 从

0x01 JNI 开发

1. Demo

我们现来看一个例子。

1
2
3
4
5
6
7
public class HelloJni {
static {
System.loadLibrary("native-lib");
}

public static native String stringFromJNI();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <jni.h>
#include <string>

extern "C"
JNIEXPORT jstring JNICALL
Java_cn_cwiki_someapp_test_HelloJni_stringFromJNI(JNIEnv *env, jclass type) {
// TODO
return env->NewStringUTF("Hello, Java Native Interface!");
}
extern "C"
JNIEXPORT jstring JNICALL
Java_cn_cwiki_someapp_test_HelloJni_test(JNIEnv *env, jobject instance) {
// TODO
return env->NewStringUTF("test");
}

image-20190628232500731

1
2
3
4
5
6
7
8
9
cmake_minimum_required(VERSION 3.4.1)
add_library(
native-lib SHARED
src/main/cpp/native-lib.cpp
)
target_link_libraries(
native-lib
src/main/cpp/native-lib.cpp
)
1
2
3
4
5
6
7
8
9
10
android {
...
externalNativeBuild {
cmake {
path "CMakeLists.txt" //CMakeLists.txt的路径
version "3.10.2"
}
}
...
}

image-20190628233820985

1
String stringFromJNI = HelloJni.stringFromJNI();

image-20190628234045501

2. Java Native Interface(Jni):

jni.h

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
typedef uint8_t  jboolean; /* unsigned 8 bits */
typedef int8_t jbyte; /* signed 8 bits */
typedef uint16_t jchar; /* unsigned 16 bits */
typedef int16_t jshort; /* signed 16 bits */
typedef int32_t jint; /* signed 32 bits */
typedef int64_t jlong; /* signed 64 bits */
typedef float jfloat; /* 32-bit IEEE 754 */
typedef double jdouble; /* 64-bit IEEE 754 */

/*
* Reference types, in C.
*/
typedef void* jobject;
typedef jobject jclass;
typedef jobject jstring;
typedef jobject jarray;
typedef jarray jobjectArray;
typedef jarray jbooleanArray;
typedef jarray jbyteArray;
typedef jarray jcharArray;
typedef jarray jshortArray;
typedef jarray jintArray;
typedef jarray jlongArray;
typedef jarray jfloatArray;
typedef jarray jdoubleArray;
typedef jobject jthrowable;
typedef jobject jweak;

#if defined(__cplusplus)
typedef _JNIEnv JNIEnv;
typedef _JavaVM JavaVM;
#else
typedef const struct JNINativeInterface* JNIEnv;
typedef const struct JNIInvokeInterface* JavaVM;
#endif

0x02 NDK 开发

CMake配置:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
cmake_minimum_required(VERSION 3.4.1)
add_library(native_app_glue STATIC
${ANDROID_NDK}/sources/android/native_app_glue/android_native_app_glue.c)
add_library(main SHARED ${CMAKE_SOURCE_DIR}/src/main/cpp/main.cpp)
target_include_directories(main PRIVATE
${ANDROID_NDK}/sources/android/native_app_glue)
target_link_libraries(
main
android
native_app_glue
EGL
GLESv1_CM
log
)

AndroidManifest.xml

1
2
3
4
5
6
7
8
9
10
11
<application android:label="@string/app_name" android:hasCode="false">
<activity android:name="android.app.NativeActivity"
android:label="@string/app_name">
<meta-data android:name="android.app.lib_name"
android:value="main"/>
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>

Main.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/

//BEGIN_INCLUDE(all)
#include <initializer_list>
#include <memory>
#include <cstdlib>
#include <cstring>
#include <jni.h>
#include <errno.h>
#include <cassert>

#include <EGL/egl.h>
#include <GLES/gl.h>

#include <android/sensor.h>
#include <android/log.h>
#include <android_native_app_glue.h>
#include <android/bitmap.h>

#include <GrContext.h>
#include <SkGpuDevice.h>
#include <gl/GrGLInterface.h>

#include <GrContext.h>
#include <SkCanvas.h>
#include <SkGraphics.h>
#include <SkSurface.h>
#include <SkString.h>
#include <SkTime.h>
#import "GrBackendSemaphore.h"
#import <GLES/gl.h>
#include <core/SkExecutor.h>
#include "cpp/skia/WindowContextFactory_android.h"
#include "cpp/skia/Window.h"

#define LOGI(...) ((void)__android_log_print(ANDROID_LOG_INFO, "native-activity", __VA_ARGS__))
#define LOGW(...) ((void)__android_log_print(ANDROID_LOG_WARN, "native-activity", __VA_ARGS__))

/**
* Our saved state data.
*/
struct saved_state {
float angle;
int32_t x;
int32_t y;
};

/**
* Shared state for our app.
*/
struct engine {
struct android_app *app;
ASensorManager *sensorManager;
const ASensor *accelerometerSensor;
ASensorEventQueue *sensorEventQueue;
int animating;
EGLDisplay display;
EGLSurface surface;
EGLContext context;
int32_t width;
int32_t height;
struct saved_state state;

};

static int init_es_egl(struct engine *engine) {
// initialize OpenGL ES and EGL
/*
* Here specify the attributes of the desired configuration.
* Below, we select an EGLConfig with at least 8 bits per color
* component compatible with on-screen windows
*/
const EGLint attribs[] = {
EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
EGL_BLUE_SIZE, 8,
EGL_GREEN_SIZE, 8,
EGL_RED_SIZE, 8,
EGL_NONE
};
EGLint w, h, format;
EGLint numConfigs;
EGLConfig config;
EGLSurface surface;
EGLContext context;
EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
eglInitialize(display, 0, 0);
SkAssertResult(eglBindAPI(EGL_OPENGL_ES_API));
/* Here, the application chooses the configuration it desires.
* find the best match if possible, otherwise use the very first one
*/
eglChooseConfig(display, attribs, nullptr, 0, &numConfigs);
std::unique_ptr<EGLConfig[]> supportedConfigs(new EGLConfig[numConfigs]);
assert(supportedConfigs);
eglChooseConfig(display, attribs, supportedConfigs.get(), numConfigs, &numConfigs);
assert(numConfigs);
auto i = 0;
for (; i < numConfigs; i++) {
auto &cfg = supportedConfigs[i];
EGLint r, g, b, d;
if (eglGetConfigAttrib(display, cfg, EGL_RED_SIZE, &r) &&
eglGetConfigAttrib(display, cfg, EGL_GREEN_SIZE, &g) &&
eglGetConfigAttrib(display, cfg, EGL_BLUE_SIZE, &b) &&
eglGetConfigAttrib(display, cfg, EGL_DEPTH_SIZE, &d) &&
r == 8 && g == 8 && b == 8 && d == 0) {

config = supportedConfigs[i];
break;
}
}
if (i == numConfigs) {
config = supportedConfigs[0];
}
/* EGL_NATIVE_VISUAL_ID is an attribute of the EGLConfig that is
* guaranteed to be accepted by ANativeWindow_setBuffersGeometry().
* As soon as we picked a EGLConfig, we can safely reconfigure the
* ANativeWindow buffers to match, using EGL_NATIVE_VISUAL_ID. */
eglGetConfigAttrib(display, config, EGL_NATIVE_VISUAL_ID, &format);
surface = eglCreateWindowSurface(display, config, engine->app->window, NULL);
context = eglCreateContext(display, config, NULL, NULL);

if (eglMakeCurrent(display, surface, surface, context) == EGL_FALSE) {
LOGW("Unable to eglMakeCurrent");
return -1;
}
eglQuerySurface(display, surface, EGL_WIDTH, &w);
eglQuerySurface(display, surface, EGL_HEIGHT, &h);

engine->display = display;
engine->context = context;
engine->surface = surface;
engine->width = w;
engine->height = h;
engine->state.angle = 0;

// Check openGL on the system
auto opengl_info = {GL_VENDOR, GL_RENDERER, GL_VERSION, GL_EXTENSIONS};
for (auto name : opengl_info) {
auto info = glGetString(name);
LOGI("OpenGL Info: %s", info);
}
LOGI("Canvas size: %d x %d", w, h);

// Initialize GL state.
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_FASTEST);
glEnable(GL_CULL_FACE);
glShadeModel(GL_SMOOTH);
glDisable(GL_DEPTH_TEST);

eglSurfaceAttrib(display, surface, EGL_SWAP_BEHAVIOR, EGL_BUFFER_PRESERVED);

return 0;
}

/**
* Initialize an EGL context for the current display.
*/
static int engine_init_display(struct engine *engine) {

int r = init_es_egl(engine);
if (r != 0) {
return r;
}
init_raster_skia(engine);
return 0;
}

static void initEgl(struct engine *engine) {
}

/**
* Just the current frame in the display.
*/
static void engine_draw_frame(struct engine *engine) {
if (engine->display == NULL) {
// No display.
return;
}
// Just fill the screen with a color.
glClearColor(((float) engine->state.x) / engine->width, engine->state.angle,
((float) engine->state.y) / engine->height, 1);
glClear(GL_COLOR_BUFFER_BIT);
eglSwapBuffers(engine->display, engine->surface);
}

/**
* Tear down the EGL context currently associated with the display.
*/
static void engine_term_display(struct engine *engine) {
if (engine->display != EGL_NO_DISPLAY) {
eglMakeCurrent(engine->display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
if (engine->context != EGL_NO_CONTEXT) {
eglDestroyContext(engine->display, engine->context);
}
if (engine->surface != EGL_NO_SURFACE) {
eglDestroySurface(engine->display, engine->surface);
}
eglTerminate(engine->display);
}
engine->animating = 0;
engine->display = EGL_NO_DISPLAY;
engine->context = EGL_NO_CONTEXT;
engine->surface = EGL_NO_SURFACE;
}

/**
* Process the next input event.
*/
static int32_t engine_handle_input(struct android_app *app, AInputEvent *event) {
struct engine *engine = (struct engine *) app->userData;
if (AInputEvent_getType(event) == AINPUT_EVENT_TYPE_MOTION) {
engine->animating = 1;
engine->state.x = AMotionEvent_getX(event, 0);
engine->state.y = AMotionEvent_getY(event, 0);
LOGI("touch %d,%d", engine->state.x, engine->state.y);
return 1;
}
return 0;
}

/**
* Process the next main command.
*/
static void engine_handle_cmd(struct android_app *app, int32_t cmd) {
struct engine *engine = (struct engine *) app->userData;
switch (cmd) {
case APP_CMD_SAVE_STATE:
// The system has asked us to save our current state. Do so.
engine->app->savedState = malloc(sizeof(struct saved_state));
*((struct saved_state *) engine->app->savedState) = engine->state;
engine->app->savedStateSize = sizeof(struct saved_state);
break;
case APP_CMD_INIT_WINDOW:
// The window is being shown, get it ready.
if (engine->app->window != NULL) {
engine_init_display(engine);
engine_draw_frame(engine);
}
break;
case APP_CMD_TERM_WINDOW:
// The window is being hidden or closed, clean it up.
engine_term_display(engine);
break;
case APP_CMD_GAINED_FOCUS:
// When our app gains focus, we start monitoring the accelerometer.
if (engine->accelerometerSensor != NULL) {
ASensorEventQueue_enableSensor(engine->sensorEventQueue,
engine->accelerometerSensor);
// We'd like to get 60 events per second (in us).
ASensorEventQueue_setEventRate(engine->sensorEventQueue,
engine->accelerometerSensor,
(1000L / 60) * 1000);
}
break;
case APP_CMD_LOST_FOCUS:
// When our app loses focus, we stop monitoring the accelerometer.
// This is to avoid consuming battery while not being used.
if (engine->accelerometerSensor != NULL) {
ASensorEventQueue_disableSensor(engine->sensorEventQueue,
engine->accelerometerSensor);
}
// Also stop animating.
engine->animating = 0;
engine_draw_frame(engine);
break;
}
}

/*
* AcquireASensorManagerInstance(void)
* Workaround ASensorManager_getInstance() deprecation false alarm
* for Android-N and before, when compiling with NDK-r15
*/
#include <dlfcn.h>

ASensorManager *AcquireASensorManagerInstance(android_app *app) {
if (!app)
return nullptr;

typedef ASensorManager *(*PF_GETINSTANCEFORPACKAGE)(const char *name);
void *androidHandle = dlopen("libandroid.so", RTLD_NOW);
PF_GETINSTANCEFORPACKAGE getInstanceForPackageFunc = (PF_GETINSTANCEFORPACKAGE)
dlsym(androidHandle, "ASensorManager_getInstanceForPackage");
if (getInstanceForPackageFunc) {
JNIEnv *env = nullptr;
app->activity->vm->AttachCurrentThread(&env, NULL);

jclass android_content_Context = env->GetObjectClass(app->activity->clazz);
jmethodID midGetPackageName = env->GetMethodID(android_content_Context,
"getPackageName",
"()Ljava/lang/String;");
jstring packageName = (jstring) env->CallObjectMethod(app->activity->clazz,
midGetPackageName);

const char *nativePackageName = env->GetStringUTFChars(packageName, 0);
ASensorManager *mgr = getInstanceForPackageFunc(nativePackageName);
env->ReleaseStringUTFChars(packageName, nativePackageName);
app->activity->vm->DetachCurrentThread();
if (mgr) {
dlclose(androidHandle);
return mgr;
}
}

typedef ASensorManager *(*PF_GETINSTANCE)();
PF_GETINSTANCE getInstanceFunc = (PF_GETINSTANCE)
dlsym(androidHandle, "ASensorManager_getInstance");
// by all means at this point, ASensorManager_getInstance should be available
assert(getInstanceFunc);
dlclose(androidHandle);

return getInstanceFunc();
}


/**
* This is the main entry point of a native application that is using
* android_native_app_glue. It runs in its own thread, with its own
* event loop for receiving input events and doing other things.
*/
void android_main(struct android_app *state) {
struct engine engine;

memset(&engine, 0, sizeof(engine));
state->userData = &engine;
state->onAppCmd = engine_handle_cmd;
state->onInputEvent = engine_handle_input;
engine.app = state;


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

if (state->savedState != NULL) {
// We are starting with a previous saved state; restore from it.
engine.state = *(struct saved_state *) state->savedState;
}

// loop waiting for stuff to do.

while (true) {
// Read all pending events.
int ident;
int events;
struct android_poll_source *source;

// If not animating, we will block forever waiting for events.
// If animating, we loop until all events are 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) {
ASensorEvent event;
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;
}
}

if (engine.animating) {
// Done with events; draw next animation frame.
engine.state.angle += .01f;
if (engine.state.angle > 1) {
engine.state.angle = 0;
}

// Drawing is throttled to the screen update rate, so there
// is no need to do timing here.
engine_draw_frame(&engine);
}
}
}
//END_INCLUDE(all)

cmake中配置main.cpp和android_native_app_glue.c,编译成main.o动态库,供NativeActivity.java调用,Android App启动入口为Java的Activity(NativeActivity),NativeActivity加载main.o动态库,将执行过程交给Native代码android_native_app_glue.c,android_native_app_glue.c中包含了Native部分的启动方法,ANativeActivity_onCreate。

/prebuilts/ndk/current/sources/android/native_app_glue/android_native_app_glue.c

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
JNIEXPORT
void ANativeActivity_onCreate(ANativeActivity* activity, void* savedState,
size_t savedStateSize){
LOGV("Creating: %p\n", activity);
activity->callbacks->onDestroy = onDestroy;
activity->callbacks->onStart = onStart;
activity->callbacks->onResume = onResume;
activity->callbacks->onSaveInstanceState = onSaveInstanceState;
activity->callbacks->onPause = onPause;
activity->callbacks->onStop = onStop;
activity->callbacks->onConfigurationChanged = onConfigurationChanged;
activity->callbacks->onLowMemory = onLowMemory;
activity->callbacks->onWindowFocusChanged = onWindowFocusChanged;
activity->callbacks->onNativeWindowCreated = onNativeWindowCreated;
activity->callbacks->onNativeWindowDestroyed = onNativeWindowDestroyed;
activity->callbacks->onInputQueueCreated = onInputQueueCreated;
activity->callbacks->onInputQueueDestroyed = onInputQueueDestroyed;
activity->instance = android_app_create(activity, savedState, savedStateSize);
}

android_native_app_glue.c中包含Activity的Native原生生命周期方法:

1
2
3
4
static void onDestroy(ANativeActivity* activity);
static void onStart(ANativeActivity* activity);
static void onResume(ANativeActivity* activity);
...

在执行ANativeActivity_onCreate方法后,调用android_app_create方法,进入android_app_entry方法。android_app_entry调用main.cpp中我们写的android_main(android_app)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
static struct android_app* android_app_create(ANativeActivity* activity,
void* savedState, size_t savedStateSize) {
struct android_app* android_app = (struct android_app*)malloc(sizeof(struct android_app));
memset(android_app, 0, sizeof(struct android_app));
android_app->activity = activity;

pthread_mutex_init(&android_app->mutex, NULL);
pthread_cond_init(&android_app->cond, NULL);

if (savedState != NULL) {
android_app->savedState = malloc(savedStateSize);
android_app->savedStateSize = savedStateSize;
memcpy(android_app->savedState, savedState, savedStateSize);
}

int msgpipe[2];
if (pipe(msgpipe)) {
LOGE("could not create pipe: %s", strerror(errno));
return NULL;
}
android_app->msgread = msgpipe[0];
android_app->msgwrite = msgpipe[1];

pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
pthread_create(&android_app->thread, &attr, android_app_entry, android_app);

// Wait for thread to start.
pthread_mutex_lock(&android_app->mutex);
while (!android_app->running) {
pthread_cond_wait(&android_app->cond, &android_app->mutex);
}
pthread_mutex_unlock(&android_app->mutex);

return android_app;
}
static void* android_app_entry(void* param) {
struct android_app* android_app = (struct android_app*)param;
android_app->config = AConfiguration_new();
AConfiguration_fromAssetManager(android_app->config, android_app->activity->assetManager);
print_cur_config(android_app);
android_app->cmdPollSource.id = LOOPER_ID_MAIN;
android_app->cmdPollSource.app = android_app;
android_app->cmdPollSource.process = process_cmd;
android_app->inputPollSource.id = LOOPER_ID_INPUT;
android_app->inputPollSource.app = android_app;
android_app->inputPollSource.process = process_input;
ALooper* looper = ALooper_prepare(ALOOPER_PREPARE_ALLOW_NON_CALLBACKS);
ALooper_addFd(looper, android_app->msgread, LOOPER_ID_MAIN, ALOOPER_EVENT_INPUT, NULL,
&android_app->cmdPollSource);
android_app->looper = looper;
pthread_mutex_lock(&android_app->mutex);
android_app->running = 1;
pthread_cond_broadcast(&android_app->cond);
pthread_mutex_unlock(&android_app->mutex);
android_main(android_app);
android_app_destroy(android_app);
return NULL;
}

0x03 NDK Native 调用原理

我们来看一下NativeActivity加载NativeCode的过程。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
public class NativeActivity extends Activity implements SurfaceHolder.Callback2,
InputQueue.Callback, OnGlobalLayoutListener{
protected void onCreate(Bundle savedInstanceState) {
String libname = "main";
String funcname = "ANativeActivity_onCreate";
ActivityInfo ai;
mIMM = getSystemService(InputMethodManager.class);
getWindow().takeSurface(this);
getWindow().takeInputQueue(this);
getWindow().setFormat(PixelFormat.RGB_565);
getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED
| WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
mNativeContentView = new NativeContentView(this);
mNativeContentView.mActivity = this;
setContentView(mNativeContentView);
mNativeContentView.requestFocus();
mNativeContentView.getViewTreeObserver().addOnGlobalLayoutListener(this);
try {
ai = getPackageManager().getActivityInfo(
getIntent().getComponent(), PackageManager.GET_META_DATA);
if (ai.metaData != null) {
String ln = ai.metaData.getString(META_DATA_LIB_NAME);
if (ln != null) libname = ln;
ln = ai.metaData.getString(META_DATA_FUNC_NAME);
if (ln != null) funcname = ln;
}
} catch (PackageManager.NameNotFoundException e) {
throw new RuntimeException("Error getting activity info", e);
}
BaseDexClassLoader classLoader = (BaseDexClassLoader) getClassLoader();
String path = classLoader.findLibrary(libname);
if (path == null) {
throw new IllegalArgumentException("Unable to find native library " + libname +
" using classloader: " + classLoader.toString());
}
byte[] nativeSavedState = savedInstanceState != null
? savedInstanceState.getByteArray(KEY_NATIVE_SAVED_STATE) : null;
mNativeHandle = loadNativeCode(path, funcname, Looper.myQueue(),
getAbsolutePath(getFilesDir()), getAbsolutePath(getObbDir()),
getAbsolutePath(getExternalFilesDir(null)),
Build.VERSION.SDK_INT, getAssets(), nativeSavedState,
classLoader, classLoader.getLdLibraryPath());
if (mNativeHandle == 0) {
throw new UnsatisfiedLinkError(
"Unable to load native library \"" + path + "\": " + getDlError());
}
super.onCreate(savedInstanceState);
}
}

onCreate方法中主要实现了以下功能:

  1. 托管Surface、InputQueue给Native
  2. 设置 NativeContentView
  3. 加载so库,获取mNativeHandle

在onStart、onResume、onPause、onStop等中分别调用Native方法,在onDestroy总则注销Surface、InputQueue以及unloadNativeCode。

其中libname默认为main,funcname默认为ANativeActivity_onCreate。libname即为加载的Native库的名称:

1
2
3
4
5
6
7
8
9
10
11
 <application android:label="@string/app_name" android:hasCode="false">
<activity android:name="android.app.NativeActivity"
android:label="@string/app_name">
<meta-data android:name="android.app.lib_name"
android:value="main"/>
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>

对应android.app.lib_name 的值main ,而funcname对于Native中loadNativeCode_native时的createActivityFunc,用于创建Activity。这2个名字可根据实际情况自定义。

在/frameworks/base/core/jni/android_app_NativeActivity.cpp 中我们可以看到Native方法的具体实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
static jlong
loadNativeCode_native(JNIEnv* env, jobject clazz, jstring path, jstring funcName,
jobject messageQueue, jstring internalDataDir, jstring obbDir,
jstring externalDataDir, jint sdkVersion, jobject jAssetMgr,
jbyteArray savedState, jobject classLoader, jstring libraryPath) {
if (kLogTrace) {
ALOGD("loadNativeCode_native");
}

ScopedUtfChars pathStr(env, path);
std::unique_ptr<NativeCode> code;
bool needs_native_bridge = false;

void* handle = OpenNativeLibrary(env,
sdkVersion,
pathStr.c_str(),
classLoader,
libraryPath,
&needs_native_bridge,
&g_error_msg);

if (handle == nullptr) {
ALOGW("NativeActivity LoadNativeLibrary(\"%s\") failed: %s",
pathStr.c_str(),
g_error_msg.c_str());
return 0;
}

void* funcPtr = NULL;
const char* funcStr = env->GetStringUTFChars(funcName, NULL);
if (needs_native_bridge) {
funcPtr = NativeBridgeGetTrampoline(handle, funcStr, NULL, 0);
} else {
funcPtr = dlsym(handle, funcStr);
}

code.reset(new NativeCode(handle, (ANativeActivity_createFunc*)funcPtr));
env->ReleaseStringUTFChars(funcName, funcStr);

if (code->createActivityFunc == NULL) {
g_error_msg = needs_native_bridge ? NativeBridgeGetError() : dlerror();
ALOGW("ANativeActivity_onCreate not found: %s", g_error_msg.c_str());
return 0;
}

code->messageQueue = android_os_MessageQueue_getMessageQueue(env, messageQueue);
if (code->messageQueue == NULL) {
g_error_msg = "Unable to retrieve native MessageQueue";
ALOGW("%s", g_error_msg.c_str());
return 0;
}

int msgpipe[2];
if (pipe(msgpipe)) {
g_error_msg = android::base::StringPrintf("could not create pipe: %s", strerror(errno));
ALOGW("%s", g_error_msg.c_str());
return 0;
}
code->mainWorkRead = msgpipe[0];
code->mainWorkWrite = msgpipe[1];
int result = fcntl(code->mainWorkRead, F_SETFL, O_NONBLOCK);
SLOGW_IF(result != 0, "Could not make main work read pipe "
"non-blocking: %s", strerror(errno));
result = fcntl(code->mainWorkWrite, F_SETFL, O_NONBLOCK);
SLOGW_IF(result != 0, "Could not make main work write pipe "
"non-blocking: %s", strerror(errno));
code->messageQueue->getLooper()->addFd(
code->mainWorkRead, 0, ALOOPER_EVENT_INPUT, mainWorkCallback, code.get());

code->ANativeActivity::callbacks = &code->callbacks;
if (env->GetJavaVM(&code->vm) < 0) {
g_error_msg = "NativeActivity GetJavaVM failed";
ALOGW("%s", g_error_msg.c_str());
return 0;
}
code->env = env;
code->clazz = env->NewGlobalRef(clazz);

const char* dirStr = env->GetStringUTFChars(internalDataDir, NULL);
code->internalDataPathObj = dirStr;
code->internalDataPath = code->internalDataPathObj.string();
env->ReleaseStringUTFChars(internalDataDir, dirStr);

if (externalDataDir != NULL) {
dirStr = env->GetStringUTFChars(externalDataDir, NULL);
code->externalDataPathObj = dirStr;
env->ReleaseStringUTFChars(externalDataDir, dirStr);
}
code->externalDataPath = code->externalDataPathObj.string();

code->sdkVersion = sdkVersion;

code->javaAssetManager = env->NewGlobalRef(jAssetMgr);
code->assetManager = NdkAssetManagerForJavaObject(env, jAssetMgr);

if (obbDir != NULL) {
dirStr = env->GetStringUTFChars(obbDir, NULL);
code->obbPathObj = dirStr;
env->ReleaseStringUTFChars(obbDir, dirStr);
}
code->obbPath = code->obbPathObj.string();

jbyte* rawSavedState = NULL;
jsize rawSavedSize = 0;
if (savedState != NULL) {
rawSavedState = env->GetByteArrayElements(savedState, NULL);
rawSavedSize = env->GetArrayLength(savedState);
}

code->createActivityFunc(code.get(), rawSavedState, rawSavedSize);

if (rawSavedState != NULL) {
env->ReleaseByteArrayElements(savedState, rawSavedState, 0);
}

return (jlong)code.release();
}

static jstring getDlError_native(JNIEnv* env, jobject clazz) {
jstring result = env->NewStringUTF(g_error_msg.c_str());
g_error_msg.clear();
return result;
}

static void
unloadNativeCode_native(JNIEnv* env, jobject clazz, jlong handle)
{
if (kLogTrace) {
ALOGD("unloadNativeCode_native");
}
if (handle != 0) {
NativeCode* code = (NativeCode*)handle;
delete code;
}
}

static void
onStart_native(JNIEnv* env, jobject clazz, jlong handle)
{
if (kLogTrace) {
ALOGD("onStart_native");
}
if (handle != 0) {
NativeCode* code = (NativeCode*)handle;
if (code->callbacks.onStart != NULL) {
code->callbacks.onStart(code);
}
}
}

static void
onResume_native(JNIEnv* env, jobject clazz, jlong handle)
{
if (kLogTrace) {
ALOGD("onResume_native");
}
if (handle != 0) {
NativeCode* code = (NativeCode*)handle;
if (code->callbacks.onResume != NULL) {
code->callbacks.onResume(code);
}
}
}

static jbyteArray
onSaveInstanceState_native(JNIEnv* env, jobject clazz, jlong handle)
{
if (kLogTrace) {
ALOGD("onSaveInstanceState_native");
}

jbyteArray array = NULL;

if (handle != 0) {
NativeCode* code = (NativeCode*)handle;
if (code->callbacks.onSaveInstanceState != NULL) {
size_t len = 0;
jbyte* state = (jbyte*)code->callbacks.onSaveInstanceState(code, &len);
if (len > 0) {
array = env->NewByteArray(len);
if (array != NULL) {
env->SetByteArrayRegion(array, 0, len, state);
}
}
if (state != NULL) {
free(state);
}
}
}

return array;
}

static void
onPause_native(JNIEnv* env, jobject clazz, jlong handle)
{
if (kLogTrace) {
ALOGD("onPause_native");
}
if (handle != 0) {
NativeCode* code = (NativeCode*)handle;
if (code->callbacks.onPause != NULL) {
code->callbacks.onPause(code);
}
}
}

static void
onStop_native(JNIEnv* env, jobject clazz, jlong handle)
{
if (kLogTrace) {
ALOGD("onStop_native");
}
if (handle != 0) {
NativeCode* code = (NativeCode*)handle;
if (code->callbacks.onStop != NULL) {
code->callbacks.onStop(code);
}
}
}

static void
onConfigurationChanged_native(JNIEnv* env, jobject clazz, jlong handle)
{
if (kLogTrace) {
ALOGD("onConfigurationChanged_native");
}
if (handle != 0) {
NativeCode* code = (NativeCode*)handle;
if (code->callbacks.onConfigurationChanged != NULL) {
code->callbacks.onConfigurationChanged(code);
}
}
}

static void
onLowMemory_native(JNIEnv* env, jobject clazz, jlong handle)
{
if (kLogTrace) {
ALOGD("onLowMemory_native");
}
if (handle != 0) {
NativeCode* code = (NativeCode*)handle;
if (code->callbacks.onLowMemory != NULL) {
code->callbacks.onLowMemory(code);
}
}
}

static void
onWindowFocusChanged_native(JNIEnv* env, jobject clazz, jlong handle, jboolean focused)
{
if (kLogTrace) {
ALOGD("onWindowFocusChanged_native");
}
if (handle != 0) {
NativeCode* code = (NativeCode*)handle;
if (code->callbacks.onWindowFocusChanged != NULL) {
code->callbacks.onWindowFocusChanged(code, focused ? 1 : 0);
}
}
}

static void
onSurfaceCreated_native(JNIEnv* env, jobject clazz, jlong handle, jobject surface)
{
if (kLogTrace) {
ALOGD("onSurfaceCreated_native");
}
if (handle != 0) {
NativeCode* code = (NativeCode*)handle;
code->setSurface(surface);
if (code->nativeWindow != NULL && code->callbacks.onNativeWindowCreated != NULL) {
code->callbacks.onNativeWindowCreated(code,
code->nativeWindow.get());
}
}
}

static int32_t getWindowProp(ANativeWindow* window, int what) {
int value;
int res = window->query(window, what, &value);
return res < 0 ? res : value;
}

static void
onSurfaceChanged_native(JNIEnv* env, jobject clazz, jlong handle, jobject surface,
jint format, jint width, jint height)
{
if (kLogTrace) {
ALOGD("onSurfaceChanged_native");
}
if (handle != 0) {
NativeCode* code = (NativeCode*)handle;
sp<ANativeWindow> oldNativeWindow = code->nativeWindow;
code->setSurface(surface);
if (oldNativeWindow != code->nativeWindow) {
if (oldNativeWindow != NULL && code->callbacks.onNativeWindowDestroyed != NULL) {
code->callbacks.onNativeWindowDestroyed(code,
oldNativeWindow.get());
}
if (code->nativeWindow != NULL) {
if (code->callbacks.onNativeWindowCreated != NULL) {
code->callbacks.onNativeWindowCreated(code,
code->nativeWindow.get());
}
code->lastWindowWidth = getWindowProp(code->nativeWindow.get(),
NATIVE_WINDOW_WIDTH);
code->lastWindowHeight = getWindowProp(code->nativeWindow.get(),
NATIVE_WINDOW_HEIGHT);
}
} else {
// Maybe it resized?
int32_t newWidth = getWindowProp(code->nativeWindow.get(),
NATIVE_WINDOW_WIDTH);
int32_t newHeight = getWindowProp(code->nativeWindow.get(),
NATIVE_WINDOW_HEIGHT);
if (newWidth != code->lastWindowWidth
|| newHeight != code->lastWindowHeight) {
if (code->callbacks.onNativeWindowResized != NULL) {
code->callbacks.onNativeWindowResized(code,
code->nativeWindow.get());
}
}
}
}
}

static void
onSurfaceRedrawNeeded_native(JNIEnv* env, jobject clazz, jlong handle)
{
if (kLogTrace) {
ALOGD("onSurfaceRedrawNeeded_native");
}
if (handle != 0) {
NativeCode* code = (NativeCode*)handle;
if (code->nativeWindow != NULL && code->callbacks.onNativeWindowRedrawNeeded != NULL) {
code->callbacks.onNativeWindowRedrawNeeded(code, code->nativeWindow.get());
}
}
}

static void
onSurfaceDestroyed_native(JNIEnv* env, jobject clazz, jlong handle, jobject surface)
{
if (kLogTrace) {
ALOGD("onSurfaceDestroyed_native");
}
if (handle != 0) {
NativeCode* code = (NativeCode*)handle;
if (code->nativeWindow != NULL && code->callbacks.onNativeWindowDestroyed != NULL) {
code->callbacks.onNativeWindowDestroyed(code,
code->nativeWindow.get());
}
code->setSurface(NULL);
}
}

static void
onInputQueueCreated_native(JNIEnv* env, jobject clazz, jlong handle, jlong queuePtr)
{
if (kLogTrace) {
ALOGD("onInputChannelCreated_native");
}
if (handle != 0) {
NativeCode* code = (NativeCode*)handle;
if (code->callbacks.onInputQueueCreated != NULL) {
AInputQueue* queue = reinterpret_cast<AInputQueue*>(queuePtr);
code->callbacks.onInputQueueCreated(code, queue);
}
}
}

static void
onInputQueueDestroyed_native(JNIEnv* env, jobject clazz, jlong handle, jlong queuePtr)
{
if (kLogTrace) {
ALOGD("onInputChannelDestroyed_native");
}
if (handle != 0) {
NativeCode* code = (NativeCode*)handle;
if (code->callbacks.onInputQueueDestroyed != NULL) {
AInputQueue* queue = reinterpret_cast<AInputQueue*>(queuePtr);
code->callbacks.onInputQueueDestroyed(code, queue);
}
}
}

static void
onContentRectChanged_native(JNIEnv* env, jobject clazz, jlong handle,
jint x, jint y, jint w, jint h)
{
if (kLogTrace) {
ALOGD("onContentRectChanged_native");
}
if (handle != 0) {
NativeCode* code = (NativeCode*)handle;
if (code->callbacks.onContentRectChanged != NULL) {
ARect rect;
rect.left = x;
rect.top = y;
rect.right = x+w;
rect.bottom = y+h;
code->callbacks.onContentRectChanged(code, &rect);
}
}
}

static const JNINativeMethod g_methods[] = {
{ "loadNativeCode",
"(Ljava/lang/String;Ljava/lang/String;Landroid/os/MessageQueue;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ILandroid/content/res/AssetManager;[BLjava/lang/ClassLoader;Ljava/lang/String;)J",
(void*)loadNativeCode_native },
{ "getDlError", "()Ljava/lang/String;", (void*) getDlError_native },
{ "unloadNativeCode", "(J)V", (void*)unloadNativeCode_native },
{ "onStartNative", "(J)V", (void*)onStart_native },
{ "onResumeNative", "(J)V", (void*)onResume_native },
{ "onSaveInstanceStateNative", "(J)[B", (void*)onSaveInstanceState_native },
{ "onPauseNative", "(J)V", (void*)onPause_native },
{ "onStopNative", "(J)V", (void*)onStop_native },
{ "onConfigurationChangedNative", "(J)V", (void*)onConfigurationChanged_native },
{ "onLowMemoryNative", "(J)V", (void*)onLowMemory_native },
{ "onWindowFocusChangedNative", "(JZ)V", (void*)onWindowFocusChanged_native },
{ "onSurfaceCreatedNative", "(JLandroid/view/Surface;)V", (void*)onSurfaceCreated_native },
{ "onSurfaceChangedNative", "(JLandroid/view/Surface;III)V", (void*)onSurfaceChanged_native },
{ "onSurfaceRedrawNeededNative", "(JLandroid/view/Surface;)V", (void*)onSurfaceRedrawNeeded_native },
{ "onSurfaceDestroyedNative", "(J)V", (void*)onSurfaceDestroyed_native },
{ "onInputQueueCreatedNative", "(JJ)V",
(void*)onInputQueueCreated_native },
{ "onInputQueueDestroyedNative", "(JJ)V",
(void*)onInputQueueDestroyed_native },
{ "onContentRectChangedNative", "(JIIII)V", (void*)onContentRectChanged_native },
};

loadNativeCode_native加载Native库,获取handle,在Activity生命周期中,生命周期方法通过NativeCode* code = (NativeCode*)handle; 交由Native代码执行,上文中直接使用 android_native_app_glue.c , 里面已经实现了Native生命周期方法,也可自己写。

在loadNativeCode_native时:

  1. 首先是通过OpenNativeLibrary来获取handle

  2. 通过设定的funcname来获取Activity创建方法 createActivityFunc

  3. 设置messageQueue

  4. 在messageQueue中设置主进程回调

    1
    2
    code->messageQueue->getLooper()->addFd(
    code->mainWorkRead, 0, ALOOPER_EVENT_INPUT, mainWorkCallback, code.get());
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    static int mainWorkCallback(int fd, int events, void* data) {
    NativeCode* code = (NativeCode*)data;
    if ((events & POLLIN) == 0) {
    return 1;
    }
    ActivityWork work;
    if (!read_work(code->mainWorkRead, &work)) {
    return 1;
    }
    if (kLogTrace) {
    ALOGD("mainWorkCallback: cmd=%d", work.cmd);
    }
    switch (work.cmd) {
    case CMD_FINISH: {
    code->env->CallVoidMethod(code->clazz, gNativeActivityClassInfo.finish);
    code->messageQueue->raiseAndClearException(code->env, "finish");
    } break;
    case CMD_SET_WINDOW_FORMAT: {
    code->env->CallVoidMethod(code->clazz,
    gNativeActivityClassInfo.setWindowFormat, work.arg1);
    code->messageQueue->raiseAndClearException(code->env, "setWindowFormat");
    } break;
    case CMD_SET_WINDOW_FLAGS: {
    code->env->CallVoidMethod(code->clazz,
    gNativeActivityClassInfo.setWindowFlags, work.arg1, work.arg2);
    code->messageQueue->raiseAndClearException(code->env, "setWindowFlags");
    } break;
    case CMD_SHOW_SOFT_INPUT: {
    code->env->CallVoidMethod(code->clazz,
    gNativeActivityClassInfo.showIme, work.arg1);
    code->messageQueue->raiseAndClearException(code->env, "showIme");
    } break;
    case CMD_HIDE_SOFT_INPUT: {
    code->env->CallVoidMethod(code->clazz,
    gNativeActivityClassInfo.hideIme, work.arg1);
    code->messageQueue->raiseAndClearException(code->env, "hideIme");
    } break;
    default:
    ALOGW("Unknown work command: %d", work.cmd);
    break;
    }
    return 1;
    }

    getLooper()->addFd() 方法见: /system/core/libutils/Looper.cpp

    数据通信通过管道进行。

  5. 设置JavaVM给NativeCode

  6. 设置internalDataPath、externalDataPath、javaAssetManager、obbPath

  7. 获取rawSavedState,并执行createActivityFunc

  8. 释放资源

至此,完成Activity创建。

可简单看一下OpenNativeLibrary代码,OpenNativeLibrary方法也是Android加载JNI库时,实际使用的方法:

1
System.loadLibrary("native-lib");

/system/core/libnativeloader/native_loader.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
void* OpenNativeLibrary(JNIEnv* env,
int32_t target_sdk_version,
const char* path,
jobject class_loader,
jstring library_path,
bool* needs_native_bridge,
std::string* error_msg) {
#if defined(__ANDROID__)
UNUSED(target_sdk_version);
if (class_loader == nullptr) {
*needs_native_bridge = false;
return dlopen(path, RTLD_NOW);
}

std::lock_guard<std::mutex> guard(g_namespaces_mutex);
NativeLoaderNamespace ns;

if (!g_namespaces->FindNamespaceByClassLoader(env, class_loader, &ns)) {
// This is the case where the classloader was not created by ApplicationLoaders
// In this case we create an isolated not-shared namespace for it.
if (!g_namespaces->Create(env,
target_sdk_version,
class_loader,
false /* is_shared */,
false /* is_for_vendor */,
library_path,
nullptr,
&ns,
error_msg)) {
return nullptr;
}
}

if (ns.is_android_namespace()) {
android_dlextinfo extinfo;
extinfo.flags = ANDROID_DLEXT_USE_NAMESPACE;
extinfo.library_namespace = ns.get_android_ns();

void* handle = android_dlopen_ext(path, RTLD_NOW, &extinfo);
if (handle == nullptr) {
*error_msg = dlerror();
}
*needs_native_bridge = false;
return handle;
} else {
void* handle = NativeBridgeLoadLibraryExt(path, RTLD_NOW, ns.get_native_bridge_ns());
if (handle == nullptr) {
*error_msg = NativeBridgeGetError();
}
*needs_native_bridge = true;
return handle;
}
#else
UNUSED(env, target_sdk_version, class_loader);

// Do some best effort to emulate library-path support. It will not
// work for dependencies.
//
// Note: null has a special meaning and must be preserved.
std::string c_library_path; // Empty string by default.
if (library_path != nullptr && path != nullptr && path[0] != '/') {
ScopedUtfChars library_path_utf_chars(env, library_path);
c_library_path = library_path_utf_chars.c_str();
}

std::vector<std::string> library_paths = base::Split(c_library_path, ":");

for (const std::string& lib_path : library_paths) {
*needs_native_bridge = false;
const char* path_arg;
std::string complete_path;
if (path == nullptr) {
// Preserve null.
path_arg = nullptr;
} else {
complete_path = lib_path;
if (!complete_path.empty()) {
complete_path.append("/");
}
complete_path.append(path);
path_arg = complete_path.c_str();
}
void* handle = dlopen(path_arg, RTLD_NOW);
if (handle != nullptr) {
return handle;
}
if (NativeBridgeIsSupported(path_arg)) {
*needs_native_bridge = true;
handle = NativeBridgeLoadLibrary(path_arg, RTLD_NOW);
if (handle != nullptr) {
return handle;
}
*error_msg = NativeBridgeGetError();
} else {
*error_msg = dlerror();
}
}
return nullptr;
#endif
}

这段主要是加载Native库的代码。可参考:

https://cloud.tencent.com/developer/article/1034856

https://blog.csdn.net/edonlii/article/details/8445239

小结

Android在启动AndroidManifest.xml中配置的android.app.NativeActivity后,主要完成了一下工作:

  1. 通过libname获取NativeCode,并将android.app.NativeActivity的生命周期方法交给NativeCode处理,并托管Surface、InputQueue给Native
  2. 在加载NativeCode对应的库时,通过OpenNativeLibrary加载Native库,进行一些列设置后,执行Native库中funcname对于的方法,用来创建原生的Native App。

/external/skia/tools/sk_app/android/main_android.cpp

/external/flatbuffers/android/jni/main.cpp

/prebuilts/ndk/current/sources/android/native_app_glue/android_native_app_glue.c

0x04 附录:CMake简单实用