編輯:Android 開發實例
在 JNI 裡做編碼轉換,最省事的思路其實是「借力打力」——把 C/C++ 端的位元組陣列丟回給 Java 的 java/lang/String,讓虛擬機幫你完成解碼。
這種做法雖然能用,但本質上還是在呼叫 Java 的 String,跨語言往返的開銷躲不掉。真想治本,應該在 native code 裡完整實作轉換邏輯。成熟方案不少,例如開源的 ICU,或者更輕量的 iconv。
值得一提的是,Android 平台自身也採用了 iconv 這套開源庫,只不過它預設並未對外導出符號,需要自行處理連結與宣告問題才能使用。
先看一段最直觀的程式碼,透過 String(byte[] data, String charsetName) 這個建構子完成字串與位元組的互轉:
jstring
MyNewString(JNIEnv *env, const char *chars, jint len)
{
jclass stringClass;
jmethodID cid;
jbyteArray elemArr;
jstring result;
jstring jencoding;
stringClass = env->FindClass("java/lang/String");
if (stringClass == NULL) {
return NULL; /* exception thrown */
}
/* Get the method ID for the String(byte[] data, String charsetName) constructor */
cid = env->GetMethodID(stringClass, "<init>", "([BLjava/lang/String;)V");
if (cid == NULL) {
return NULL; /* exception thrown */
}
jencoding = env->NewStringUTF("GBK");
/* Create a byte[] that holds the string characters */
elemArr = env->NewByteArray(len);
if (elemArr == NULL) {
return NULL; /* exception thrown */
}
env->SetByteArrayRegion(elemArr, 0, len, (jbyte*)chars);
/* Construct a java.lang.String object */
result = (jstring)(env->NewObject(stringClass, cid, elemArr, jencoding));
/* Free local references */
env->DeleteLocalRef(elemArr);
env->DeleteLocalRef(stringClass);
return result;
}
以上寫法參考了《The JavaTM Native Interface Programmer's Guide and Specification》中的範例並加以改寫。說穿了,核心不過是呼叫 java.lang.String 的方法而已。
下面把兩個方向的轉換函式一併貼出,方便日後查閱。
/*
* you can use these functions freely, but please keep this declaration
* with no modified.
*
* created by jerry.lin, 2011-08-04
*/
#include <stdio.h>
#include <jni.h>
#include <string.h>
/*
* convert the char string to JString
* parameter:
* [in] pszSrc: the source string to be converted.
* [in] pszEncoding: the encoding of pszSrc, if it is null, means utf8
*
* return value:
* return the converted string if successful, otherwise return NULL.
*/
jstring CharToJString(JNIEnv* env, const char* pszSrc, const char* pszEncoding)
{
jstring jstr = NULL;
jclass stringClass = NULL;
jbyteArray byteElemArr = NULL;
do {
jmethodID cid = NULL;
jstring jstrEncoding = NULL;
const char* pszEnco = NULL;
int nStrLen = 0;
/* check the income parameters */
if (NULL == pszSrc || NULL == env) {
break;
}
/* get the String class of java */
stringClass = env->FindClass("java/lang/String");
if (NULL == stringClass) {
break;
}
/* Get the method ID for the java.lang.String constructor */
cid = env->GetMethodID(stringClass, "<init>", "([BLjava/lang/String;)V");
if (NULL == cid) {
break;
}
if (NULL == pszEncoding) {
pszEnco = "utf-8";
} else {
pszEnco = pszEncoding;
}
jstrEncoding = env->NewStringUTF(pszEnco);
if (NULL == jstrEncoding) {
break;
}
/* put char string into array of java */
nStrLen = (int)strlen(pszSrc);
byteElemArr = env->NewByteArray(nStrLen);
if (NULL == byteElemArr) {
break;
}
env->SetByteArrayRegion(byteElemArr, 0, nStrLen, (jbyte*)pszSrc);
/* create a new object of java.lang.String with string(byte[], string) */
jstr = (jstring)(env->NewObject(stringClass, cid, byteElemArr, jstrEncoding));
} while (0);
/* Free local references */
if (NULL != byteElemArr) {
env->DeleteLocalRef(byteElemArr);
}
if (NULL != stringClass) {
env->DeleteLocalRef(stringClass);
}
return jstr;
}
/*
* convert the JString to char string
*
* parameter:
* [in] jstr: the source string to be converted.
* [in] pszEncoding: the encoding to which the JString is to be converted.
* [out] pszOutBuf: the buffer to receive the converted string.
* [in] nBufLen: the length of the buffer.
*
* return value:
* the length of the string in bytes copied into pszOutBuf.
*/
int JStringToChar(JNIEnv* env, jstring jstr, const char *pszEncoding,
char* pszOutBuf, int nBufLen)
{
int nRet = -1;
jclass stringClass = NULL;
jbyteArray byteElemArr = NULL;
do {
jmethodID cid = NULL;
jstring jstrEncoding = NULL;
const char* pszEnco = NULL;
int nStrLen = 0;
/* check the income parameters */
if (NULL == jstr || NULL == env) {
break;
}
/* get the String class of java */
stringClass = env->FindClass("java/lang/String");
if (NULL == stringClass) {
break;
}
/* Get the method ID for java.lang.String getBytes(String) */
cid = env->GetMethodID(stringClass, "getBytes", "(Ljava/lang/String;)[B");
if (NULL == cid) {
break;
}
if (NULL == pszEncoding) {
pszEnco = "utf-8";
} else {
pszEnco = pszEncoding;
}
jstrEncoding = env->NewStringUTF(pszEnco);
if (NULL == jstrEncoding) {
break;
}
/* get char string into array with designated encode */
byteElemArr = (jbyteArray)env->CallObjectMethod(jstr, cid, jstrEncoding);
if (NULL == byteElemArr) {
break;
}
nStrLen = (int)(env->GetArrayLength(byteElemArr));
/* return the length of the char string if nBufLen is 0 or pszOutBuf is NULL */
if (0 == nBufLen || NULL == pszOutBuf) {
nRet = nStrLen;
break;
}
/* if nBufLen < nStrLen, return failed */
if (nBufLen < nStrLen) {
nRet = -2;
break;
}
/* copy the byteArray content into the out buffer */
jbyte* pszBytes = env->GetByteArrayElements(byteElemArr, JNI_FALSE);
if (NULL != pszBytes) {
memcpy(pszOutBuf, pszBytes, nStrLen);
pszOutBuf[nStrLen] = 0;
nRet = nStrLen;
}
} while (0);
/* Free local references */
if (NULL != byteElemArr) {
env->DeleteLocalRef(byteElemArr);
}
if (NULL != stringClass) {
env->DeleteLocalRef(stringClass);
}
return nRet;
}
上面這組程式碼在處理純英文或純中文時沒問題,但一旦遇到中英混雜的字串就會出錯,問題出在簽章裡的 char* 參數——它依賴 strlen 求長度,無法表達帶結束符語意的位元組序列。更合適的介面設計應該顯式傳入緩衝區與長度:
jstring CharToJString(JNIEnv* env, const void* pszSrc, int nLen, const char* pszEncoding);
int JStringToChar(JNIEnv* env, jstring jstr, const char *pszEncoding,
void* pszOutBuf, int nBufLen);
實測經驗是:Java 呼叫 native 大約比 Java 呼叫 Java 慢上 2~3 倍。理論上 native 呼叫 Java 應該與前者相當,但由於 Java→native 的使用量遠高於 native→Java,虛擬機對前者的優化投入也更多,因此實測下 native→Java 有可能慢到 10 倍左右。在效能敏感的場景,這筆往返成本值得事先評估。
Android 讀取短信並轉存到 SQLite 的實現
系統短信本身也存在 SQLite 數據庫裡,但出於安全機制,Android 不允許其他應用直接訪問。繞過這個限制的正規做法是利用 ContentProvider:通過 c
Android 九宮格圖文菜單實現:GridView + SimpleAdapter 完整示例
九宮格圖文菜單是很常見的界面形態,實現起來並不複雜,核心就是 GridView 加一個 SimpleAdapter。下面把佈局、適配器與點擊事件串起來走一遍。 一、佈局
Android miniTwitter 登入畫面實作:漸層背景、圓角表單與相對佈局
登入畫面是許多 App 的第一印象。本文以 miniTwitter 登入頁為例,說明如何用漸層背景、圓角容器、相對佈局與表單控制項,做出一個清爽美觀的登入介面。 畫面結構
Android 進階:用 BLE 開發搜索 iBeacon 基站
前文講述了 Android 手機與 BLE 終端之間的通信,而最常見的 BLE 終端,莫過於蘋果公司倡導的 iBeacon 基站。iBeacon 技術基於 BLE,其特點