QGroundControl
Ground Control Station for MAVLink Drones
Loading...
Searching...
No Matches
AndroidInterface.cc
Go to the documentation of this file.
1#include "AndroidInterface.h"
2
3#include <QAndroidScreen.h>
4#include <QtAndroidHelpers/QAndroidPartialWakeLocker.h>
5#include <QtAndroidHelpers/QAndroidWiFiLocker.h>
6#include <QtCore/QCoreApplication>
7#include <QtCore/QDir>
8#include <QtCore/QFileInfo>
9#include <QtCore/QJniEnvironment>
10#include <QtCore/QJniObject>
11#include <QtCore/QMetaObject>
12#include <QtCore/QSharedPointer>
13#include <QtCore/QStandardPaths>
14#include <QtCore/private/qandroidextras_p.h>
15
16#include "AppSettings.h"
17#include "QGCApplication.h"
18#include "QGCLoggingCategory.h"
19#include "SettingsFact.h"
20#include "SettingsManager.h"
21
22QGC_LOGGING_CATEGORY(AndroidInterfaceLog, "Android.AndroidInterface")
23// What the Java side of the USB serial ports logs, so that it is switched on with the other serial categories.
24QGC_LOGGING_CATEGORY(AndroidSerialJavaLog, "Android.AndroidSerial.Java")
25
27
28static std::function<void(const QString&)> s_importCallback;
29
32static const QLoggingCategory& javaLogCategory(const QString& message)
33{
34 return message.startsWith(QLatin1String("QGCUsbSerial")) ? AndroidSerialJavaLog() : AndroidInterfaceLog();
35}
36
37static void jniLogDebug(JNIEnv*, jobject, jstring message)
38{
39 const QString text = QJniObject(message).toString();
40 qCDebug(javaLogCategory(text)).noquote() << text;
41}
42
43static void jniLogWarning(JNIEnv*, jobject, jstring message)
44{
45 const QString text = QJniObject(message).toString();
46 qCWarning(javaLogCategory(text)).noquote() << text;
47}
48
49static void jniStoragePermissionsResult(JNIEnv*, jobject, jboolean granted)
50{
51 if (!qgcApp()) {
52 return;
53 }
54
55 if (!granted) {
56 qCWarning(AndroidInterfaceLog) << "Storage permission request denied; disabling save to SD card";
57
58 (void)QMetaObject::invokeMethod(
59 qgcApp(),
60 []() {
61 SettingsManager* const settingsManager = SettingsManager::instance();
62 if (!settingsManager) {
63 return;
64 }
65
66 AppSettings* const appSettings = settingsManager->appSettings();
67 if (!appSettings) {
68 return;
69 }
70
71 if (!appSettings->androidDontSaveToSDCard()->rawValue().toBool()) {
72 appSettings->androidDontSaveToSDCard()->setRawValue(true);
73 }
74 },
75 Qt::QueuedConnection);
76 return;
77 }
78
79 (void)QMetaObject::invokeMethod(
80 qgcApp(),
81 []() {
82 SettingsManager* const settingsManager = SettingsManager::instance();
83 if (!settingsManager) {
84 return;
85 }
86
87 AppSettings* const appSettings = settingsManager->appSettings();
88 if (!appSettings || appSettings->androidDontSaveToSDCard()->rawValue().toBool()) {
89 return;
90 }
91
92 SettingsFact* const savePathFact = qobject_cast<SettingsFact*>(appSettings->savePath());
93 if (!savePathFact) {
94 return;
95 }
96
97 const QString appName = QCoreApplication::applicationName();
98 const QString currentSavePath = savePathFact->rawValue().toString();
99 const QString internalBasePath = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation);
100 const QString internalSavePath = QDir(internalBasePath).filePath(appName);
101
102 if (!currentSavePath.isEmpty() && (currentSavePath != internalSavePath)) {
103 return;
104 }
105
106 const QString sdCardRootPath = getSDCardPath();
107 if (sdCardRootPath.isEmpty() || !QDir(sdCardRootPath).exists() || !QFileInfo(sdCardRootPath).isWritable()) {
108 return;
109 }
110
111 const QString sdSavePath = QDir(sdCardRootPath).filePath(appName);
112 if (currentSavePath != sdSavePath) {
113 qCDebug(AndroidInterfaceLog) << "Applying SD card save path after permission grant:" << sdSavePath;
114 savePathFact->setRawValue(sdSavePath);
115 }
116 },
117 Qt::QueuedConnection);
118}
119
120static void jniOnImportResult(JNIEnv* env, jobject, jstring filePathA)
121{
122 const char* const filePathCStr = env->GetStringUTFChars(filePathA, nullptr);
123 const QString filePath = QString::fromUtf8(filePathCStr);
124 env->ReleaseStringUTFChars(filePathA, filePathCStr);
125 (void)QJniEnvironment::checkAndClearExceptions(env);
126 auto callback = std::move(s_importCallback);
127 if (!callback) {
128 return;
129 }
130 callback(filePath);
131}
132
134{
135 qCDebug(AndroidInterfaceLog) << "Registering Native Functions";
136
137 const JNINativeMethod javaMethods[]{
138 {"qgcLogDebug", "(Ljava/lang/String;)V", reinterpret_cast<void*>(jniLogDebug)},
139 {"qgcLogWarning", "(Ljava/lang/String;)V", reinterpret_cast<void*>(jniLogWarning)},
140 {"nativeStoragePermissionsResult", "(Z)V", reinterpret_cast<void*>(jniStoragePermissionsResult)},
141 {"onImportResult", "(Ljava/lang/String;)V", reinterpret_cast<void*>(jniOnImportResult)}};
142
143 QJniEnvironment env;
144 if (!env.registerNativeMethods(kJniQGCActivityClassName, javaMethods, std::size(javaMethods))) {
145 qCWarning(AndroidInterfaceLog) << "Failed to register native methods for" << kJniQGCActivityClassName;
146 } else {
147 qCDebug(AndroidInterfaceLog) << "Native Functions Registered";
148 }
149}
150
152{
153 const bool hasPermission =
154 QJniObject::callStaticMethod<jboolean>(kJniQGCActivityClassName, "checkStoragePermissions", "()Z");
155 QJniEnvironment env;
156 if (env.checkAndClearExceptions()) {
157 qCWarning(AndroidInterfaceLog) << "Exception in checkStoragePermissions";
158 return false;
159 }
160
161 if (hasPermission) {
162 qCDebug(AndroidInterfaceLog) << "Storage permissions granted";
163 } else {
164 qCWarning(AndroidInterfaceLog) << "Storage permissions not granted";
165 }
166
167 return hasPermission;
168}
169
171{
173 qCWarning(AndroidInterfaceLog) << "Storage Permission Denied";
174 return QString();
175 }
176
177 const QJniObject result =
178 QJniObject::callStaticObjectMethod(kJniQGCActivityClassName, "getSDCardPath", "()Ljava/lang/String;");
179 QJniEnvironment env;
180 if (env.checkAndClearExceptions()) {
181 qCWarning(AndroidInterfaceLog) << "Exception in getSDCardPath";
182 return QString();
183 }
184 if (!result.isValid()) {
185 qCWarning(AndroidInterfaceLog) << "Call to java getSDCardPath failed: Invalid Result";
186 return QString();
187 }
188
189 return result.toString();
190}
191
192void openFileImportDialog(const QString& destPath, std::function<void(const QString&)> callback)
193{
194 s_importCallback = std::move(callback);
195
196 const QJniObject jDestPath = QJniObject::fromString(destPath);
197 QJniObject::callStaticMethod<void>(
199 "openFileImportDialog",
200 "(Ljava/lang/String;)V",
201 jDestPath.object<jstring>());
202
203 QJniEnvironment env;
204 if (env.checkAndClearExceptions()) {
205 qCWarning(AndroidInterfaceLog) << "Exception in openFileImportDialog";
206 if (s_importCallback) {
207 auto cb = std::move(s_importCallback);
208 cb(QString());
209 }
210 }
211}
212
213static QSharedPointer<QLocks::QLockBase> s_partialWakeLock;
214static QSharedPointer<QLocks::QLockBase> s_wifiLock;
215
216void setKeepScreenOn(bool on)
217{
218 if (!QAndroidScreen::instance()) {
219 new QAndroidScreen(QCoreApplication::instance());
220 }
221 QAndroidScreen::instance()->keepScreenOn(on);
222
223 if (on) {
224 s_partialWakeLock = QAndroidPartialWakeLocker::instance().getLock();
225 s_wifiLock = QAndroidWiFiLocker::instance().getLock();
226 } else {
227 s_partialWakeLock.reset();
228 s_wifiLock.reset();
229 }
230}
231
232void setBackgroundWork(BackgroundWork work, bool active)
233{
234 static int s_activeWork = 0;
235 static QSharedPointer<QLocks::QLockBase> s_backgroundWakeLock;
236 static QSharedPointer<QLocks::QLockBase> s_backgroundWifiLock;
237
238 const bool wasActive = (s_activeWork != 0);
239 if (active) {
240 s_activeWork |= static_cast<int>(work);
241 } else {
242 s_activeWork &= ~static_cast<int>(work);
243 }
244 const bool isActive = (s_activeWork != 0);
245 if (isActive == wasActive) {
246 return;
247 }
248
249 if (isActive) {
250 s_backgroundWakeLock = QAndroidPartialWakeLocker::instance().getLock();
251 s_backgroundWifiLock = QAndroidWiFiLocker::instance().getLock();
252 const QJniObject channelName =
253 QJniObject::fromString(QCoreApplication::translate("AndroidInterface", "Background activity"));
254 const QJniObject title = QJniObject::fromString(
255 QCoreApplication::translate("AndroidInterface", "%1 is running").arg(QCoreApplication::applicationName()));
256 const QJniObject text = QJniObject::fromString(QCoreApplication::translate(
257 "AndroidInterface", "Active in the background while a vehicle is connected or video is recording."));
258 QJniObject::callStaticMethod<void>(kJniQGCActivityClassName, "startBackgroundWork",
259 "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V",
260 channelName.object<jstring>(), title.object<jstring>(),
261 text.object<jstring>());
262 } else {
263 s_backgroundWakeLock.reset();
264 s_backgroundWifiLock.reset();
265 QJniObject::callStaticMethod<void>(kJniQGCActivityClassName, "stopBackgroundWork", "()V");
266 }
267 QJniEnvironment env;
268 if (env.checkAndClearExceptions()) {
269 qCWarning(AndroidInterfaceLog) << "Exception while" << (isActive ? "starting" : "stopping")
270 << "the foreground service";
271 }
272
273 // Android 13+ shows the service's notification only once the user has allowed notifications; the service runs
274 // either way. Asked once a run: Android shows its dialog only until the user has answered it.
275 static bool s_askedForNotifications = false;
276 if (isActive && !s_askedForNotifications && (QNativeInterface::QAndroidApplication::sdkVersion() >= 33)) {
277 s_askedForNotifications = true;
278 (void) QtAndroidPrivate::requestPermission(QStringLiteral("android.permission.POST_NOTIFICATIONS"));
279 }
280}
281
282} // namespace AndroidInterface
#define qgcApp()
#define QGC_LOGGING_CATEGORY(name, categoryStr)
Application Settings.
Definition AppSettings.h:10
void setRawValue(const QVariant &value)
Definition Fact.cc:135
QVariant rawValue() const
Definition Fact.h:87
A SettingsFact is Fact which holds a QSettings value.
Provides access to all app settings.
static SettingsManager * instance()
AppSettings * appSettings() const
static void jniOnImportResult(JNIEnv *env, jobject, jstring filePathA)
static void jniLogDebug(JNIEnv *, jobject, jstring message)
static const QLoggingCategory & javaLogCategory(const QString &message)
static void jniStoragePermissionsResult(JNIEnv *, jobject, jboolean granted)
static std::function< void(const QString &)> s_importCallback
static void jniLogWarning(JNIEnv *, jobject, jstring message)
void setBackgroundWork(BackgroundWork work, bool active)
static QSharedPointer< QLocks::QLockBase > s_wifiLock
void openFileImportDialog(const QString &destPath, std::function< void(const QString &)> callback)
BackgroundWork
What should go on while the app is in the background, where Android freezes an app and cuts its netwo...
void setKeepScreenOn(bool on)
constexpr const char * kJniQGCActivityClassName
static QSharedPointer< QLocks::QLockBase > s_partialWakeLock