描述
当需要访问到设备硬件时, 涉及到Android权限,所以需要进行权限申请, 申请完之后访问常常发现权限不足, 为什么呢?
1. 从Qt库角度看问题:
无论是 QCoreApplication::requestPermission
[since 6.5] template void QCoreApplication::requestPermission(const QPermission &permission, Functor &&functor)
还是 QtAndroidPrivate::requestPermission
QFutureQtAndroidPrivate::PermissionResult QtAndroidPrivate::requestPermission(const QString &permission)
从官方库接口定义来说 权限请求都是异步的,或者QFuture或者设置槽函数。
2. Android 开发文档
提供了onRequestPermissionsResult 用于当用户同意权限或者拒绝权限之后的调用
其实可以想象得到,当申请权限时,需要等待用户点击, 所以这是需要一个过程的。
3. 参考Qt示例中的方式
举例如下, 请求权限, 请求完毕之后再回调init初始化,
下面是一个camera的请求权限示例,当checkPremission函数检查权限完毕之后, 没有权限则调用requestPremission申请权限,申请完毕之后槽函数还是init,再执行checkPremission... , 直到用户同意权限申请。
cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#ifdef Q_OS_ANDROID
#include <QPermissions>
#endif
#include <QCameraDevice>
#include <QCamera>
#include <QImageCapture>
#include <QMediaCaptureSession>
#include <QMediaDevices>
#include <QMediaMetaData>
#include <QMediaRecorder>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
init();
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::init()
{
#ifdef Q_OS_ANDROID
QCameraPermission cameraPermission;
switch (qApp->checkPermission(cameraPermission))
{
case Qt::PermissionStatus::Undetermined:
qApp->requestPermission(cameraPermission, this, &MainWindow::init);
qDebug() << "requestPermission...";
return;
case Qt::PermissionStatus::Denied:
qWarning("Camera permission is not granted!");
return;
case Qt::PermissionStatus::Granted:
break;
}
#endif
setCamera(QMediaDevices::defaultVideoInput());
}
void MainWindow::setCamera(const QCameraDevice &cameraDevice)
{
m_camera.reset(new QCamera(cameraDevice));
m_captureSession.setCamera(m_camera.data());
connect(m_camera.data(), &QCamera::activeChanged,
this, [=]()
{
qDebug().noquote() << "[camera] activeChanged";
});
connect(m_camera.data(), &QCamera::errorOccurred,
this, [=]()
{
qDebug().noquote() << "[camera] errorOccurred: " << m_camera->errorString();
});
if (!m_imageCapture) {
m_imageCapture.reset(new QImageCapture);
m_captureSession.setImageCapture(m_imageCapture.get());
connect(m_imageCapture.get(), &QImageCapture::readyForCaptureChanged,
this, [=]()
{
qDebug().noquote() << "[imageCapture] readyForCaptureChanged";
});
connect(m_imageCapture.get(), &QImageCapture::imageCaptured,
this, [=]()
{
qDebug().noquote() << "[imageCapture] imageCaptured";
});
connect(m_imageCapture.get(), &QImageCapture::imageSaved,
this, [=]()
{
qDebug().noquote() << "[imageCapture] imageSaved";
});
connect(m_imageCapture.get(), &QImageCapture::errorOccurred,
this, [=]()
{
qDebug().noquote() << "[imageCapture] errorOccurred: " << m_imageCapture->errorString() ;
});
}
m_captureSession.setVideoOutput(ui->videoWidget);
m_camera->start();
}