Reputation: 153
I wrote a method that gets the android ID in NDK
void getAndroidID(JNIEnv *env, jobject context, char *deviceId){
int android_id_len = 16;
//Get the Setting.Secure class and the Context Class
jclass c_settings_secure = (*env)->FindClass(env, "android/provider/Settings$Secure");
jclass c_context = (*env)->FindClass(env,"android/content/Context");
if(c_settings_secure == NULL || c_context == NULL){
return;
}
//Get the getContentResolver method
jmethodID m_get_content_resolver = (*env)->GetMethodID(env, c_context, "getContentResolver",
"()Landroid/content/ContentResolver;");
if(m_get_content_resolver == NULL){
return;
}
//Get the Settings.Secure.ANDROID_ID constant
jfieldID f_android_id = (*env)->GetStaticFieldID(env, c_settings_secure, "ANDROID_ID", "Ljava/lang/String;");
if(f_android_id == NULL){
return;
}
jstring s_android_id = (*env)->GetStaticObjectField(env, c_settings_secure, f_android_id);
//create a ContentResolver instance context.getContentResolver()
jobject o_content_resolver = (*env)->CallObjectMethod(env, context, m_get_content_resolver);
if(o_content_resolver == NULL || s_android_id == NULL){
return;
}
//get the method getString
jmethodID m_get_string = (*env)->GetStaticMethodID(env, c_settings_secure, "getString",
"(Landroid/content/ContentResolver;Ljava/lang/String;)Ljava/lang/String;");
if(m_get_string == NULL){
return;
}
//get the Android ID
jstring android_id = (*env)->CallStaticObjectMethod(env, c_settings_secure,
m_get_string,
o_content_resolver,
s_android_id);
(*env)->GetStringUTFRegion(env, android_id, 0, android_id_len, deviceId);
deviceId[android_id_len] = '\0';
LOGI("deviceId %s", deviceId);
}
I tested this code in several phones and it works in all of them with the exception on one phone where I get a StringIndexOutOfBoundsException
java.lang.StringIndexOutOfBoundsException: length=15; regionStart=0; regionLength=16
when I invoke the GetStringUTFRegion
method.
Why I am getting the exception and what can I do to fix it?
Upvotes: 1
Views: 1093
Reputation: 2711
It seems like you are asking to translate more characters than there are in the string - android_id_len
has a hard-coded value of 16, whereas the string in this case is 15, as the error message says. Make sure you calculate the correct length of the string and pass that length to GetStringUTFRegion
, and this way you code will be cross-device generic.
Upvotes: 1