android c java,Android中C ++与Java之间的通信

本文介绍了如何在不使用JNI的情况下,从C++原生代码直接调用Android Java方法。作者分享了通过链接库和第三方工具如Swig来实现这一目标,并提供了一个简单的示例代码片段,展示了如何在C++中调用Java的getCurrentActivityName方法。此外,还提到了Android官方NDK样本和相关GitHub资源作为学习参考。
摘要由CSDN通过智能技术生成

I want to call a java method from C++ file in native code in Android. I know, we can achieve this from JNI but in that case the, I need to initiate the call from Java, which will not fit in my requirements.

I need to call a method written in Java from main() function in C++.

So is there any other approach to achieve this without JNI?

If I can achieve exact this thing using JNI, please let me know how?

Thanks in advance.

Thank You,

Maulik

解决方案

Did you check this:

https://developer.android.com/ndk/samples/sample_hellojni.html

I basically learned from there.

Or:

1. https://github.com/sureshjoshi/android-ndk-swig-example.

2. https://github.com/googlesamples/android-ndk.

A simple search would have gotten you in all these places.

EDIT

Now, once you are done with this and it works well next you call from C/C++:

Calling a java method from c++ in Android. The

Snippet that should help you is:

#include

#include

//other imports

jstring get_package_MainActivity_getJniString( JNIEnv* env, jobject obj){

jstring jstr = (*env)->NewStringUTF(env, "MainActivity class");

jclass clazz = (*env)->FindClass(env, "com/org/android/ui/activities/MainActivity");

jmethodID mCurrentActivityId = (*env)->GetMethodID(env, clazz, "getCurrentActivityName", "(Ljava/lang/String;)Ljava/lang/String;");

jobject result = (*env)->CallObjectMethod(env, obj, mCurrentActivityId, jstr);

const char* str = (*env)->GetStringUTFChars(env,(jstring) result, NULL); // should be released but what a heck, it's a tutorial :)

printf("%s\n", str);

return (*env)->NewStringUTF(env, str);

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值