Search code examples
javaandroidjava-native-interfacecompression

Compress and decompress String in JNI


For a network usage, I need to compress the data exchanged. For better performance, I think it's way better to use Android NDK with JNI. I've tried to do it but without success as I'm not really proficient with C nor JNI.

I've created a Java class:

public class CompressUtils
{
    // Declare native method
    private static native String compressData(String data);
    private static native String decompressData(String data);

    public static String compress(String data)
    {
        return compressData(data);
    }

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

Here is the C header file:

/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class com_my_app_utils_CompressUtils */

#ifndef _Included_com_my_app_utils_CompressUtils
#define _Included_com_my_app_utils_CompressUtils
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     com_my_app_utils_CompressUtils
 * Method:    compressData
 * Signature: (Ljava/lang/String;)Ljava/lang/String;
 */
JNIEXPORT jstring JNICALL Java_com_my_app_utils_CompressUtils_compressData
  (JNIEnv *, jclass, jstring);

/*
 * Class:     com_my_app_utils_DecompressUtils
 * Method:    decompressData
 * Signature: (Ljava/lang/String;)Ljava/lang/String;
 */
JNIEXPORT jstring JNICALL Java_com_my_app_utils_CompressUtils_decompressData
  (JNIEnv *, jclass, jstring);

#ifdef __cplusplus
}
#endif
#endif

And finally the C body:

JNIEXPORT jstring JNICALL Java_com_my_app_utils_CompressUtils_compressData
  (JNIEnv * env, jclass cl, jstring input)
{

}

JNIEXPORT jstring JNICALL Java_com_my_app_utils_CompressUtils_decompressData
  (JNIEnv *env, jclass cl, jstring input)
{

}

I've tried to put some real C code inside put I don't understand what I am supposed to do here and which good compression algorythm exists.

Could your help me to find a good working compression algorythm and the way to use it here ?

Thanks


Solution

  • All you need to do is just use java api implemention. Algorithms implemented in java such as gzip, is natively implemented. Think about how android can read an APK file efficiently without native support?

    For this issue, you can check out zlib, translate jstring to chars via GetStringUTFChars, and compress into compressed chars, then return it in form of byte array rather than string.