【Android JNI】 C/C++ 标准输入输出打印至Android日志控制台

【Android】 C/C++ 标准输入输出打印至Android日志控制台

C++ 复制代码
#if defined(__ANDROID__)
start_logger("yeasound_sdk-native");
#endif

#if defined(__ANDROID__)
#include <stdio.h>
#include <unistd.h>
#include <android/log.h>
#include <android/native_activity.h>
#include <android/asset_manager_jni.h>
#include <android/asset_manager.h>
#endif


#if defined(__ANDROID__)
extern "C" {
    static int pfd[2];
    static pthread_t thr;
    static const char *tag = "myapp";
    static void *thread_func(void *)
    {
        ssize_t rdsz;
        char buf[128];
        while ((rdsz = read(pfd[0], buf, sizeof buf - 1)) > 0) {
            if (buf[rdsz - 1] == '\n') --rdsz;
            buf[rdsz] = 0;  /* add null-terminator */
            __android_log_write(ANDROID_LOG_DEBUG, tag, buf);
        }
        return 0;
    }

    int start_logger(const char *app_name)
    {
        tag = app_name;

        /* make stdout line-buffered and stderr unbuffered */
        setvbuf(stdout, 0, _IOLBF, 0);
        setvbuf(stderr, 0, _IONBF, 0);

        /* create the pipe and redirect stdout and stderr */
        pipe(pfd);
        dup2(pfd[1], 1);
        dup2(pfd[1], 2);

        /* spawn the logging thread */
        if (pthread_create(&thr, 0, thread_func, 0) == -1)
            return -1;
        pthread_detach(thr);
        return 0;
    }
}
#endif


JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved)
{
    JNIEnv *env;
    if (vm->GetEnv(reinterpret_cast<void **>(&env), JNI_VERSION_1_6) != JNI_OK) {
        return JNI_ERR;
    }

#if defined(__ANDROID__)
    start_logger("yeasound_sdk-native");
#endif

    /* --javaVM是虚拟机在JNI中的表示 --*/
    env->GetJavaVM(&g_jni_vm);
    if (g_jni_vm == nullptr) {
        return JNI_ERR;
    }

    jni_utils_set_global_vm(g_jni_vm);

    if(jni_cache_init() != YeasoundLib::YS_STATUS_SUCCESS){
        return JNI_ERR;
    }

    return JNI_VERSION_1_6;
}
相关推荐
Cyanto7 分钟前
Spring注解IoC与JUnit整合实战
java·开发语言·spring·mybatis
qq_433888937 分钟前
Junit多线程的坑
java·spring·junit
gadiaola11 分钟前
【SSM面试篇】Spring、SpringMVC、SpringBoot、Mybatis高频八股汇总
java·spring boot·spring·面试·mybatis
写不出来就跑路14 分钟前
WebClient与HTTPInterface远程调用对比
java·开发语言·后端·spring·springboot
Cyanto20 分钟前
深入MyBatis:CRUD操作与高级查询实战
java·数据库·mybatis
悠哉清闲25 分钟前
C++ MediaCodec H264解码
开发语言·c++
麦兜*1 小时前
Spring Boot 集成Reactive Web 性能优化全栈技术方案,包含底层原理、压测方法论、参数调优
java·前端·spring boot·spring·spring cloud·性能优化·maven
天上掉下来个程小白1 小时前
MybatisPlus-06.核心功能-自定义SQL
java·spring boot·后端·sql·微服务·mybatisplus
知了一笑1 小时前
独立开发第二周:构建、执行、规划
java·前端·后端
小李飞飞砖2 小时前
Sophix、Tinker 和 Robust 三大主流 Android 热修复框架的详细对比
android