在用Qt开发android应用的时候,有一个需求是通过调用android原生接口去实现图片分享功能,原理很简单,首先在java文件中用android接口封装一个分享功能的方法,然后在C++中调用QAndroidJniObject::callStaticMethod即可。
首先,如果是一个新创建的Qt工程,需要创建一个AndroidManifest.xml文件,创建过程不再赘述,然后创建一个Java的类,继承于
public class MainActivity extends org.qtproject.qt5.android.bindings.QtActivity
然后定义一个公有的静态函数
/**
* 分享功能
*/
//分享单张图片
public static void shareImage(String title,
String path, QtActivity activity)
{
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/png");
File file = new File(path);
share.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
activity.startActivity(Intent.createChooser(share, title));
}
其中,title是分享对话框的显示标题,path是要分享的图片的保存位置
当然,还可以分享单独的文字内容,如下
public static void shareString(String title,
String content, QtActivity activity)
{
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("text/plain");//分享字符串
share.putExtra(Intent.EXTRA_TEXT, content);
activity.startActivity(Intent.createChooser(share, title));
}
//分享多张图片
public static void shareImages(String title,
String imagesPath,QtActivity activity)
{
String[] pathList = imagesPath.split("\\|"); //由于"|"是转义字符,所以不能直接写 "|"做分割
ArrayList imagesUriList = new ArrayList();
for(int i = 0 ; i < pathList.length ; ++i){
File file = new File(pathList[i]);
if(file.isFile())
{
imagesUriList.add(Uri.fromFile(file));
}
}
Intent intent = new Intent(Intent.ACTION_SEND_MULTIPLE);
intent.setType("image/*");
intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, imagesUriList);
intent.putExtra(Intent.EXTRA_SUBJECT, title);
activity.startActivity(Intent.createChooser(intent, title));
}
接下来看看C++端的调用方式
单张图片分享
void AndroidInterface::share(const QString &title, const QString &path)
{
QAndroidJniObject jTitle = QAndroidJniObject::fromString(title);
QAndroidJniObject jPath = QAndroidJniObject::fromString(path);
QAndroidJniObject activity = QtAndroid::androidActivity();
QAndroidJniObject::callStaticMethod(
"com/lyy/test/MainActivity",
"shareImage",
"(Ljava/lang/String;Ljava/lang/String;Lorg/qtproject/qt5/android/bindings/QtActivity;)V",
jTitle.object(),
jPath.object(),
activity.object());
}
void AndroidInterface::shareImages(const QString &title, const QStringList &imagesPathList)
{
QString imagesPath;
foreach (QString str, imagesPathList) {
imagesPath += str + "|";
}
imagesPath = imagesPath.remove(imagesPath.size() - 1,1).trimmed();
QAndroidJniObject jTitle = QAndroidJniObject::fromString(title);
QAndroidJniObject jPathList = QAndroidJniObject::fromString(imagesPath);
QAndroidJniObject activity = QtAndroid::androidActivity();
QAndroidJniObject::callStaticMethod(
"com/lyy/airlink/MainActivity",
"shareImages",
"(Ljava/lang/String;Ljava/lang/String;Lorg/qtproject/qt5/android/bindings/QtActivity;)V",
jTitle.object(),
jPathList.object(),
activity.object());
}