• Android NDK学习(三):Hello World


    版权声明:转载请说明出处:http://www.cnblogs.com/renhui/p/6925810.html

    首先编写Jni接口的c文件,此文件命名有些特殊,具体的命名方式可以参考文档来做。

    #include <jni.h>
    #include <string.h>
    #include <stdio.h>
    
    
    JNIEXPORT jstring JNICALL
    Java_com_renhui_mplayer_MainActivity_displayHelloWorld(JNIEnv *env, jobject obj)
    {
        return (*env)->NewStringUTF(env, "11111");
    }

    配置Android.mk

    #定义本地路径变量 LOCAL_PATH
    LOCAL_PATH := $(call my-dir)
    include $(CLEAR_VARS)
    LOCAL_MODULE := native-lib
    LOCAL_SRC_FILES := native-lib.c
    include $(BUILD_SHARED_LIBRARY)

    配置好mk文件后,在jni目录下执行ndk-build,即可获得当前所有的cpu平台的so文件。将so文件导入到项目中后,再写Java层的代码。

    Java 代码

    @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
        // Example of a call to a native method
        TextView tv = (TextView) findViewById(R.id.sample_text);
        tv.setText(displayHelloWorld());
        }
    
        /**
         * A native method that is implemented by the 'native-lib' native library,
         * which is packaged with this application.
         */
        public native String displayHelloWorld();
    
        // Used to load the 'native-lib' library on application startup.
        static {
            System.loadLibrary("native-lib");
        }

    写完后,执行可以在真机上看到屏幕中有11111的内容输出。此时,NDK的hello world的学习就结束了,后续理解其他的NDK项目时,可以根据此思路来做相应的理解和调整。

    -------------------------------------------- 补充一:日志工具类AndroidLog -----------------------------------------------------------

    当我们跑通了HelloWorld之后,我们会想到如何在JNI层像Android原生开发一样输出Log内容到LogCat,这样能帮助我们更加快速的定位问题。只需要在jni层添加AndroidLog.h文件即可,头文件代码如下:

    #pragma once
    
    #ifdef ANDROID
    
    #include <jni.h>
    #include <android/log.h>
    
    #define LOGE(format, ...)  __android_log_print(ANDROID_LOG_ERROR, "renhui", format, ##__VA_ARGS__)
    #define LOGI(format, ...)  __android_log_print(ANDROID_LOG_INFO,  "renhui", format, ##__VA_ARGS__)
    
    #else
    #define LOGE(format, ...)  printf("renhui" format "
    ", ##__VA_ARGS__)
    #define LOGI(format, ...)  printf("renhui" format "
    ", ##__VA_ARGS__)
    #endif
  • 相关阅读:
    Android 面试知识集1
    Android 开发自己的网络收音机2——电台列表(SlidingMenu侧滑栏)
    Android 程序drawable资源保存到data目录
    Android 开发自己的网络收音机1——功能要求及设计方案
    Android内存机制分析2——分析APP内存使用情况
    Android内存机制分析1——了解Android堆和栈
    Android Gallery实现3D相册(附效果图+Demo源码)
    Android 后台发送邮件 (收集应用异常信息+Demo代码)
    纯代码写UI的时候,如何指定style?
    解决SimpleCursorAdapter不能自动更新的问题
  • 原文地址:https://www.cnblogs.com/renhui/p/6925810.html
Copyright © 2020-2023  润新知