从 JNI/C++ 获取 Android 蓝牙适配器名称
Getting Android Bluetooth Adapter Name from JNI/C++
有
问题的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
土地上,事情有点麻烦。简而言之,这就是您需要的:
- 获取班级
android.bluetooth.BluetoothAdapter
- 获取静态方法
BluetoothAdapter.getDefaultAdapter()
- 获取方法
BluetoothAdapter.getName()
为了:
- 在
1
上调用2
以获取默认BluetoothAdapter
实例 - 从
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);
相关文章:
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 为什么 STL 容器适配器堆栈中的 top 返回常量引用?
- 创建包装升压适配器的自定义范围类
- 在 C++20 中将多个范围适配器连接到一个范围中
- 使用 适用于 Android 和 iOS 的 tf-lite C++ API
- 递归应用 C++20 范围适配器会导致编译时无限循环
- Lambda 到函数指针适配器的理解
- 返回迭代器以提升适配器转换的容器
- 将 Kleene 运算符解析为一组替代方案,适配器? 与精神 x3
- Boost Range适配器制作集合
- 升压范围适配器
- DXGI 集成适配器
- 克隆设计模式适配器 - 避免切片子项(类似于原型模式)
- 为什么不支持容器适配器中元素的初始化和迭代
- C++ 提升范围:any_range和转换适配器
- 用于隐藏结构细节的迭代器适配器
- 如何在 DirectX 11 应用程序中提供选择图形适配器的选项?
- 适配器模式:支持可以是const或非const的基础数据,优雅
- 如何对VC 17/20的分配适配器现代化
- 从 JNI/C++ 获取 Android 蓝牙适配器名称