Ubuntu下如何写简单的jni

来源:互联网 发布:淘宝客邮件推广 编辑:程序博客网 时间:2024/06/11 09:52

在网上面的关于在eclipse下使用ndk的例子太多了,今天我想写下在android studio下生成so的例子。
系统:Ubuntu14.04
IDE:android studio

首先建一个android studio的android项目,com.example.myndk
这里写图片描述

然后就开始写C吧:
首先在项目与src同目录下新建文件jni,然后放入这三个文件:
这里写图片描述

android.mk:

LOCAL_PATH:=${call my-dir}include $(CLEAR_VARS)LOCAL_MODULE :=name    //name os库名LOCAL_SRC_FILES:=name.c  //name.c 你编辑的C文件名include $(BUILD_SHARED_LIBRARY)

我的文件内容如下:

# Copyright (C) 2009 The Android Open Source Project## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at##      http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.#LOCAL_PATH := $(call my-dir)include $(CLEAR_VARS)LOCAL_MODULE    := MyNDKLOCAL_SRC_FILES := MyNDK.cinclude $(BUILD_SHARED_LIBRARY)

Application.mk;

APP_ABI := all

MyNDK.c:

#include <jni.h>#include <stdio.h>  jstringJava_com_example_myndk_MyNDK_print  (JNIEnv *env, jobject obj) {    printf("the project which i write is prepared for java-ndk");    return (*env)->NewStringUTF(env, "Hello from JNI ! ");}

然后在此目录下,
这里写图片描述
终端:

ndk-build

就会生成libs,里面有各种so库。
这个时候重启studio,进入bulid.gradle(Module:app)
android{}中插入:

sourceSets{        main{            jniLibs.srcDirs = ['libs']        }    }

sync now

就可以看到jniLibs下的sso库了
这里写图片描述

那么测试下:

Toast.makeText(this, print(), Toast.LENGTH_LONG).show();

截图:
这里写图片描述

It’s ok ,但是我在c里面有这样一句:

printf("the project which i write is prepared for java-ndk");

到底打印到了哪里呢?
还在查找中

0 0
原创粉丝点击