summaryrefslogtreecommitdiff
path: root/src/bluetooth/android/androidutils.cpp
blob: 7c99bad3ff1cf071a06ba190bba50f8e209580b1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// Copyright (C) 2022 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only

#include "androidutils_p.h"
#include "jni_android_p.h"

#include <QtCore/QLoggingCategory>
#include <QtCore/private/qandroidextras_p.h>

QT_BEGIN_NAMESPACE

Q_DECLARE_LOGGING_CATEGORY(QT_BT_ANDROID)

static QString androidPermissionString(BluetoothPermission permission)
{
    switch (permission) {
    case BluetoothPermission::Scan:
        return {QStringLiteral("android.permission.BLUETOOTH_SCAN")};
    case BluetoothPermission::Advertise:
        return {QStringLiteral("android.permission.BLUETOOTH_ADVERTISE")};
    case BluetoothPermission::Connect:
        return {QStringLiteral("android.permission.BLUETOOTH_CONNECT")};
    }
    return {};
}

bool ensureAndroidPermission(BluetoothPermission permission)
{
    // The current set of permissions are only applicable with 31+
    if (QNativeInterface::QAndroidApplication::sdkVersion() < 31)
        return true;

    const auto permString = androidPermissionString(permission);

    // First check if we have the permission already
    if (QtAndroidPrivate::checkPermission(permString).result() == QtAndroidPrivate::Authorized)
        return true;

     qCWarning(QT_BT_ANDROID) << "Permission not authorized:" << permString;
     return false;
}

QJniObject getDefaultBluetoothAdapter()
{
    QJniObject service = QJniObject::getStaticField<QtJniTypes::AndroidContext, jstring>(
                                   "BLUETOOTH_SERVICE");
    QJniObject context = QNativeInterface::QAndroidApplication::context();
    QJniObject manager =
            context.callMethod<jobject>("getSystemService", service.object<jstring>());
    QJniObject adapter;
    if (manager.isValid())
        adapter = manager.callMethod<QtJniTypes::BluetoothAdapter>("getAdapter");

    // ### Qt 7 check if the below double-get of the adapter can be removed.
    // It is a workaround for QTBUG-57489, fixed in 2016. According to the bug it occurred on
    // a certain device running Android 6.0.1 (Qt 6 supports Android 6.0 as the minimum).
    // For completeness: the original workaround was for the deprecated getDefaultAdapter()
    // method, and it is thus unclear if this is needed even in Qt 6 anymore. In addition the
    // impacted device is updateable to Android 8 which may also have fixed the issue.
    if (!adapter.isValid())
        adapter = manager.callMethod<QtJniTypes::BluetoothAdapter>("getAdapter");

    return adapter;
}

QT_END_NAMESPACE