新线程中的Java环境变量导致的错误

时间:2016-03-15 11:19:39

标签: java android c java-native-interface audiorecord

我的应用程序需要将java层中audiorecord录制的样本发送到JNI。

但为了多次避免内存操作(复制),我在Native层初始化期间创建了缓冲区,并将其传递给java层,如下所示。

Application.c

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

#include <android/log.h>
#include "Application.h"

JNIEnv *Native_env;
jobject native_obj;

jmethodID WriteID, ReadID;
jclass JavaClass;
jshortArray ShortArray;

FILE *read_fptr;
//jsize start = 0;
//jsize leng = 0;
jshort NativeArray[1920];

void Update_NativeJNVVariables(JNIEnv *env, jobject obj)
{
    Native_env = (JNIEnv * )env;
    native_obj = obj;

    //ShortArray = (*Native_env)->NewShortArray(Native_env, 1920);

    //leng = (*Native_env)->GetArrayLength(Native_env,ShortArray);

    //__android_log_print(ANDROID_LOG_ERROR, "Update_NativeJNVVariables", "Length of array is %d", leng);

    memset(NativeArray, 0x00, sizeof(NativeArray));

    //(*Native_env)->SetShortArrayRegion(Native_env,ShortArray, start, leng, NativeArray);

    //jclass LocalClass;
    //LocalClass = (*Native_env)->GetObjectClass(Native_env,native_obj);
    //WriteClass = (*Native_env)->NewGlobalRef(Native_env,LocalClass);

    JavaClass = (*Native_env)->FindClass(Native_env, "com/consilient/tech/uday/javaapi/MainActivity");

    //LocalClass = (*Native_env)->GetObjectClass(Native_env,native_obj);
    //ReadClass = (*Native_env)->NewGlobalRef(Native_env,LocalClass);

   if(JavaClass != NULL)
   {
       WriteID = (*Native_env)->GetMethodID(Native_env,JavaClass,"WriteAndroidPCM","([B)V");
   }

   if(JavaClass != NULL)
   {
       //ReadID = (*Native_env)->GetMethodID(Native_env,JavaClass,"ReadAndroidPCM","([SI)V");
       ReadID = (*Native_env)->GetMethodID(Native_env,JavaClass,"ReadAndroidPCM","(I)V");
   }

    read_fptr = fopen("/sdcard/outputs/read_file.pcm","wb");
    if(read_fptr == NULL)
   {
        __android_log_print(ANDROID_LOG_ERROR, "UPdateJavaEnv", "Read FIle Cannot Be opened");
   }
}

void ReadPCMSamples(short *Buffer, int no_of_samples)
{
    //    jboolean isCopy = JNI_TRUE;
    //    jshort *ArrayPointer = (*Native_env)->GetShortArrayElements(Native_env,ShortArray, &isCopy);

    if(ReadID)
        (*Native_env)->CallVoidMethod(Native_env,JavaClass,ReadID,no_of_samples);

    //fwrite(ArrayPointer, sizeof(short), 160, read_fptr);

    //(*Native_env)->ReleaseShortArrayElements( Native_env, ShortArray, ArrayPointer, 0 );

    //(*Native_env)->GetDirectBufferAddress(Native_env,native_obj);

    //GetByteArray(Buffer, no_of_samples);
}

/*
 * Class:     com_consilient_tech_uday_javaapi_MainActivity
 *  Method:    StartNativeThread
 * Signature: ()V
 */
JNIEXPORT void JNICALL Java_com_consilient_tech_uday_javaapi_MainActivity_FillNativeBuffer
    (JNIEnv *env, jobject obj, jshortArray Buffer, int no_of_samples)
{
      jboolean isCopy = JNI_TRUE;
      jshort *ArrayPointer = (*Native_env)->GetShortArrayElements(Native_env, Buffer, 0);
/*
        for (int i = 0; i < no_of_samples; i++)
        {
            NativeArray[i] = ArrayPointer[i];
        }
*/
         (*Native_env)->ReleaseShortArrayElements( Native_env, Buffer, ArrayPointer, 0 );
    }

int ifReceivedExit = 0;

void Start()
{
    while(ifReceivedExit == 0)
    {
        ReadPCMSamples(NativeArray,160);
    }
}

void Stop()
{
    ifReceivedExit = 1;
}

pthread_t threadID;

void StartThread()
{
int res  = 0;
res = pthread_create(&threadID, NULL, Start, NULL);
if (res != 0)
    __android_log_print(ANDROID_LOG_ERROR, "Thread Creation", "Failed %s", strerror(res));
else
    __android_log_print(ANDROID_LOG_ERROR, "Thread Creation", "Success"); // Thread ID %x res %d", threadID, res);
}

void StopThread()
{
    Stop();
    if(JavaClass)
        (*Native_env)->DeleteGlobalRef(Native_env,JavaClass);

    if(read_fptr)
       fclose(read_fptr);
}

jint JNI_OnLoad(JavaVM* vm, void* reserved)
{
    return JNI_VERSION_1_6;
}

MainActivity.java

public class MainActivity extends AppCompatActivity 
{
     @Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    InitializeJNI();
}

public void ReadAndroidPCM(int no_of_samples)
{
    int read_samples = audioRecord.read(ReadBuffer, 0, no_of_samples);

    FillNativeBuffer(ReadBuffer,no_of_samples);

    //WriteRecordedDataToFile(ReadBuffer, read_samples, READ);
}

static
{
    System.loadLibrary("VajraAPI");
}

public native void InitializeJNI();
public native void StartNativeThread();
public native void StopNativeThread();
public native void FillNativeBuffer(short[] Buffer, int no_of_samples);
}

MainActivity.c

#include <jni.h>

#include "com_consilient_tech_uday_javaapi_MainActivity.h"
#include "Application.h"

/*
* Class:     com_consilient_tech_uday_javaapi_MainActivity
* Method:    InitializeJNI
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_com_consilient_tech_uday_javaapi_MainActivity_InitializeJNI
    (JNIEnv *env, jobject obj)
{
Update_NativeJNVVariables(env, obj);
}

/*
* Class:     com_consilient_tech_uday_javaapi_MainActivity
* Method:    StartNativeThread
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_com_consilient_tech_uday_javaapi_MainActivity_StartNativeThread
    (JNIEnv *env, jobject obj)
{
StartThread();
}

/*
* Class:     com_consilient_tech_uday_javaapi_MainActivity
* Method:    StartNativeThread
* Signature: ()V
*/
JNIEXPORT void JNICALL Java_com_consilient_tech_uday_javaapi_MainActivity_StopNativeThread
    (JNIEnv *env, jobject obj)
{
StopThread();
}

/*
* Class:     com_consilient_tech_uday_javaapi_MainActivity
* Method:    GetByteArrayFromNative
* Signature: (SI)V
*/
JNIEXPORT void JNICALL Java_com_consilient_tech_uday_javaapi_MainActivity_GetByteArrayFromNative
    (JNIEnv *env, jobject obj, jint no_of_samples)
{
//GetByteArray(no_of_samples);
}

当我试图找到错误时,它会在GetShortArrayRegion崩溃,从而产生分段错误

由于

1 个答案:

答案 0 :(得分:0)

感谢Michael提供的链接。

问题是缓存Java Native Environment Variable(正如您指定的那样)。

不应该缓存环境,而可以使用NewGlobalRef方法将类设置为全局,这也有助于在其他线程中使用该类。方法ID也可以是全局的。

最好在JNI_OnLoad中获取Class和MethodID,并为其创建全局引用。

当我们创建一个新线程时,我们需要将新线程附加到Java VM。 并获得JNI Env进行进一步处理。