Home > Back-end >  How can I get the Android IMEI code in Qt?
How can I get the Android IMEI code in Qt?

Time:10-22

I have run the following code in the qt program and the jstr value is null.

I added the [androidextras] in the .pro file. I added the [READ_PHONE_STATE] Permission in the Androidmanifest.xml. I have run this app on Android 12.

Please advise why the value of jstr is null? If there is a better way, please help me.

I want when the user logs in, user can no longer run the program with the same ID on another device, or a part of the program cannot be run?

this code:

#include <QAndroidJniObject>
#include <QAndroidJniEnvironment>
#include <QtAndroid>

void getDeviceImei()
{
    QAndroidJniEnvironment env;

    jclass contextClass = env->FindClass("android/content/Context");
    jfieldID fieldId = env->GetStaticFieldID(contextClass, "TELEPHONY_SERVICE",       "Ljava/lang/String;");
    jstring telephonyManagerType = (jstring) env->GetStaticObjectField(contextClass, fieldId);

    jclass telephonyManagerClass = env->FindClass("android/telephony/TelephonyManager");
    jmethodID methodId = env->GetMethodID(contextClass, "getSystemService", "(Ljava/lang/String;)Ljava/lang/Object;");

    QAndroidJniObject qtActivityObj = QAndroidJniObject::callStaticObjectMethod("org/qtproject/qt5/android/QtNative",  "activity", "()Landroid/app/Activity;");
    jobject telephonyManager = env->CallObjectMethod(qtActivityObj.object<jobject>(), methodId, telephonyManagerType);

    methodId = env->GetMethodID(telephonyManagerClass, "getDeviceId", "()Ljava/lang/String;");
    jstring jstr = (jstring) env->CallObjectMethod(telephonyManager, methodId);

    qDebug() << "## methodId -->> " << methodId;
    qDebug() << "## jstr -->> " << jstr;    // NULL

    jsize len = env->GetStringUTFLength(jstr);
    char* buf_devid = new char[32];
    env->GetStringUTFRegion(jstr, 0, len, buf_devid);
    QString imei(buf_devid);

    qDebug() << "## imei -->> " << imei;

}

CodePudding user response:

GetDeviceId is deprecated. It should be getIMEI now. But either way it won't work- you need READ_PRIVILEGED_PHONE_STATE instead of READ_PHONE_STATE. The PRIVLIDGED version only works for system apps- you need to either be preinstalled or root your phone to turn the app into a privlidged app. You can not get this data as a normal app.

This change was due to privacy concerns. Pretty much any unique id on the device is now either randomized per app install, or removed entirely. This is so you can't track someone across installs (unless they make an account with you).

  • Related