Lucian
Lucian

Reputation: 894

I want to start an apk from my Qt under Android application(Neccesitas sdk)

My goal is to start an apk already installed on my Android device when pressing a button from my application written in Qt under Andoird(Neccesitas sdk). In Qt under Windows this was done simply by using QProcess like:

m_processP = new QProcess;
m_processP->start ( "somthing.exe" );
.....

But on Android it seems that it does not work like that. I'm trying also with QProcess...start("Settings.apk") but i always got the error: ProcessError::FailedToStart. Has somebody encountered the same issues like me? Thank you

Upvotes: 1

Views: 1821

Answers (2)

Aleksey Kontsevich
Aleksey Kontsevich

Reputation: 5011

Uh, googled through the tons of resources here and on Qt forum finally puzzled a solution from many sources to run an application:

C++ code:

Q_INVOKABLE void start(const QString &packageName)
{
    QAndroidJniObject javaPackageName = QAndroidJniObject::fromString(packageName);
    bool success = (bool)QAndroidJniObject::callStaticMethod<jboolean>(
                "com/mycompany/myapp/PackageActivity",
                "runApplication",
                "(Ljava/lang/String;)Z",
                javaPackageName.object<jstring>());

    if(!success) {
        qDebug() << "Error:" << packageName << "package not found!";
    }
}

Java code:

package com.mycompany.myapp;

import android.content.pm.PackageManager;
import android.content.Intent;
import android.content.Context;
import android.app.Activity;

public class PackageActivity
{
    public static boolean runApplication(String packageName)
    {
        Activity activity = org.qtproject.qt5.android.QtNative.activity();
        PackageManager pm = activity.getApplicationContext().getPackageManager();
        Intent intent = pm.getLaunchIntentForPackage(packageName);
        if (intent != null) {
            activity.startActivity(intent);
            return true;
        } else {
            return false;
        }
    }
}

Main problems were

  • to get working Activity object
  • and then call getPackageManager() on proper object as method was returning following error to me called on arbitrary created Acivity and Context objects:

java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.pm.PackageManager android.content.Context.getPackageManager()' on a null object reference

Upvotes: 2

Fenix Voltres
Fenix Voltres

Reputation: 3448

Things are not so simple on Android. You have to know package and an Activity names you want to run (on Android "application" consists of Activities, and you can only display them, not "run"). You must do it via JNI call (from C++ to Java), and try to start an instance of desired Activity from there. It's a bit complex.

Read more about starting entry activity from other app here, ans about JNI calls here.

Upvotes: 1

Related Questions