Qt6.4获取qml安卓手机路径
时间: 2023-07-22 12:39:00 浏览: 215
使用Qt for android, QML复刻YYets Android客户端
在Qt6.4中获取安卓手机路径的方法与Qt5.x有所不同。以下是获取安卓手机路径的步骤:
1. 引入Qt Android Extras模块。
```qml
import QtAndroid.Extras 1.0
```
2. 添加以下权限到AndroidManifest.xml文件中:
```xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
```
3. 在C++代码中定义一个槽函数,并使用Qt Android Extras模块中的QAndroidJniObject类获取相册路径。例如:
```cpp
void MyObject::getAlbumPath(){
QAndroidJniObject ACTION_PICK = QAndroidJniObject::fromString("android.intent.action.PICK");
QAndroidJniObject externalContentUri = QAndroidJniObject::fromString("content://media/external/images/media");
QAndroidJniObject intent("android/content/Intent", "(Ljava/lang/String;Landroid/net/Uri;)V", ACTION_PICK.object<jstring>(), externalContentUri.object<jobject>());
QtAndroid::startActivity(intent, 101, [this](int requestCode, const QAndroidJniObject& data){
if(requestCode == 101){
QAndroidJniObject uri = data.callObjectMethod("getData", "()Landroid/net/Uri;");
QAndroidJniObject filePath = QAndroidJniObject::callStaticObjectMethod("android/os/Environment", "getExternalStorageDirectory", "()Ljava/io/File;");
filePath = filePath.callObjectMethod("getAbsolutePath", "()Ljava/lang/String;");
QAndroidJniObject resolver = QtAndroid::androidActivity().callObjectMethod("getContentResolver","()Landroid/content/ContentResolver;");
QAndroidJniObject options;
options = QAndroidJniObject::callStaticObjectMethod("android/provider/MediaStore$Images$Media", "query", "(Landroid/content/ContentResolver;Landroid/net/Uri;[Ljava/lang/String;Ljava/lang/String;[Ljava/lang/String;)Landroid/database/Cursor;", resolver.object<jobject>(), uri.object<jobject>(), nullptr, nullptr, nullptr);
jint columnIndex = options.callMethod<jint>("getColumnIndex", "(Ljava/lang/String;)I", QAndroidJniObject::fromString("_data").object<jstring>());
options.callMethod<jboolean>("moveToFirst");
QAndroidJniObject path = options.callObjectMethod("getString", "(I)Ljava/lang/String;", columnIndex);
qDebug() << "Path: " << path.toString();
}
});
}
```
该函数会弹出相册选择界面,用户选择一张图片后,会返回该图片的路径。需要注意的是,该函数只能在Qt Android应用程序中调用,不能在Windows、Linux等平台下测试运行。
以上就是在Qt6.4中获取安卓手机路径的方法。
阅读全文