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

标签 android c++ bluetooth android-ndk java-native-interface

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

在 java 中:BluetoothAdapter.getDefaultAdapter().getName()

我知道我可以将它包装在一个 java 函数中,我通过 jni 调用它,但是,我怎样才能在 C++ 中实现相同的功能,只有 jni/android-ndk?

最佳答案

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

添加到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);

关于android - 从 JNI/C++ 获取 Android 蓝牙适配器名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28991228/

相关文章:

android - 删除幻灯片窗口转换在启动时创建的白屏

android - java.lang.RuntimeException : Unable to start activity 错误

c++ - 使用 clang 的功能检查宏来检测 std::launder 的存在

Android:隐藏配对对话框

audio - 如何将蓝牙音频 A2DP 路由到音频设备 MediaStream 中? (来自 Electron 应用程序)

java - 在 PC 上从 RFCOMM 接收字符串,从 Android 发送

android - 关闭android中的整个应用程序

android - Android 和 App Engine 实际上是如何通信的?

c++ - 如何创建以当前时间命名的文件?

c++ - `Counter::metaObject() const'的多重定义