在用Qt开发android应用的时候碰到这样的需求,点击某按钮后将程序最小化,也就是说将其移到后台运行,程序本身没有退出,这相当于点击了Home键。而当程序收到某个广播后又将后台运行的程序打开显示到最前端,原理很简单,同样还是先通过android接口实现相应功能,然后在C++端调用。

首先,如果是一个新创建的Qt工程,需要创建一个AndroidManifest.xml文件,创建过程不再赘述,然后创建一个Java的类,继承于


public class MainActivity extends org.qtproject.qt5.android.bindings.QtActivity

定义一个公有的静态函数

最小化,将程序移到后台:

public static void mini()
{
m_instance.moveTaskToBack(true);
}

其中m_instance是本窗口对象this


将软件移到前台

public static void moveTaskToFrount(){
if(!m_instance.isForeground(m_instance.getPackageName()))
{
ActivityManager am = (ActivityManager)m_instance.getSystemService(Context.ACTIVITY_SERVICE);
am.moveTaskToFront(m_instance.getTaskId(),0);
}

}
private boolean isForeground(String packageName){

ActivityManager activityManager = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);

List<RunningAppProcessInfo> appProcesses = activityManager
.getRunningAppProcesses();
if (appProcesses == null)
return false;

for (RunningAppProcessInfo appProcess : appProcesses) {
// The name of the process that this object is associated with.
if (appProcess.processName.equals(packageName)
&& appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
return true;
}
}

return false;

}

需要导入包

import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.ActivityManager.RunningAppProcessInfo;



然后看C++ 调用

void AndroidInterface::showMini()
{
QAndroidJniObject::callStaticMethod<void>(
"com/lyy/test/MainActivity",
"mini",
"()V");
}
void AndroidInterface::moveToFront()
{
QAndroidJniObject::callStaticMethod<void>(
"com/lyy/test/MainActivity",
"moveTaskToFrount",
"()V");
}