对于C++程序员来说使用Qt开发手机app不失为一个好的选择,当Qt不能满足要求时可以调用Android原生代码实现功能,由于Qt的帮助文档有限,相信不少Qt开发者也踩了不少坑
首先创建Qt工程
1.添加Android支持工程pro文件添加
QT += androidextras
2.编写Activity返回值类,派生于
QAndroidActivityResultReceiver,实现返回函数handleActivityResult,通过信号SendData将数据抛出去,代码如下:
ActivityResult .h 文件
#ifndef ACTIVITYRESULT_H
#define ACTIVITYRESULT_H
#include
class ActivityResult : public QObject,public QAndroidActivityResultReceiver
{
Q_OBJECT
signals:
void sendData(QString);
public:
int requestId;
ActivityResult(int id, QObject *parent = nullptr) : QObject(parent), requestId(id) {}
void handleActivityResult(int receiverRequestCode, int resultCode, const QAndroidJniObject &data);
};
#endif // ACTIVITYRESULT_H
ActivityResult .cpp文件
#include
void ActivityResult::handleActivityResult(int receiverRequestCode, int resultCode, const QAndroidJniObject &data)
{
if(receiverRequestCode == requestId)
{
if(resultCode ==-1)
{
QAndroidJniObject name=QAndroidJniObject::fromString("select");
QAndroidJniObject str = data.callObjectMethod("getStringExtra", "(Ljava/lang/String;)Ljava/lang/String;",name.object
if(str==NULL)
{
emit sendData(tr("返回为空"));
return;
}
str.toString();
emit sendData(str.toString());
return;
}
else
{
//some code here
}
}
}
QT端调用代码
//调用Activity
void MainWindow::on_pushButton_clicked()
{
ActivityResult *m_ActivityResult;
QAndroidJniEnvironment env;
if(m_ActivityResult!=NULL)
{
delete m_ActivityResult;
}
m_ActivityResult = new ActivityResult(0);
connect(m_ActivityResult,SIGNAL(sendData(QString)),this,SLOT(sendData(QString)));//连接信号获得返回值
QtAndroid::runOnAndroidThread([=](){
QAndroidJniObject action =
QAndroidJniObject::fromString("org.qtproject.example.HelloWindow.XNActivity");//通用调用名称为org.qtproject.example.HelloWindow.XNActivity 保持和Java中要调用的Activity一致
QAndroidJniObject intent("android/content/Intent","(Ljava/lang/String;)V", action.object
QtAndroid::startActivity(intent, 0, m_ActivityResult);
});
}
void MainWindow::sendData(QString str)
{
QMessageBox::information(NULL, tr("提示"), str,QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);//d窗显示返回的值
}
编译该工程将产生build-工程目录
用Android Studio打开该目录下的android-build
添加要调用的Activity
activity在AndroidManifest.xml中定义
org.qtproject.example.HelloWindow.XNActivity"/>
XNActivity布局代码
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ff0000ff"
>
评论列表(0条)