从 JNI/C++ 获取 Android 蓝牙适配器名称

Getting Android Bluetooth Adapter Name from JNI/C++

本文关键字:适配器 Android JNI C++ 获取      更新时间:2023-10-16

问题的Android API是android.bluetooth.BluetoothAdapter,它有一个成员函数getName()返回适配器的用户友好名称。

在爪哇中:BluetoothAdapter.getDefaultAdapter().getName()

我知道我可以把它包装在一个java函数中,我通过jni调用它,但是,我如何在C++中实现相同的目标,只有jni/android-ndk?

首先,您需要具有读取此值的权限(无论它是本机值,您都需要该权限)。

添加到AndroidManifest.xml

<uses-permission android:name="android.permission.BLUETOOTH"/>

在原生jni土地上,事情有点麻烦。简而言之,这就是您需要的:

  1. 获取班级android.bluetooth.BluetoothAdapter
  2. 获取静态方法BluetoothAdapter.getDefaultAdapter()
  3. 获取方法BluetoothAdapter.getName()

为了:

  1. 1上调用2以获取默认BluetoothAdapter实例
  2. 4. 调用实例上的getName()以获取适配器的名称。

这与java单行相同,只是分解了。


代码(假设您已经有一个JNIEnv对象):

// 1. Get class
// The path matches the package hierarchy of
// 'android.bluetooth.BluetoothAdapter'
jclass classBta = env->FindClass("android/bluetooth/BluetoothAdapter");
// 2. Get id of the static method, getDefaultAdapter()
// Search the web for 'jni function signature' to understand
// the third argument. In short it's a function that takes no arguments,
// hence '()', and returns an object of type
// android.bluetooth.BluetoothAdapter, which uses syntax "L{path};"
jmethodID methodIdGetAdapter =
    env->GetStaticMethodID(classBta,
                           "getDefaultAdapter",
                           "()Landroid/bluetooth/BluetoothAdapter;");
// 3. Get id of the non-static method, getName()
// The third argument is the getName function signature,
// no arguments, and returns a java.lang.String object.
jmethodID methodIdGetName =
    env->GetMethodID(classBta,
                     "getName",
                     "()Ljava/lang/String;");
// 4. We get the instance returned by getDefaultAdapter()
jobject objBta = (jobject)
    env->CallStaticObjectMethod(classBta, methodIdGetAdapter);
// 5. Call member method getName on instance
jstring strName = (jstring)
    env->CallObjectMethod(objBta, methodIdGetName);
// Convert jstring to a regular string
const char *result = env->GetStringUTFChars(strName, 0);
std::string blueToothName(result);

为了清楚起见,我省略了明智的检查以查看各种功能是否成功,并进行了清理:

env->DeleteLocalRef(classBta);
env->DeleteLocalRef(objBta);
env->DeleteLocalRef(strName);
env->ReleaseStringUTFChars(strName, result);