這裏使用了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即可看到網頁