这里使用了mongoose里面的hello_world这个例子,将里面的main函数转换成了jni函数,以便能够在java代码中通过native调用。
static int ev_handler(struct mg_connection *conn, enum mg_event ev) {
switch (ev) {
__android_log_print(ANDROID_LOG_INFO, "JNI_LOG", "ev:%d", ev);
case MG_AUTH: return MG_TRUE;
case MG_REQUEST:
// 原来是这个mg_printf_data(conn, "Hello! Requested URI is [%s]", conn->uri);
// 换成发送如下网页,这个文件可以预先存入手机,路径随意
mg_send_file(conn, "/storage/sdcard0/index.html", NULL);
return MG_MORE;
//return MG_TRUE; // 更改返回值
default: return MG_FALSE;
}
}
JNIEXPORT jint JNICALL Java_com_test_mongoosetest_MainActivity_main(JNIEnv *env, jclass clazz){
struct mg_server *server;
// Create and configure the server
server = mg_create_server(NULL, ev_handler);
mg_set_option(server, "listening_port", "8080");
// Serve request. Hit Ctrl-C to terminate the program
printf("Starting on port %s\n", mg_get_option(server, "listening_port"));
for (;;) {
mg_poll_server(server, 1000);
__android_log_print(ANDROID_LOG_INFO, "JNI_LOG", "hello");
}
// Cleanup, and free server instance
mg_destroy_server(&server);
return 0;
}
public class MainActivity extends Activity {
private static native int main();
static{
System.loadLibrary("monogoose");
System.loadLibrary("hello_world");
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 新建一个进程去执行
new Thread(new Runnable(){
@Override
public void run() {
main();
}
}).start();
}
}
最后的最后别忘了在AndroidManifest.xml中添加权限,否则可能找不到网页。运行起来需要Internet权限,而我们需要读取外部存储的数据,所以也需要添加相应权限。
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
最后手机端访问127.0.0.1:8080即可看到网页