javah是用來幹嘛的呢?
它是用來生成C語音的頭文件的。
通過一個helloworld看一下 javah的作用吧:
原來我們新建一個項目後,自己寫C代碼:
#include <stdio.h>
#include <jni.h>
jstring Java_com_itheima15_ndk1_MainActivity_helloFromJNI(JNIEnv* env, jobject obj){
//輸出一個java字符串
//返回一個java字符串
//jstring (*NewStringUTF)(JNIEnv*, const char*);
char* cstr = "helloFromJNI";
return (**env).NewStringUTF(env, cstr);
}
jstring Java_com_itheima15_ndk1_MainActivity_helloFromJNI(JNIEnv* env, jobject obj)
這個方法名要自己寫,挺費勁吧,就算C++功底還算不錯,寫出一個,如果真到項目中,我們java中使用到了十幾甚至幾十個c方法,那就真的hi有的忙活了
javah就是給我們自動生成這玩意兒用的
下面介紹下使用方法:
新建一個android項目,我們先寫佈局和activity
佈局,老規矩:一個按鈕
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="調用C代碼"
android:onClick="click" />
</RelativeLayout>
activity裏面寫一個本地方法(這個是我們需要調用的本地方法)
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends Activity {
static{
System.loadLibrary("Hello");
}
public native String hello();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void click(View view){
//調用c代碼
Toast.makeText(this, hello(), 0).show();
}
}
哦了之後呢,我們本來是要手動的去寫這個C代碼了,但是現在我們使用javah來生成這個所需的頭文件
這個需要注意jdk1.6以下版本和jdk1.7版本是有一點不一樣的
先說1.6版本
進入我們工程的bin目錄下:執行 javah -jni + 寫了調用c方法的那個類的class文件
而1.7版本呢
進入我們工程的src目錄下:執行 javah -jni + 寫了調用c方法的那個類
然後到對應文件夾下就會生成一個對應的 h 文件
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class com_test_MainActivity */
#ifndef _Included_com_test_MainActivity
#define _Included_com_test_MainActivity
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: com_test_MainActivity
* Method: hello
* Signature: ()Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_com_test_MainActivity_hello
(JNIEnv *, jobject);
#ifdef __cplusplus
}
#endif
#endif
那接下來就方便了吧
開始根據這個頭文件來寫對應的c文件
#include <jni.h>
#include "com_test_MainActivity.h"//引入生成的頭文件
#include <android/log.h>
#define LOG_TAG "System.out"
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
JNIEXPORT jstring JNICALL Java_com_test_MainActivity_hello
(JNIEnv * env, jobject obj){
//NewStringUTF()
//return (**env).NewStringUTF(env, "您好 jni");
LOGI("hello");
LOGI("1");
LOGI("2");
return (**env).NewStringUTF(env, "您好 jni");
LOGI("3");
}
接下來的步驟就和上一篇博文一樣啦,交叉編譯,後刷新工程,部署app即可