Android APK调用mongoose

这篇博客介绍如何在Android应用中利用JNI技术调用mongoose库,将mongoose的hello_world示例转换为JNI函数,从而在Java代码中进行原生调用。同时,文章提醒在AndroidManifest.xml中添加必要的权限,包括Internet权限和读取外部存储权限,以确保应用能正常运行并显示本地HTTP服务器的网页内容。用户可以在手机上访问127.0.0.1:8080查看效果。

这里使用了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即可看到网页

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值