android 中 c++调用java代码(3)

时间:2022-09-22 09:08:32


基于前两篇文章,自己做了一个测试demo。


android 程序中代码


package com.example.jniccalljava;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.os.Bundle;
import android.view.Menu;

public class MainActivity extends Activity {
String contentString;
public static Context mContext;
static {
System.loadLibrary("test");
}

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = this.getApplicationContext();
callShowMessage();
}

public void showMessage()

{

contentString = getStringFromC();

AlertDialog.Builder builder = new Builder(this);

builder.setTitle(contentString);

builder.setMessage("这是一个C++调用Android的例子");

builder.show();

}

public native String callShowMessage();

public native String getStringFromC();

}


JNI 文件


/*
 * test.cpp
 *
 *  Created on: 2013/12/23
 *      Author: xxxx
 */

#include<string.h>
#include<jni.h>

/*
 * Class:     com_example_jniccalljava_MainActivity
 * Method:    callShowMessage
 * Signature: ()Ljava/lang/String;
 */
extern "C" {
JNIEXPORT jstring JNICALL Java_com_example_jniccalljava_MainActivity_callShowMessage(
  JNIEnv *env, jobject thiz) {

 jmethodID notification_method = env->GetMethodID(env->GetObjectClass(thiz),
   "showMessage", "()V");

 env->CallVoidMethod(thiz, notification_method);

 return 0;

}

/*
 * Class:     com_example_jniccalljava_MainActivity
 * Method:    getStringFromC
 * Signature: ()Ljava/lang/String;
 */
JNIEXPORT jstring JNICALL Java_com_example_jniccalljava_MainActivity_getStringFromC(
  JNIEnv *env, jobject thiz) {

 return env->NewStringUTF("callCMessageBox");

}

}


Android.mk 文件



LOCAL_PATH := $(call my-dir)
 
include $(CLEAR_VARS)
 
LOCAL_MODULE    := test
 
LOCAL_SRC_FILES := ./test.cpp
include $(BUILD_SHARED_LIBRARY)


运行效果如下:


android 中 c++调用java代码(3)