如何使用QtAndroid :: startActivity

Mar*_*Guo 6 qt android

新的Qt Android extra有一个新功能.QtAndroid :: startActivity

我不知道如何在C++代码中设置fisrt参数.有人可以举个例子吗?非常感谢你.

K9s*_*pud 0

您必须构建一个包含 Android“Intent”对象的 JNI 对象。在 Java 中创建 Intent 对象相当容易,但我不知道如何在 C++ 中做到这一点。

因此,我的解决方案是向我的 Qt 项目添加一个 .java 文件,并在 Java 中创建一个小辅助函数,该函数将为我生成并返回一个 Android Intent 对象:

package com.k9spud.FileBrowser;

import java.io.File;
import android.net.Uri;
import android.content.Intent;

public class AndroidAction
{
    public static Intent openFile(String filePath, String fileType)
    {
        File f = new File(filePath);
        Uri uri = Uri.fromFile(f);
        Intent intent = new Intent();
        intent.setAction(android.content.Intent.ACTION_VIEW);
        intent.setDataAndType(uri, fileType);
        return intent;
    }
}
Run Code Online (Sandbox Code Playgroud)

(您可以在这里阅读有关 Android Intents 的更多信息:https ://developer.android.com/guide/components/intents-filters )

现在我有了 Java 辅助函数,我可以从 C++ 代码发出 JNI 调用来使用我的辅助函数。Java 代码将生成所需的 Intent 对象,我最终将能够使用 QtAndroid::startActivity()。

这是我用来在外部 Android 应用程序中打开(查看)文件的 C++ 函数:

void openFile(QString filePath, QString fileType)
{
    QAndroidJniObject jfilePath = 
    QAndroidJniObject::fromString(filePath);
    QAndroidJniObject jfileType = 
    QAndroidJniObject::fromString(fileType);
    QAndroidJniObject intent = QAndroidJniObject::callStaticObjectMethod("com/k9spud/FileBrowser/AndroidAction",
                                                                     "openFile",
                                                                     "(Ljava/lang/String;Ljava/lang/String;)Landroid/content/Intent;",
                                                                     jfilePath.object<jstring>(),
                                                                     jfileType.object<jstring>());

    QtAndroid::startActivity(intent, 0);
}
Run Code Online (Sandbox Code Playgroud)

例如,为了显示视频文件,我调用 C++ openFile() 函数,传递所需文件的完整路径和 MIME 类型,该类型向 Android 指示应将哪些应用程序作为查看此文件的可能方式呈现:

openFile("/storage/emulated/legacy/Movies/myvideo.mp4", "video/mp4");
Run Code Online (Sandbox Code Playgroud)