Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Qt failed to write external SD card on Android



  • When using Qt on Android, I found that the external SD card can be read but cannot be written. I applied for write permission when using it.AndroidManifest.xml has set <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

    main.cpp

    #include <QGuiApplication>
    #include <QQmlApplicationEngine>
    #include <QtQuick/QQuickView>
    #include <QQmlContext>
    #include <QDebug>
    #include <QFile>
    #include <QtAndroid>

    bool checkPermission() {
    QtAndroid::PermissionResult r = QtAndroid::checkPermission("android.permission.WRITE_EXTERNAL_STORAGE");
    if(r == QtAndroid::PermissionResult::Denied) {
    QtAndroid::requestPermissionsSync( QStringList() << "android.permission.WRITE_EXTERNAL_STORAGE" );
    r = QtAndroid::checkPermission("android.permission.WRITE_EXTERNAL_STORAGE");//READ_EXTERNAL_STORAGE
    if(r == QtAndroid::PermissionResult::Denied) {
    return false;
    }
    }
    return true;
    }

    int main(int argc, char *argv[])
    {
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
    QGuiApplication app(argc, argv);
    QQmlApplicationEngine engine;
    checkPermission();

    const QUrl url(QStringLiteral("qrc:/main.qml"));
    QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
                     &app, [url](QObject *obj, const QUrl &objUrl) {
        if (!obj && url == objUrl)
            QCoreApplication::exit(-1);
    }, Qt::QueuedConnection);
    engine.load(url);
    
    QString string = findSDCardStr();
    QFile* file=new QFile(string + "/test.txt");
    if (file->exists()) {
        if(file->open(QIODevice::WriteOnly))
            qDebug()<<"true";
        else
           qDebug()<<"false";
    }
    return app.exec();
    

    }



  • I found that QtAndroid setting permissions on the external SD card did not work, so I used java, but the first time I put the file in the root directory, it also prompted the file to have no permissions until I saw this https://stackoverflow. com/questions/43349110/android-write-on-external-sd-card-java-io-ioexception-permission-denied found the new folder path, and then I tried it and it can be used



  • I found that QtAndroid setting permissions on the external SD card did not work, so I used java, but the first time I put the file in the root directory, it also prompted the file to have no permissions until I saw this https://stackoverflow. com/questions/43349110/android-write-on-external-sd-card-java-io-ioexception-permission-denied found the new folder path, and then I tried it and it can be used


Log in to reply