andorid ndk 各種坑啊 記錄下
阿新 • • 發佈:2017-08-20
sso null enum ptr als tty protect rep oid
android jni代碼回調java的問題
因為多線程原因會導致找不到java類,無法call函數的問題
問題1找不到java類
在JNI_OnLoad的時候 保存下來
JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void* reserved)
{
g_vm = vm;
JNIEnv* env = NULL;
jint result = -1;
if (vm->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK) {
return -1;
}
assert(env != NULL);
register_location_methods(env);
result = JNI_VERSION_1_4;
return result;
}
int register_location_methods(JNIEnv *env)
{
jniEnv = env;
jclass clazz;
clazz = env->FindClass("com/TongBan/Chat/NetBilling");
if (clazz == NULL) {
return -1;
}
JNetBilling = clazz;
onReceivedMsgType = env->GetStaticMethodID(clazz,
"OnReceivedMsgType", "(I)V");
// env->CallStaticVoidMethod(JNetBilling, onReceivedMsgType, 1);
return 0;
}
問題2多線程回調call函數
此處生成的JNIEnv無法獲取到class 函數 等 須要之前保存好的全局變量
bool isAttacked = false;
JNIEnv* env;
int status = g_vm->GetEnv((void **) &env, JNI_VERSION_1_4);
if (status < 0) {
status = g_vm->AttachCurrentThread(&env, NULL);
if (status < 0) {
return len;
}
isAttacked = true;
}
env->CallStaticVoidMethod(JNetBilling,onReceivedMsgType,iMsgType);
if (isAttacked) {
g_vm->DetachCurrentThread();
}
輸出問題因為還是比較喜歡cout就百度了個cout輸出到logCat日誌的
int iMsgType = MSG_PACKET::GetMsgType(kBuffer);
StreamBuf g_StreamBuf;
std::cout.rdbuf(&g_StreamBuf);
std::cout << iMsgType;//就可以顯示到logCat
#include <iostream>
#include <streambuf>
class StreamBuf : public std::streambuf
{
enum
{
BUFFER_SIZE = 255,
};
public:
StreamBuf()
{
buffer_[BUFFER_SIZE] = ‘\0‘;
setp(buffer_, buffer_ + BUFFER_SIZE - 1);
}
~StreamBuf()
{
sync();
}
protected:
virtual int_type overflow(int_type c)
{
if (c != EOF)
{
*pptr() = c;
pbump(1);
}
flush_buffer();
return c;
}
virtual int sync()
{
flush_buffer();
return 0;
}
private:
int flush_buffer()
{
int len = int(pptr() - pbase());
if (len <= 0)
return 0;
if (len <= BUFFER_SIZE)
buffer_[len] = ‘\0‘;
#ifdef ANDROID
android_LogPriority t = ANDROID_LOG_INFO;
__android_log_write(t, "JNI_DEBUG", buffer_);
#else
printf("%s", buffer_);
#endif
pbump(-len);
return len;
}
private:
char buffer_[BUFFER_SIZE + 1];
};
到這裏 最終能夠 互動了 android->server->android
andorid ndk 各種坑啊 記錄下